hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
b4f15544ccbf06ddbe8f7b61117269c3d27a9229
16,716
hpp
C++
include/nsimd/cxx_adv_api.hpp
eschnett/nsimd
11a58156ac8f1d8b60f1112c41efd9ef91d91c3d
[ "MIT" ]
null
null
null
include/nsimd/cxx_adv_api.hpp
eschnett/nsimd
11a58156ac8f1d8b60f1112c41efd9ef91d91c3d
[ "MIT" ]
null
null
null
include/nsimd/cxx_adv_api.hpp
eschnett/nsimd
11a58156ac8f1d8b60f1112c41efd9ef91d91c3d
[ "MIT" ]
null
null
null
/* Copyright (c) 2019 Agenium Scale Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef NSIMD_CXX_ADV_API_HPP #define NSIMD_CXX_ADV_API_HPP #include <nsimd/nsimd.h> #include <ostream> namespace nsimd { // ---------------------------------------------------------------------------- // For ARM SVE we need a special struct #ifdef NSIMD_SVE #define NSIMD_STRUCT __sizeless_struct #else #define NSIMD_STRUCT struct #endif // ---------------------------------------------------------------------------- // Definition of pack template <typename T, int N = 1, typename SimdExt = NSIMD_SIMD> NSIMD_STRUCT pack; template <typename T, typename SimdExt> NSIMD_STRUCT pack<T, 1, SimdExt> { typedef typename simd_traits<T, SimdExt>::simd_vector simd_vector; typedef T value_type; typedef SimdExt simd_ext; static const int unroll = 1; simd_vector car; // Default ctor pack() {} // Ctor that splats template <typename S> pack(S const &s) { car = set1(T(s), T(), SimdExt()); } // Ctor taking a SIMD vector pack(simd_vector v) { car = v; } // Underlying native SIMD vector getter simd_vector native_register() const { return car; } friend std::ostream &operator<<(std::ostream &os, pack const &a0) { T buf[max_len_t<T>::value]; storeu(buf, a0.car, T(), SimdExt()); os << "{ "; int n = len(a0); for (int i = 0; i < n; i++) { os << buf[i]; if (i < n - 1) { os << ", "; } } os << " }"; return os; } }; template <typename T, int N, typename SimdExt> NSIMD_STRUCT pack { typedef typename simd_traits<T, SimdExt>::simd_vector simd_vector; typedef T value_type; typedef SimdExt simd_ext; static const int unroll = N; simd_vector car; pack<T, N - 1, SimdExt> cdr; // Default ctor pack() {} // Ctor that splats template <typename S> pack(S const &s) : cdr(s) { car = set1(T(s), T(), SimdExt()); } friend std::ostream &operator<<(std::ostream &os, pack const &a0) { os << pack<T, 1, SimdExt>(a0.car) << ", " << a0.cdr; return os; } }; // ---------------------------------------------------------------------------- // Definition of logical template <typename T, int N = 1, typename SimdExt = NSIMD_SIMD> NSIMD_STRUCT packl; template <typename T, typename SimdExt> NSIMD_STRUCT packl<T, 1, SimdExt> { typedef typename simd_traits<T, SimdExt>::simd_vectorl simd_vectorl; simd_vectorl car; // Default ctor packl() {} // Ctor taking a SIMD vector packl(simd_vectorl v) { car = v; } // Underlying native SIMD vector getter simd_vectorl native_register() const { return car; } typedef T value_type; typedef SimdExt simd_ext; static const int unroll = 1; }; template <typename T, int N, typename SimdExt> NSIMD_STRUCT packl { typename simd_traits<T, SimdExt>::simd_vectorl car; packl<T, N - 1, SimdExt> cdr; typedef T value_type; typedef SimdExt simd_ext; static const int unroll = N; }; // ---------------------------------------------------------------------------- // Definition of SOA of degree 2 template <typename T, int N = 1, typename SimdExt = NSIMD_SIMD> NSIMD_STRUCT packx2; template <typename T, typename SimdExt> NSIMD_STRUCT packx2<T, 1, SimdExt> { typedef typename simd_traits<T, SimdExt>::simd_vector simd_vector; typedef T value_type; typedef SimdExt simd_ext; static const int unroll = 1; pack<T, 1, SimdExt> v0; pack<T, 1, SimdExt> v1; void set_car(simd_vector v0_, simd_vector v1_) { v0.car = v0_; v1.car = v1_; } }; template <typename T, int N, typename SimdExt> NSIMD_STRUCT packx2 { typedef typename simd_traits<T, SimdExt>::simd_vector simd_vector; typedef T value_type; typedef SimdExt simd_ext; static const int unroll = N; pack<T, N, SimdExt> v0; pack<T, N, SimdExt> v1; void set_car(simd_vector v0_, simd_vector v1_) { v0.car = v0_; v1.car = v1_; } void set_cdr(pack<T, N - 1, SimdExt> const &v0_, pack<T, N - 1, SimdExt> const &v1_) { v0.cdr = v0_; v1.cdr = v1_; } }; // ---------------------------------------------------------------------------- // Definition of SOA of degree 3 template <typename T, int N = 1, typename SimdExt = NSIMD_SIMD> NSIMD_STRUCT packx3; template <typename T, typename SimdExt> NSIMD_STRUCT packx3<T, 1, SimdExt> { typedef typename simd_traits<T, SimdExt>::simd_vector simd_vector; typedef T value_type; typedef SimdExt simd_ext; static const int unroll = 1; pack<T, 1, SimdExt> v0; pack<T, 1, SimdExt> v1; pack<T, 1, SimdExt> v2; void set_car(simd_vector v0_, simd_vector v1_, simd_vector v2_) { v0.car = v0_; v1.car = v1_; v2.car = v2_; } }; template <typename T, int N, typename SimdExt> NSIMD_STRUCT packx3 { typedef typename simd_traits<T, SimdExt>::simd_vector simd_vector; typedef T value_type; typedef SimdExt simd_ext; static const int unroll = N; pack<T, N, SimdExt> v0; pack<T, N, SimdExt> v1; pack<T, N, SimdExt> v2; void set_car(simd_vector v0_, simd_vector v1_, simd_vector v2_) { v0.car = v0_; v1.car = v1_; v2.car = v2_; } void set_cdr(pack<T, N - 1, SimdExt> const &v0_, pack<T, N - 1, SimdExt> const &v1_, pack<T, N - 1, SimdExt> const &v2_) { v0.cdr = v0_; v1.cdr = v1_; v2.cdr = v2_; } }; // ---------------------------------------------------------------------------- // Definition of SOA of degree 4 template <typename T, int N = 1, typename SimdExt = NSIMD_SIMD> NSIMD_STRUCT packx4; template <typename T, typename SimdExt> NSIMD_STRUCT packx4<T, 1, SimdExt> { typedef typename simd_traits<T, SimdExt>::simd_vector simd_vector; typedef T value_type; typedef SimdExt simd_ext; static const int unroll = 1; pack<T, 1, SimdExt> v0; pack<T, 1, SimdExt> v1; pack<T, 1, SimdExt> v2; pack<T, 1, SimdExt> v3; void set_car(simd_vector v0_, simd_vector v1_, simd_vector v2_, simd_vector v3_) { v0.car = v0_; v1.car = v1_; v2.car = v2_; v3.car = v3_; } }; template <typename T, int N, typename SimdExt> NSIMD_STRUCT packx4 { typedef typename simd_traits<T, SimdExt>::simd_vector simd_vector; typedef T value_type; typedef SimdExt simd_ext; static const int unroll = N; pack<T, N, SimdExt> v0; pack<T, N, SimdExt> v1; pack<T, N, SimdExt> v2; pack<T, N, SimdExt> v3; void set_car(simd_vector v0_, simd_vector v1_, simd_vector v2_, simd_vector v3_) { v0.car = v0_; v1.car = v1_; v2.car = v2_; v3.car = v3_; } void set_cdr(pack<T, N - 1, SimdExt> const &v0_, pack<T, N - 1, SimdExt> const &v1_, pack<T, N - 1, SimdExt> const &v2_, pack<T, N - 1, SimdExt> const &v3_) { v0.cdr = v0_; v1.cdr = v1_; v2.cdr = v2_; v3.cdr = v3_; } }; // ---------------------------------------------------------------------------- // The len function cannot be auto-generated template <typename T, int N, typename SimdExt> int len(pack<T, N, SimdExt> const &) { return N * len(T(), SimdExt()); } template <typename T, int N, typename SimdExt> int len(packl<T, N, SimdExt> const &) { return N * len(T(), SimdExt()); } template <typename T, int N, typename SimdExt> int len(packx2<T, N, SimdExt> const &) { return 2 * N * len(T(), SimdExt()); } template <typename T, int N, typename SimdExt> int len(packx3<T, N, SimdExt> const &) { return 3 * N * len(T(), SimdExt()); } template <typename T, int N, typename SimdExt> int len(packx4<T, N, SimdExt> const &) { return 4 * N * len(T(), SimdExt()); } // ---------------------------------------------------------------------------- // The addv function cannot be auto-generated template <typename T, typename SimdExt> T addv(pack<T, 1, SimdExt> const &a0) { return addv(a0.car, T(), SimdExt()); } template <typename T, int N, typename SimdExt> T addv(pack<T, N, SimdExt> const &a0) { return addv(a0.car, T(), SimdExt()) + addv(a0.cdr); } // ---------------------------------------------------------------------------- // The all function cannot be auto-generated template <typename T, typename SimdExt> int all(packl<T, 1, SimdExt> const &a0) { return all(a0.car, T(), SimdExt()); } template <typename T, int N, typename SimdExt> int all(packl<T, N, SimdExt> const &a0) { return all(a0.car, T(), SimdExt()) && all(a0.cdr); } // ---------------------------------------------------------------------------- // The any function cannot be auto-generated template <typename T, typename SimdExt> int any(packl<T, 1, SimdExt> const &a0) { return any(a0.car, T(), SimdExt()); } template <typename T, int N, typename SimdExt> int any(packl<T, N, SimdExt> const &a0) { return any(a0.car, T(), SimdExt()) || any(a0.cdr); } // ---------------------------------------------------------------------------- // The nbtrue function cannot be auto-generated template <typename T, typename SimdExt> int nbtrue(packl<T, 1, SimdExt> const &a0) { return nbtrue(a0.car, T(), SimdExt()); } template <typename T, int N, typename SimdExt> int nbtrue(packl<T, N, SimdExt> const &a0) { return nbtrue(a0.car, T(), SimdExt()) + nbtrue(a0.cdr); } // ---------------------------------------------------------------------------- // Include functions that act on packs } // namespace nsimd #include <nsimd/cxx_adv_api_functions.hpp> namespace nsimd { // ---------------------------------------------------------------------------- // The if_else function cannot be auto-generated template <typename L, typename T, typename SimdExt> pack<T, 1, SimdExt> if_else(packl<L, 1, SimdExt> const &a0, pack<T, 1, SimdExt> const &a1, pack<T, 1, SimdExt> const &a2) { pack<T, 1, SimdExt> ret; ret.car = if_else(a0.car, a1.car, a2.car, L(), T(), SimdExt()); return ret; } template <typename L, typename T, int N, typename SimdExt> pack<T, N, SimdExt> if_else(packl<L, N, SimdExt> const &a0, pack<T, N, SimdExt> const &a1, pack<T, N, SimdExt> const &a2) { pack<T, N, SimdExt> ret; ret.car = if_else(a0.car, a1.car, a2.car, L(), T(), SimdExt()); ret.cdr = if_else(a0.cdr, a1.cdr, a2.cdr); return ret; } // ---------------------------------------------------------------------------- // Loads/Stores templated on the alignment cannot be auto-generated namespace detail { template <typename SimdVector, typename Alignment> struct load_helper {}; template <typename SimdVector> struct load_helper<SimdVector, aligned> { template <typename A0> static SimdVector load(A0 a0) { return loada<SimdVector, A0>(a0); } template <typename A0> static SimdVector loadl(A0 a0) { return loadla<SimdVector, A0>(a0); } template <typename A0> static SimdVector load2(A0 a0) { return load2a<SimdVector, A0>(a0); } template <typename A0> static SimdVector load3(A0 a0) { return load3a<SimdVector, A0>(a0); } template <typename A0> static SimdVector load4(A0 a0) { return load4a<SimdVector, A0>(a0); } }; template <typename SimdVector> struct load_helper<SimdVector, unaligned> { template <typename A0> static SimdVector load(A0 a0) { return loadu<SimdVector, A0>(a0); } template <typename A0> static SimdVector loadl(A0 a0) { return loadlu<SimdVector, A0>(a0); } template <typename A0> static SimdVector load2(A0 a0) { return load2u<SimdVector, A0>(a0); } template <typename A0> static SimdVector load3(A0 a0) { return load3u<SimdVector, A0>(a0); } template <typename A0> static SimdVector load4(A0 a0) { return load4u<SimdVector, A0>(a0); } }; template <typename SimdVector, typename Alignment> struct store_helper {}; template <typename SimdVector> struct store_helper<SimdVector, aligned> { template <typename A0, typename A1> static SimdVector store(A0 a0, A1 a1) { storea<SimdVector, A0, A1>(a0, a1); } template <typename A0, typename A1> static SimdVector storel(A0 a0, A1 a1) { storela<SimdVector, A0, A1>(a0, a1); } template <typename A0, typename A1, typename A2> static SimdVector store2(A0 a0, A1 a1, A2 a2) { store2a<SimdVector, A0, A1, A2>(a0, a1, a2); } template <typename A0, typename A1, typename A2, typename A3> static SimdVector store3(A0 a0, A1 a1, A2 a2, A3 a3) { store3a<SimdVector, A0, A1, A2, A3>(a0, a1, a2, a3); } template <typename A0, typename A1, typename A2, typename A3, typename A4> static SimdVector store4(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { store4a<SimdVector, A0>(a0, a1, a2, a3, a4); } }; template <typename SimdVector> struct store_helper<SimdVector, unaligned> { template <typename A0, typename A1> static SimdVector store(A0 a0, A1 a1) { storeu<SimdVector, A0, A1>(a0, a1); } template <typename A0, typename A1> static SimdVector storel(A0 a0, A1 a1) { storelu<SimdVector, A0, A1>(a0, a1); } template <typename A0, typename A1, typename A2> static SimdVector store2(A0 a0, A1 a1, A2 a2) { store2u<SimdVector, A0, A1, A2>(a0, a1, a2); } template <typename A0, typename A1, typename A2, typename A3> static SimdVector store3(A0 a0, A1 a1, A2 a2, A3 a3) { store3u<SimdVector, A0, A1, A2, A3>(a0, a1, a2, a3); } template <typename A0, typename A1, typename A2, typename A3, typename A4> static SimdVector store4(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { store4u<SimdVector, A0>(a0, a1, a2, a3, a4); } }; } // namespace detail template <typename SimdVector, typename Alignment, typename A0> SimdVector load(A0 a0) { return detail::load_helper<SimdVector, Alignment>::load(a0); } template <typename SimdVector, typename Alignment, typename A0> SimdVector loadl(A0 a0) { return detail::load_helper<SimdVector, Alignment>::loadl(a0); } template <typename SimdVector, typename Alignment, typename A0> SimdVector load2(A0 a0) { return detail::load_helper<SimdVector, Alignment>::load2(a0); } template <typename SimdVector, typename Alignment, typename A0> SimdVector load3(A0 a0) { return detail::load_helper<SimdVector, Alignment>::load3(a0); } template <typename SimdVector, typename Alignment, typename A0> SimdVector load4(A0 a0) { return detail::load_helper<SimdVector, Alignment>::load4(a0); } template <typename SimdVector, typename Alignment, typename A0, typename A1> SimdVector store(A0 a0, A1 a1) { detail::store_helper<SimdVector, Alignment>::store(a0, a1); } template <typename SimdVector, typename Alignment, typename A0, typename A1> SimdVector storel(A0 a0, A1 a1) { return detail::store_helper<SimdVector, Alignment>::storel(a0, a1); } template <typename SimdVector, typename Alignment, typename A0, typename A1, typename A2> SimdVector store2(A0 a0, A1 a1, A2 a2) { return detail::store_helper<SimdVector, Alignment>::store2(a0, a1, a2); } template <typename SimdVector, typename Alignment, typename A0, typename A1, typename A2, typename A3> SimdVector store3(A0 a0, A1 a1, A2 a2, A3 a3) { return detail::store_helper<SimdVector, Alignment>::store3(a0, a1, a2, a3); } template <typename SimdVector, typename Alignment, typename A0, typename A1, typename A2, typename A3, typename A4> SimdVector store4(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { return detail::store_helper<SimdVector, Alignment>::store4(a0, a1, a2, a3, a4); } // ---------------------------------------------------------------------------- template <typename T> T native_register(T a) { return a; } template <typename T, typename SimdExt> typename pack<T, 1, SimdExt>::simd_vector native_register(pack<T, 1, SimdExt> const &a) { return a.car; } } // namespace nsimd #endif
29.121951
79
0.626825
eschnett
b4f3985c4624b9a1e4df3f507e1c601182aad782
46,815
hpp
C++
include/internal/iutest_genparams.hpp
BuildJet/iutest
7d92bc1957b8e1815bde55f5aa36171197518adc
[ "BSD-3-Clause" ]
null
null
null
include/internal/iutest_genparams.hpp
BuildJet/iutest
7d92bc1957b8e1815bde55f5aa36171197518adc
[ "BSD-3-Clause" ]
null
null
null
include/internal/iutest_genparams.hpp
BuildJet/iutest
7d92bc1957b8e1815bde55f5aa36171197518adc
[ "BSD-3-Clause" ]
null
null
null
//====================================================================== //----------------------------------------------------------------------- /** * @file iutest_genparams.hpp * @brief iris unit test parameter generator * * @author t.shirayanagi * @par copyright * Copyright (C) 2011-2021, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== #ifndef INCG_IRIS_IUTEST_GENPARAMS_HPP_7845F59A_825C_426A_B451_573245408998_ #define INCG_IRIS_IUTEST_GENPARAMS_HPP_7845F59A_825C_426A_B451_573245408998_ #if IUTEST_HAS_PARAM_TEST namespace iutest { namespace detail { //====================================================================== // declare #if IUTEST_HAS_CONCAT template<typename Generator1, typename Generator2>class iuConcatParamHolder; #endif //====================================================================== // class /** * @brief パラメータ生成器インターフェイス */ template<typename T> class iuIParamGenerator { public: typedef T type; public: typedef iuIParamGenerator<T>* (*Generator)(); public: virtual ~iuIParamGenerator() {} public: virtual void Begin() = 0; //!< パラメータリストの先頭に移動 virtual T GetCurrent() const = 0; //!< 現在のパラメータを取得 virtual void Next() = 0; //!< パラメータを取得して次に移動 virtual bool IsEnd() const = 0; //!< パラメータリストの終端にいるかどうか }; /** * @brief パラメータ生成器保持クラス */ template<typename T> class iuParamGenerator IUTEST_CXX_FINAL : public iuIParamGenerator<T> { typedef iuIParamGenerator<T> _Interface; typedef iuParamGenerator<T> _Myt; public: typedef T type; public: iuParamGenerator(_Interface* pInterface=NULL) : m_pInterface(pInterface) {} // NOLINT public: operator iuIParamGenerator<T>* () const { return m_pInterface; } public: #if IUTEST_HAS_CONCAT template<typename Other> iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const { return iuConcatParamHolder<_Myt, Other>(*this, g); } #endif public: virtual void Begin() IUTEST_CXX_OVERRIDE { m_pInterface->Begin(); } virtual T GetCurrent() const IUTEST_CXX_OVERRIDE { return m_pInterface->GetCurrent(); } virtual void Next() IUTEST_CXX_OVERRIDE { m_pInterface->Next(); } virtual bool IsEnd() const IUTEST_CXX_OVERRIDE { return m_pInterface->IsEnd(); } private: _Interface* m_pInterface; }; /** * @brief 範囲パラメータ生成器 * @tparam T = パラメータ型 */ template<typename T> class iuRangeParamsGenerator IUTEST_CXX_FINAL : public iuIParamGenerator<T> { T m_begin; T m_end; T m_step; T m_cur; public: /** * @brief コンストラクタ * @param [in] begin = 開始値 * @param [in] end = 終了値 * @param [in] step = 増値 */ iuRangeParamsGenerator(T begin, T end, T step) : m_begin(begin) , m_end(end) , m_step(step) , m_cur(begin) { } public: virtual void Begin() IUTEST_CXX_OVERRIDE { m_cur = m_begin; } virtual T GetCurrent() const IUTEST_CXX_OVERRIDE { return m_cur; } virtual void Next() IUTEST_CXX_OVERRIDE { m_cur = static_cast<T>(m_cur + m_step); } virtual bool IsEnd() const IUTEST_CXX_OVERRIDE { return !(m_cur < m_end); } }; /** * @brief 真偽値パラメータ生成器 */ class iuBoolParamsGenerator IUTEST_CXX_FINAL : public iuIParamGenerator<bool> { int m_n; bool m_cur; public: iuBoolParamsGenerator() : m_n(0) , m_cur(false) {} public: virtual void Begin() IUTEST_CXX_OVERRIDE { m_cur = false; m_n = 0; } virtual bool GetCurrent() const IUTEST_CXX_OVERRIDE { return m_cur; } virtual void Next() IUTEST_CXX_OVERRIDE { ++m_n; m_cur = !m_cur; } virtual bool IsEnd() const IUTEST_CXX_OVERRIDE { return m_n >= 2; } }; /** * @brief 値配列パラメータ生成器 * @tparam T = パラメータ型 */ template<typename T> class iuValuesInParamsGenerator : public iuIParamGenerator<T> { typedef ::std::vector<T> params_t; params_t m_values; typename params_t::const_iterator m_it; public: explicit iuValuesInParamsGenerator(const params_t& values) : m_values(values) {} template<typename Container> explicit iuValuesInParamsGenerator(const Container& values) { m_values.insert(m_values.end(), values.begin(), values.end()); } #if !defined(IUTEST_NO_FUNCTION_TEMPLATE_ORDERING) template<typename TT, size_t SIZE> explicit iuValuesInParamsGenerator(const TT (&values)[SIZE]) { m_values.insert(m_values.end(), values, values + SIZE); } #endif template<typename Ite> iuValuesInParamsGenerator(Ite begin, Ite end) { m_values.insert(m_values.end(), begin, end); } #if IUTEST_HAS_INITIALIZER_LIST iuValuesInParamsGenerator(::std::initializer_list<T> l) { m_values.insert(m_values.end(), l.begin(), l.end()); } #endif public: virtual void Begin() IUTEST_CXX_OVERRIDE { m_it = m_values.begin(); } virtual T GetCurrent() const IUTEST_CXX_OVERRIDE { return *m_it; } virtual void Next() IUTEST_CXX_OVERRIDE { ++m_it; } virtual bool IsEnd() const IUTEST_CXX_OVERRIDE { return (m_it == m_values.end()); } }; #if IUTEST_HAS_CONCAT /** * @brief パラメータ生成器加算保持クラス */ template<typename G1, typename G2> class iuConcatParamHolder { typedef iuConcatParamHolder<G1, G2> _Myt; public: iuConcatParamHolder(const G1& g1, const G2& g2) : m_g1(g1), m_g2(g2) {} private: iuConcatParamHolder() IUTEST_CXX_DELETED_FUNCTION; public: template<typename T> operator iuIParamGenerator<T>* () { params_t<T> params; params.append(m_g1); params.append(m_g2); return new iuValuesInParamsGenerator<T>(params.val); } template<typename Other> iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const { return iuConcatParamHolder<_Myt, Other>(*this, g); } private: template<typename T> struct params_t { typedef iuIParamGenerator<T> IParamGenerater; ::std::vector<T> val; void append(IParamGenerater* gen) { detail::scoped_ptr<IParamGenerater> p(gen); for( p->Begin(); !p->IsEnd(); p->Next() ) { val.push_back(p->GetCurrent()); } } template<typename U> void append(iuParamGenerator<U>& gen) { for( gen.Begin(); !gen.IsEnd(); gen.Next() ) { val.push_back(static_cast<T>(gen.GetCurrent())); } } }; private: G1 m_g1; G2 m_g2; }; #endif #if IUTEST_HAS_VARIADIC_VALUES template<typename... Args> class iuValueArray { typedef tuples::tuple<Args...> _MyTuple; typedef iuValueArray<Args...> _Myt; template<typename T> struct make_array { T val[sizeof...(Args)]; template<typename U> void operator ()(int index, const U& value) { val[index] = value; } explicit make_array(const _MyTuple& t) { tuples::tuple_foreach(t, *this); } }; public: explicit iuValueArray(const Args&... args) : v(args...) {} #if defined(__clang__) && defined(IUTEST_LIBSTDCXX_VERSION) && IUTEST_LIBSTDCXX_VERSION >= 40900 #if IUTEST_HAS_RVALUE_REFS // https://stackoverflow.com/questions/23374953/why-does-this-exceed-the-maximum-recursive-template-depth iuValueArray(const iuValueArray& rhs) : v(rhs.v) {} iuValueArray(iuValueArray&& rhs) : v(rhs.v) {} #endif #endif public: template<typename T> operator iuIParamGenerator<T>* () const { make_array<T> ar(v); #if !defined(IUTEST_NO_FUNCTION_TEMPLATE_ORDERING) return new iuValuesInParamsGenerator<T>(ar.val); #else return new iuValuesInParamsGenerator<T>(ar.val, ar.val + IUTEST_PP_COUNTOF(ar.val)); #endif } public: #if IUTEST_HAS_CONCAT template<typename Other> iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const { return iuConcatParamHolder<_Myt, Other>(*this, g); } #endif private: _MyTuple v; }; #else /* template<typename A1, typename A2> class iuValueArray2 { typedef iuValueArray2<A1, A2> _Myt; public: iuValueArray2(A1 a1, A2 a2) : v1(a1), v2(a2) {} public: template<typename T> operator iuIParamGenerator<T>* () const { const T val[] = { static_cast<T>(v1), static_cast<T>(v2) }; return new iuValuesInParamsGenerator<T>(val); } public: template<typename Other> iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const { return iuConcatParamHolder<_Myt, Other>(*this, g); } private: A1 v1; A2 v2; }; */ /** * @private * @{ */ #define IIUT_DECL_VALUEARRAY_CONSTRUCT_(i, p1, p2) IUTEST_PP_CAT(p1, i)(IUTEST_PP_CAT(p2, i)) #define IIUT_DECL_VALUEARRAY_STATICCAST_(i, p1, p2) static_cast<p1>(IUTEST_PP_CAT(p2, i)) #define IIUT_DECL_VALUEARRAY_VARIABLE_(i, p1, p2) IUTEST_PP_CAT(p1, i) IUTEST_PP_CAT(p2, i); #if IUTEST_HAS_CONCAT # define IIUT_DECL_VALUEARRAY_CONCAT_() \ template<typename Other> iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const { \ return iuConcatParamHolder<_Myt, Other>(*this, g); } #else # define IIUT_DECL_VALUEARRAY_CONCAT_() #endif #define IIUT_DECL_VALUEARRAY_(n) \ template< IUTEST_PP_ENUM_PARAMS(n, typename A) > \ class IUTEST_PP_CAT(iuValueArray, n) { \ typedef IUTEST_PP_CAT(iuValueArray, n)< IUTEST_PP_ENUM_PARAMS(n, A) > _Myt; \ public: \ IUTEST_PP_CAT(iuValueArray, n)( IUTEST_PP_ENUM_BINARY_PARAMS(n, A, a) ) \ : IUTEST_PP_ENUM_BINARY(n, IIUT_DECL_VALUEARRAY_CONSTRUCT_, v, a) {} \ template<typename T>operator iuIParamGenerator<T>* () const { \ const T val[] = { IUTEST_PP_ENUM_BINARY(n, IIUT_DECL_VALUEARRAY_STATICCAST_, T, v) }; \ return new iuValuesInParamsGenerator<T>(val); \ } \ IIUT_DECL_VALUEARRAY_CONCAT_() \ private: IUTEST_PP_REPEAT_BINARY(n, IIUT_DECL_VALUEARRAY_VARIABLE_, A, v) \ } /** * @} */ IIUT_DECL_VALUEARRAY_(1); IIUT_DECL_VALUEARRAY_(2); IIUT_DECL_VALUEARRAY_(3); IIUT_DECL_VALUEARRAY_(4); IIUT_DECL_VALUEARRAY_(5); IIUT_DECL_VALUEARRAY_(6); IIUT_DECL_VALUEARRAY_(7); IIUT_DECL_VALUEARRAY_(8); IIUT_DECL_VALUEARRAY_(9); IIUT_DECL_VALUEARRAY_(10); IIUT_DECL_VALUEARRAY_(11); IIUT_DECL_VALUEARRAY_(12); IIUT_DECL_VALUEARRAY_(13); IIUT_DECL_VALUEARRAY_(14); IIUT_DECL_VALUEARRAY_(15); IIUT_DECL_VALUEARRAY_(16); IIUT_DECL_VALUEARRAY_(17); IIUT_DECL_VALUEARRAY_(18); IIUT_DECL_VALUEARRAY_(19); IIUT_DECL_VALUEARRAY_(20); IIUT_DECL_VALUEARRAY_(21); IIUT_DECL_VALUEARRAY_(22); IIUT_DECL_VALUEARRAY_(23); IIUT_DECL_VALUEARRAY_(24); IIUT_DECL_VALUEARRAY_(25); IIUT_DECL_VALUEARRAY_(26); IIUT_DECL_VALUEARRAY_(27); IIUT_DECL_VALUEARRAY_(28); IIUT_DECL_VALUEARRAY_(29); IIUT_DECL_VALUEARRAY_(30); IIUT_DECL_VALUEARRAY_(31); IIUT_DECL_VALUEARRAY_(32); IIUT_DECL_VALUEARRAY_(33); IIUT_DECL_VALUEARRAY_(34); IIUT_DECL_VALUEARRAY_(35); IIUT_DECL_VALUEARRAY_(36); IIUT_DECL_VALUEARRAY_(37); IIUT_DECL_VALUEARRAY_(38); IIUT_DECL_VALUEARRAY_(39); IIUT_DECL_VALUEARRAY_(40); IIUT_DECL_VALUEARRAY_(41); IIUT_DECL_VALUEARRAY_(42); IIUT_DECL_VALUEARRAY_(43); IIUT_DECL_VALUEARRAY_(44); IIUT_DECL_VALUEARRAY_(45); IIUT_DECL_VALUEARRAY_(46); IIUT_DECL_VALUEARRAY_(47); IIUT_DECL_VALUEARRAY_(48); IIUT_DECL_VALUEARRAY_(49); IIUT_DECL_VALUEARRAY_(50); #undef IIUT_DECL_VALUEARRAY_CONSTRUCT_ #undef IIUT_DECL_VALUEARRAY_STATICCAST_ #undef IIUT_DECL_VALUEARRAY_VARIABLE_ #undef IIUT_DECL_VALUEARRAY_CONCAT_ #undef IIUT_DECL_VALUEARRAY_ #endif #if IUTEST_HAS_COMBINE #if IUTEST_HAS_VARIADIC_COMBINE template<typename... Args> class iuCartesianProductGenerator IUTEST_CXX_FINAL : public iuIParamGenerator< tuples::tuple<Args...> > { typedef tuples::tuple< iuParamGenerator<Args>... > _MyTuple; static const int kCount = sizeof...(Args); struct begin_func { template<typename T> void operator ()(int, T& value) const { value.Begin(); } }; template<int index, int end, typename Tuple> bool is_end_foreach(Tuple& t , typename detail::enable_if<index != end, void>::type*& = detail::enabler::value ) const { const bool b = tuples::get<index>(t).IsEnd(); return b && is_end_foreach<index+1, end>(t); } template<int index, int end, typename Tuple> bool is_end_foreach(Tuple& , typename detail::enable_if<index == end, void>::type*& = detail::enabler::value ) const { return true; } template<int index, int end, typename Tuple> void next_foreach(Tuple& t , typename detail::enable_if<index != end, void>::type*& = detail::enabler::value ) { next_foreach<index+1, end>(t); if( is_end_foreach<index+1, end>(t) ) { tuples::get<index>(t).Next(); if( !tuples::get<index>(t).IsEnd() ) { tuples::tuple_foreach<index + 1>(t, begin_func()); } } } template<int index, int end, typename Tuple> void next_foreach(Tuple& , typename detail::enable_if<index == end, void>::type*& = detail::enabler::value ) { } template<int index, int end, typename T1, typename ...TArgs> tuples::tuple<T1, TArgs...> current_foreach( typename detail::enable_if<index != end-1, void>::type*& = detail::enabler::value ) const { return ::std::tuple_cat( tuples::tuple<T1>(tuples::get<index>(v).GetCurrent()) , current_foreach<index+1, end, TArgs...>()); } template<int index, int end, typename T1, typename ...TArgs> tuples::tuple<T1> current_foreach( typename detail::enable_if<index == end-1, void>::type*& = detail::enabler::value ) const { return tuples::tuple<T1>(tuples::get<index>(v).GetCurrent()); } public: typedef tuples::tuple<Args...> ParamType; public: iuCartesianProductGenerator() {} public: virtual void Begin() IUTEST_CXX_OVERRIDE { tuples::tuple_foreach(v, begin_func()); } virtual void Next() IUTEST_CXX_OVERRIDE { if( !IsEnd() ) { next_foreach<0, kCount>(v); } } virtual bool IsEnd() const IUTEST_CXX_OVERRIDE { return is_end_foreach<0, kCount>(v); } virtual ParamType GetCurrent() const IUTEST_CXX_OVERRIDE { return current_foreach<0, kCount, Args...>(); } _MyTuple& generators() { return v; } private: _MyTuple v; }; template<typename... Generator> class iuCartesianProductHolder { typedef iuCartesianProductHolder<Generator...> _Myt; typedef tuples::tuple<const Generator...> _MyTuple; public: explicit iuCartesianProductHolder(const Generator&... generators) : v(generators...) {} public: template<typename... Args> operator iuIParamGenerator< tuples::tuple<Args...> >* () const { iuCartesianProductGenerator<Args...>* p = new iuCartesianProductGenerator<Args...>(); tuples::tuple_cast_copy(p->generators(), v); return p; } public: #if IUTEST_HAS_CONCAT template<typename Other> iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const { return iuConcatParamHolder<_Myt, Other>(*this, g); } #endif private: _Myt& operator = (const _Myt&) IUTEST_CXX_DELETED_FUNCTION; private: _MyTuple v; }; #else template<typename Generator1, typename Generator2, typename ParamType> class iuICartesianProductGeneratorBase : public iuIParamGenerator< ParamType > { public: iuICartesianProductGeneratorBase(const Generator1& g1, const Generator2& g2) : m_g1(g1), m_g2(g2) {} public: virtual void Begin() IUTEST_CXX_OVERRIDE { m_g1.Begin(); m_g2.Begin(); } virtual void Next() IUTEST_CXX_OVERRIDE { if( m_g2.IsEnd() ) { return; } m_g2.Next(); if( m_g2.IsEnd() ) { m_g1.Next(); if( !m_g1.IsEnd() ) { m_g2.Begin(); } } } virtual bool IsEnd() const IUTEST_CXX_OVERRIDE { return m_g1.IsEnd() && m_g2.IsEnd(); } protected: Generator1 m_g1; Generator2 m_g2; }; template<typename T1, typename T2> class iuCartesianProductGenerator2 : public iuICartesianProductGeneratorBase<iuParamGenerator<T1>, iuParamGenerator<T2>, tuples::tuple<T1, T2> > { typedef iuICartesianProductGeneratorBase<iuParamGenerator<T1>, iuParamGenerator<T2>, tuples::tuple<T1, T2> > _Mybase; typedef iuParamGenerator<T1> Generator1; typedef iuParamGenerator<T2> Generator2; public: typedef tuples::tuple<T1, T2> ParamType; public: iuCartesianProductGenerator2(const Generator1 &g1, const Generator2 &g2) : _Mybase(g1, g2) {} public: virtual ParamType GetCurrent() const IUTEST_CXX_OVERRIDE { return ParamType(this->m_g1.GetCurrent(), this->m_g2.GetCurrent()); } }; /* template<typename T1, typename T2, typename T3> class iuCartesianProductGenerator3 IUTEST_CXX_FINAL : public iuICartesianProductGeneratorBase<iuParamGenerator<T1> , iuCartesianProductGenerator2<T2, T3> , tuples::tuple<T1, T2, T3> > { typedef iuICartesianProductGeneratorBase<iuParamGenerator<T1>, iuCartesianProductGenerator2<T2, T3>, tuples::tuple<T1, T2, T3> > _Mybase; typedef iuParamGenerator<T1> Generator1; typedef iuParamGenerator<T2> Generator2; typedef iuParamGenerator<T3> Generator3; public: typedef tuples::tuple<T1, T2, T3> ParamType; public: iuCartesianProductGenerator3(const Generator1& g1, const Generator2& g2, const Generator3& g3) : _Mybase(g1, iuCartesianProductGenerator2<T2, T3>(g2, g3)) {} public: virtual ParamType GetCurrent() const IUTEST_CXX_OVERRIDE { tuples::tuple<T2, T3> param(this->m_g2.GetCurrent()); return ParamType(this->m_g1.GetCurrent(), tuples::get<0>(param), tuples::get<1>(param) ); } }; */ /** * @private * @{ */ #define IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_TYPEDEF_(i, p1, p2) \ typedef iuParamGenerator<IUTEST_PP_CAT(p1, i)> IUTEST_PP_CAT(p2, i); #define IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_TUPLEGET_(i, param) \ tuples::get<i>(param) #define IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_BASE_(n) \ iuICartesianProductGeneratorBase< iuParamGenerator<T0> \ , IUTEST_PP_CAT(iuCartesianProductGenerator, IUTEST_PP_DEC(n))< \ IUTEST_PP_ENUM_SHIFTED_PARAMS(IUTEST_PP_DEC(n), T) > \ , tuples::tuple< IUTEST_PP_ENUM_PARAMS(n, T) > > #define IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_(n) \ template< IUTEST_PP_ENUM_PARAMS(n, typename T) > \ class IUTEST_PP_CAT(iuCartesianProductGenerator, n) \ : public IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_BASE_(n) { \ typedef IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_BASE_(n) _Mybase; \ IUTEST_PP_REPEAT_BINARY(n, IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_TYPEDEF_, T, Generator) \ public: \ typedef tuples::tuple< IUTEST_PP_ENUM_PARAMS(n, T) > ParamType; \ IUTEST_PP_CAT(iuCartesianProductGenerator, n)( IUTEST_PP_ENUM_BINARY_PARAMS(n, const Generator, &g) ) \ : _Mybase(g0, IUTEST_PP_CAT(iuCartesianProductGenerator, IUTEST_PP_DEC(n))< \ IUTEST_PP_ENUM_SHIFTED_PARAMS(IUTEST_PP_DEC(n), T)> \ ( IUTEST_PP_ENUM_SHIFTED_PARAMS(IUTEST_PP_DEC(n), g) ) ) {} \ virtual ParamType GetCurrent() const IUTEST_CXX_OVERRIDE { \ tuples::tuple< IUTEST_PP_ENUM_SHIFTED_PARAMS(IUTEST_PP_DEC(n), T) > \ params(this->m_g2.GetCurrent()); \ return ParamType(this->m_g1.GetCurrent(), IUTEST_PP_ENUM(IUTEST_PP_DEC(n) \ , IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_TUPLEGET_, params) ); \ } \ } /** * @} */ IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_(3); IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_(4); IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_(5); IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_(6); IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_(7); IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_(8); IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_(9); #undef IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_TYPEDEF_ #undef IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_TUPLEGET_ #undef IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_BASE_ #undef IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_ // iuCartesianProductHolder /* template<typename Generator1, typename Generator2> class iuCartesianProductHolder2 { typedef iuCartesianProductHolder2<Generator1, Generator2> _Myt; public: iuCartesianProductHolder2(const Generator1& g1, const Generator2& g2) : m_g1(g1), m_g2(g2) {} public: template<typename T1, typename T2> operator iuIParamGenerator< tuples::tuple<T1, T2> >* () const { return new iuCartesianProductGenerator2<T1, T2>( static_cast< iuIParamGenerator<T1>* >(m_g1) , static_cast< iuIParamGenerator<T2>* >(m_g2) ); } public: template<typename Other> iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const { return iuConcatParamHolder<_Myt, Other>(*this, g); } private: _Myt& operator = (const _Myt&); private: const Generator1 m_g1; const Generator2 m_g2; }; */ /** * @private * @{ */ #define IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_CONSTRUCT_(i, p1, p2) IUTEST_PP_CAT(p1, i)(IUTEST_PP_CAT(p2, i)) #define IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_STATICCAST_(i, p1, p2) \ static_cast< iuIParamGenerator< IUTEST_PP_CAT(p1, i) >* >(IUTEST_PP_CAT(p2, i)) #define IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_VARIABLE_(i, p1, p2) IUTEST_PP_CAT(p1, i) IUTEST_PP_CAT(p2, i); #if IUTEST_HAS_CONCAT #define IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_CONCAT_() \ template<typename Other> iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const { \ return iuConcatParamHolder<_Myt, Other>(*this, g); } #else #define IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_CONCAT_() #endif #define IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(n) \ template< IUTEST_PP_ENUM_PARAMS(n, typename Generator) > \ class IUTEST_PP_CAT(iuCartesianProductHolder, n) { \ typedef IUTEST_PP_CAT(iuCartesianProductHolder, n)< IUTEST_PP_ENUM_PARAMS(n, Generator) > _Myt; \ public: \ IUTEST_PP_CAT(iuCartesianProductHolder, n)( IUTEST_PP_ENUM_BINARY_PARAMS(n, const Generator, &g) ) \ : IUTEST_PP_ENUM_BINARY(n, IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_CONSTRUCT_, m_g, g) {} \ template< IUTEST_PP_ENUM_PARAMS(n, typename T) > \ operator iuIParamGenerator< tuples::tuple< IUTEST_PP_ENUM_PARAMS(n, T) > >* () const { \ return new IUTEST_PP_CAT(iuCartesianProductGenerator, n)< IUTEST_PP_ENUM_PARAMS(n, T) >( \ IUTEST_PP_ENUM_BINARY(n, IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_STATICCAST_, T, m_g) ); \ } \ IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_CONCAT_() \ private: _Myt& operator = (const _Myt&) IUTEST_CXX_DELETED_FUNCTION; \ IUTEST_PP_REPEAT_BINARY(n, IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_VARIABLE_, const Generator, m_g) \ } /** * @} */ IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(2); IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(3); IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(4); IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(5); IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(6); IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(7); IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(8); IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(9); #undef IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_CONSTRUCT_ #undef IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_STATICCAST_ #undef IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_VARIABLE_ #undef IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_CONCAT_ #undef IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_ #endif #endif #if IUTEST_HAS_PAIRWISE class iuPairwiseGeneratorBase { protected: template<int N> struct ParamIndexes { int index[N]; ParamIndexes() { for( int i=0; i < N; ++i ) index[i] = -1; } }; private: struct PairInfo { PairInfo(int r1, int r2, int i1, int i2) : raw1(r1), raw2(r2), idx1(i1), idx2(i2) {} int raw1, raw2; // 列のペア int idx1, idx2; // インデックスのペア }; protected: template<typename T1> static void MakeParamVector( ::std::vector<T1>& list, iuParamGenerator<T1>& g1) { for( g1.Begin(); !g1.IsEnd(); g1.Next() ) { list.push_back(g1.GetCurrent()); } } template<typename T1, typename T2> static void MakePairList( ::std::vector< ::std::pair<T1, T2> >& list , iuParamGenerator<T1>& g1, iuParamGenerator<T2>& g2) { for( g1.Begin(); !g1.IsEnd(); g1.Next() ) { T1 t1 = g1.GetCurrent(); for( g2.Begin(); !g2.IsEnd(); g2.Next() ) { #if IUTEST_HAS_STD_EMPLACE list.emplace_back(t1, g2.GetCurrent()); #else list.push_back(::std::pair<T1, T2>(t1, g2.GetCurrent())); #endif } } } template<int N> static void MakeIndexList( ::std::vector< ParamIndexes<N> >& list, int* count_list) { typedef typename ::std::vector< ParamIndexes<N> >::iterator list_iterator; list.clear(); // ペアを列挙 ::std::vector<PairInfo> pair_list; for( int i=0; i < N; ++i ) { int l = count_list[i]; for( int j=i+1; j < N; ++j ) { int r = count_list[j]; for( int li=0; li < l; ++li ) { for( int ri=0; ri < r; ++ri ) { #if IUTEST_HAS_STD_EMPLACE pair_list.emplace_back(i, j, li, ri); #else PairInfo info( i, j, li, ri ); pair_list.push_back(info); #endif } } } } // シャッフル iuRandom random; unsigned int seed = TestEnv::get_random_seed(); if( seed != 0 ) { random.init(seed); } random.shuffle(pair_list.begin(), pair_list.end()); for( ::std::vector<PairInfo>::const_iterator it=pair_list.begin(); it != pair_list.end(); ++it ) { const PairInfo& pair_info = *it; list_iterator find = Find(list, pair_info, list.begin()); if( find == list.end() ) { find = FindFree(list, pair_info, list.begin()); if( find == list.end() ) { // 空きが無いので作る ParamIndexes<N> params; params.index[pair_info.raw1] = pair_info.idx1; params.index[pair_info.raw2] = pair_info.idx2; list.push_back(params); } else { // 埋める ParamIndexes<N>& params = *find; params.index[pair_info.raw1] = pair_info.idx1; params.index[pair_info.raw2] = pair_info.idx2; } } } //for( list_iterator it=list.begin(), end=list.end(); it != end; ++it ) //{ // for( int i=0; i < N; ++i ) printf("%2d ", it->index[i]); // printf("\n"); //} } template<int N, typename Fn> static int GetParamIndex(const ParamIndexes<N>& indexes, int raw, int count, Fn& func) { return indexes.index[raw] == -1 ? func(count) : indexes.index[raw]; } template<int N, typename T> static T GetParam(const ::std::vector<T>& params, const ParamIndexes<N>& indexes, int raw) { iuTypedRandom<int> rnd(TestEnv::genrand()()); const int index = GetParamIndex(indexes, raw, static_cast<int>(params.size()), rnd); return params[index]; } private: template<int N> static typename ::std::vector< ParamIndexes<N> >::iterator Find( ::std::vector< ParamIndexes<N> >& list , const PairInfo& pair_info, typename ::std::vector< ParamIndexes<N> >::iterator start) { typedef typename ::std::vector< ParamIndexes<N> >::iterator iterator; for( iterator it = start, end=list.end(); it != end; ++it ) { ParamIndexes<N>& indexes = *it; if( indexes.index[pair_info.raw1] == pair_info.idx1 && indexes.index[pair_info.raw2] == pair_info.idx2 ) { return it; } } return list.end(); } template<int N> static typename ::std::vector< ParamIndexes<N> >::iterator FindFree( ::std::vector< ParamIndexes<N> >& list , const PairInfo& pair_info, typename ::std::vector< ParamIndexes<N> >::iterator start) { // 入れそうなとこを探す typedef typename ::std::vector< ParamIndexes<N> >::iterator iterator; iterator find = list.end(); UInt32 max_overlap = static_cast<UInt32>(-1); for( iterator it = start, end=list.end(); it != end; ++it ) { ParamIndexes<N>& indexes = *it; int free_raw = -1; int free_idx = -1; if( indexes.index[pair_info.raw1] == -1 && indexes.index[pair_info.raw2] == pair_info.idx2 ) { free_raw = pair_info.raw1; free_idx = pair_info.idx1; } if( indexes.index[pair_info.raw2] == -1 && indexes.index[pair_info.raw1] == pair_info.idx1 ) { free_raw = pair_info.raw2; free_idx = pair_info.idx2; } if( free_raw != -1 ) { // 仮に入ったとして重複がないか調べる UInt32 overlap = 0; for( int i=0; i < N; ++i ) { if( indexes.index[i] == -1 || i == free_raw ) { continue; } PairInfo tmp(i, free_raw, indexes.index[i], free_idx); iterator it2 = Find(list, tmp, list.begin()); while(it2 != end) { ++overlap; ++it2; it2 = Find(list, tmp, it2); } } if( overlap == 0 ) { return it; } if( find == list.end() || (overlap < max_overlap) ) { find = it; max_overlap = overlap; } } } if( find != list.end() ) { return find; } typedef typename ::std::vector< ParamIndexes<N> >::iterator iterator; for( iterator it = start, end=list.end(); it != end; ++it ) { ParamIndexes<N>& indexes = *it; if( indexes.index[pair_info.raw1] == -1 && indexes.index[pair_info.raw2] == -1 ) { return it; } } return list.end(); } }; #if IUTEST_HAS_VARIADIC_PAIRWISE template<typename... Args> class iuPairwiseGenerator : public iuPairwiseGeneratorBase { typedef tuples::tuple< Args... > ParamType; typedef tuples::tuple< iuParamGenerator<Args>... > GeneratorTuple; static const int kRAW_COUNT = sizeof...(Args); typedef ParamIndexes<kRAW_COUNT> _MyParamIndexes; typedef ::std::vector< _MyParamIndexes > ParamIndexesList; typedef tuples::tuple< ::std::vector<Args>... > ParamsTuple; public: static iuIParamGenerator< ParamType >* Create(GeneratorTuple& generators) { ParamIndexesList list; ParamVecotrs param_vectors(generators); MakeIndexList(list, param_vectors.count_list); ::std::vector<ParamType> params; for( typename ParamIndexesList::const_iterator it=list.begin(), end=list.end(); it != end; ++it ) { const _MyParamIndexes& indexes = *it; params.push_back(MakeParam<0, Args...>(param_vectors.params_list, indexes)); } return new iuValuesInParamsGenerator< ParamType >(params); } private: template<int N, typename T1, typename... TArgs> static tuples::tuple<T1, TArgs...> MakeParam(ParamsTuple& list, const _MyParamIndexes& indexes , typename detail::disable_if<N == kRAW_COUNT -1, void>::type*& = detail::enabler::value) { return ::std::tuple_cat( tuples::tuple<T1>(GetParam(tuples::get<N>(list), indexes, N)) , MakeParam<N+1, TArgs...>(list, indexes) ); } template<int N, typename T1, typename... TArgs> static tuples::tuple<T1> MakeParam(ParamsTuple& list, const _MyParamIndexes& indexes , typename detail::enable_if<N == kRAW_COUNT -1, void>::type*& = detail::enabler::value) { return tuples::tuple<T1>( GetParam( tuples::get<N>(list), indexes, N) ); } struct ParamVecotrs { ParamsTuple params_list; int count_list[kRAW_COUNT]; template<int N> void MakeParamVecotrs(GeneratorTuple& generators , typename detail::disable_if<N == kRAW_COUNT -1, void>::type*& = detail::enabler::value) { MakeParamVector(tuples::get<N>(params_list), tuples::get<N>(generators)); count_list[N] = static_cast<int>(tuples::get<N>(params_list).size()); MakeParamVecotrs<N+1>(generators); } template<int N> void MakeParamVecotrs(GeneratorTuple& generators , typename detail::enable_if<N == kRAW_COUNT -1, void>::type*& = detail::enabler::value) { MakeParamVector(tuples::get<N>(params_list), tuples::get<N>(generators)); count_list[N] = static_cast<int>(tuples::get<N>(params_list).size()); } explicit ParamVecotrs(GeneratorTuple& generators) { MakeParamVecotrs<0>(generators); } }; }; template<typename... Generator> class iuPairwiseHolder { typedef iuPairwiseHolder<Generator...> _Myt; typedef tuples::tuple<const Generator...> _MyTuple; public: explicit iuPairwiseHolder(const Generator&... generators) : v(generators...) {} public: template<typename... Args> operator iuIParamGenerator< tuples::tuple<Args...> >* () const { tuples::tuple< iuParamGenerator<Args>... > generators; tuples::tuple_cast_copy(generators, v); return iuPairwiseGenerator<Args...>::Create(generators); } public: #if IUTEST_HAS_CONCAT template<typename Other> iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const { return iuConcatParamHolder<_Myt, Other>(*this, g); } #endif private: _Myt& operator = (const _Myt&) IUTEST_CXX_DELETED_FUNCTION; private: _MyTuple v; }; #else template<typename T1, typename T2> class iuPairwiseGenerator2 IUTEST_CXX_FINAL : public iuIParamGenerator< tuples::tuple<T1, T2> > { typedef iuParamGenerator<T1> Generator1; typedef iuParamGenerator<T2> Generator2; public: typedef tuples::tuple<T1, T2> ParamType; public: iuPairwiseGenerator2(const Generator1& g1, const Generator2& g2) : m_g1(g1), m_g2(g2) {} static iuIParamGenerator< ParamType >* Create(const Generator1& g1, const Generator2& g2) { return new iuPairwiseGenerator2<T1, T2>(g1, g2); } public: virtual void Begin() IUTEST_CXX_OVERRIDE { m_g1.Begin(); m_g2.Begin(); } virtual void Next() IUTEST_CXX_OVERRIDE { if( m_g2.IsEnd() ) { return; } m_g2.Next(); if( m_g2.IsEnd() ) { m_g1.Next(); if( !m_g1.IsEnd() ) { m_g2.Begin(); } } } virtual bool IsEnd() const IUTEST_CXX_OVERRIDE { return m_g1.IsEnd() && m_g2.IsEnd(); } virtual ParamType GetCurrent() const IUTEST_CXX_OVERRIDE { return ParamType(this->m_g1.GetCurrent(), this->m_g2.GetCurrent()); } private: Generator1 m_g1; Generator2 m_g2; }; /* template<typename T1, typename T2, typename T3> class iuPairwiseGenerator3 : public iuPairwiseGeneratorBase { typedef iuParamGenerator<T1> Generator1; typedef iuParamGenerator<T2> Generator2; typedef iuParamGenerator<T3> Generator3; static const int kRAW_COUNT = 3; typedef ParamIndexes<kRAW_COUNT> _MyParamIndexes; typedef ::std::vector< _MyParamIndexes > ParamIndexesList; public: typedef tuples::tuple<T1, T2, T3> ParamType; public: static iuIParamGenerator< ParamType >* Create(Generator1 g1, Generator2 g2, Generator3 g3) { ParamIndexesList list; ::std::vector<T1> params1; ::std::vector<T2> params2; ::std::vector<T3> params3; MakeParamVector(params1, g1); MakeParamVector(params2, g2); MakeParamVector(params3, g3); int count_list[] = { static_cast<int>(params1.size()) , static_cast<int>(params2.size()) , static_cast<int>(params3.size()) }; MakeIndexList(list, count_list); ::std::vector<ParamType> params; for( typename ParamIndexesList::const_iterator it=list.begin(), end=list.end(); it != end; ++it ) { const _MyParamIndexes& indexes = *it; params.push_back( ParamType( GetParam(params1, indexes, 0) , GetParam(params2, indexes, 1) , GetParam(params3, indexes, 2) ) ); } return new iuValuesInParamsGenerator< ParamType >(params); } }; */ /** * @private * @{ */ #define IIUT_DECL_PAIRWISE_GENERATOR_TEMPLATE_T_(i, p1, p2) \ p1<IUTEST_PP_CAT(T, i)> IUTEST_PP_CAT(p2, i); #define IIUT_DECL_PAIRWISE_GENERATOR_MAKEPARAM_VECTOR_(i, p1, p2) \ MakeParamVector( IUTEST_PP_CAT(p1, i), IUTEST_PP_CAT(p2, i) ); #define IIUT_DECL_PAIRWISE_GENERATOR_PARAM_SIZE_(i, param) \ static_cast<int>( IUTEST_PP_CAT(param, i).size() ) #define IIUT_DECL_PAIRWISE_GENERATOR_GETPARAM_(i, param) \ GetParam( IUTEST_PP_CAT(param, i), indexes, i) #define IIUT_DECL_PAIRWISE_GENERATOR_(n) \ template< IUTEST_PP_ENUM_PARAMS(n, typename T) > \ class IUTEST_PP_CAT(iuPairwiseGenerator, n) IUTEST_CXX_FINAL : public iuPairwiseGeneratorBase { \ IUTEST_PP_REPEAT_BINARY(n, IIUT_DECL_PAIRWISE_GENERATOR_TEMPLATE_T_, typedef iuParamGenerator, Generator) \ typedef ParamIndexes<n> _MyParamIndexes; \ typedef ::std::vector< _MyParamIndexes > ParamIndexesList; \ public: typedef tuples::tuple< IUTEST_PP_ENUM_PARAMS(n, T) > ParamType; \ static iuIParamGenerator< ParamType >* Create( \ IUTEST_PP_ENUM_BINARY_PARAMS(n, Generator, g) ) { \ ParamIndexesList list; \ IUTEST_PP_REPEAT_BINARY(n, IIUT_DECL_PAIRWISE_GENERATOR_TEMPLATE_T_, ::std::vector, params) \ IUTEST_PP_REPEAT_BINARY(n, IIUT_DECL_PAIRWISE_GENERATOR_MAKEPARAM_VECTOR_, params, g) \ int count_list[] = { IUTEST_PP_ENUM(n, IIUT_DECL_PAIRWISE_GENERATOR_PARAM_SIZE_, params) }; \ MakeIndexList(list, count_list); \ ::std::vector<ParamType> params; \ for( typename ParamIndexesList::const_iterator it=list.begin(), end=list.end(); it != end; ++it ) { \ const _MyParamIndexes& indexes = *it; \ params.push_back( ParamType( IUTEST_PP_ENUM(n, IIUT_DECL_PAIRWISE_GENERATOR_GETPARAM_, params) ) ); \ } \ return new iuValuesInParamsGenerator< ParamType >(params); \ } \ } /** * @} */ IIUT_DECL_PAIRWISE_GENERATOR_(3); IIUT_DECL_PAIRWISE_GENERATOR_(4); IIUT_DECL_PAIRWISE_GENERATOR_(5); IIUT_DECL_PAIRWISE_GENERATOR_(6); IIUT_DECL_PAIRWISE_GENERATOR_(7); IIUT_DECL_PAIRWISE_GENERATOR_(8); IIUT_DECL_PAIRWISE_GENERATOR_(9); #undef IIUT_DECL_PAIRWISE_GENERATOR_TEMPLATE_T_ #undef IIUT_DECL_PAIRWISE_GENERATOR_MAKEPARAM_VECTOR_ #undef IIUT_DECL_PAIRWISE_GENERATOR_PARAM_SIZE_ #undef IIUT_DECL_PAIRWISE_GENERATOR_GETPARAM_ #undef IIUT_DECL_PAIRWISE_GENERATOR_ /* template<typename Generator1, typename Generator2> class iuPairwiseHolder2 { typedef iuPairwiseHolder2<Generator1, Generator2> _Myt; public: iuPairwiseHolder2(const Generator1& g1, const Generator2& g2) : m_g1(g1), m_g2(g2) {} public: template<typename T1, typename T2> operator iuIParamGenerator< tuples::tuple<T1, T2> >* () const { return iuPairwiseGenerator2<T1, T2>::Create( static_cast< iuIParamGenerator<T1>* >(m_g1) , static_cast< iuIParamGenerator<T2>* >(m_g2) ); } public: template<typename Other> iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const { return iuConcatParamHolder<_Myt, Other>(*this, g); } private: _Myt& operator = (const _Myt&) IUTEST_CXX_DELETED_FUNCTION; private: const Generator1 m_g1; const Generator2 m_g2; }; */ #define IIUT_DECL_PAIRWISE_HOLDER_CONSTRUCT_(i, p1, p2) IUTEST_PP_CAT(p1, i)(IUTEST_PP_CAT(p2, i)) #define IIUT_DECL_PAIRWISE_HOLDER_STATICCAST_(i, p1, p2) \ static_cast< iuIParamGenerator< IUTEST_PP_CAT(p1, i) >* >(IUTEST_PP_CAT(p2, i)) #define IIUT_DECL_PAIRWISE_HOLDER_VARIABLE_(i, p1, p2) IUTEST_PP_CAT(p1, i) IUTEST_PP_CAT(p2, i); #if IUTEST_HAS_CONCAT # define IIUT_DECL_PAIRWISE_HOLDER_CONCAT_() \ template<typename Other> iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const { \ return iuConcatParamHolder<_Myt, Other>(*this, g); } #else # define IIUT_DECL_PAIRWISE_HOLDER_CONCAT_() #endif #define IIUT_DECL_PAIRWISE_HOLDER_(n) \ template< IUTEST_PP_ENUM_PARAMS(n, typename Generator) > \ class IUTEST_PP_CAT(iuPairwiseHolder, n) { \ typedef IUTEST_PP_CAT(iuPairwiseHolder, n)< IUTEST_PP_ENUM_PARAMS(n, Generator) > _Myt; \ public: IUTEST_PP_CAT(iuPairwiseHolder, n)( \ IUTEST_PP_ENUM_BINARY_PARAMS(n, const Generator, &g) ) \ : IUTEST_PP_ENUM_BINARY(n, IIUT_DECL_PAIRWISE_HOLDER_CONSTRUCT_, m_g, g) {} \ template< IUTEST_PP_ENUM_PARAMS(n, typename T) > \ operator iuIParamGenerator< tuples::tuple< IUTEST_PP_ENUM_PARAMS(n, T) > >* () const { \ return IUTEST_PP_CAT(iuPairwiseGenerator, n)< IUTEST_PP_ENUM_PARAMS(n, T) >::Create( \ IUTEST_PP_ENUM_BINARY(n, IIUT_DECL_PAIRWISE_HOLDER_STATICCAST_, T, m_g) ); \ } \ IIUT_DECL_PAIRWISE_HOLDER_CONCAT_() \ private: _Myt& operator = (const _Myt&) IUTEST_CXX_DELETED_FUNCTION; \ IUTEST_PP_REPEAT_BINARY(n, IIUT_DECL_PAIRWISE_HOLDER_VARIABLE_, const Generator, m_g) \ } IIUT_DECL_PAIRWISE_HOLDER_(2); IIUT_DECL_PAIRWISE_HOLDER_(3); IIUT_DECL_PAIRWISE_HOLDER_(4); IIUT_DECL_PAIRWISE_HOLDER_(5); IIUT_DECL_PAIRWISE_HOLDER_(6); IIUT_DECL_PAIRWISE_HOLDER_(7); IIUT_DECL_PAIRWISE_HOLDER_(8); IIUT_DECL_PAIRWISE_HOLDER_(9); #undef IIUT_DECL_PAIRWISE_HOLDER_CONSTRUCT_ #undef IIUT_DECL_PAIRWISE_HOLDER_STATICCAST_ #undef IIUT_DECL_PAIRWISE_HOLDER_VARIABLE_ #undef IIUT_DECL_PAIRWISE_HOLDER_CONCAT_ #undef IIUT_DECL_PAIRWISE_HOLDER_ #endif #endif #if IUTEST_HAS_VALUESGEN /** * @brief パラメータ生成器 * @tparam G = パラメータ生成器 */ template<typename StdGenerator> class iuValuesParamsGeneratorHolder { typedef iuValuesParamsGeneratorHolder<StdGenerator> _Myt; public: iuValuesParamsGeneratorHolder(size_t num, const StdGenerator& g) : m_num(num), m_g(g) {} public: template<typename T> operator iuIParamGenerator<T>* () const { ::std::vector<T> params(m_num); ::std::generate(params.begin(), params.end(), m_g); return new iuValuesInParamsGenerator<T>( params ); } public: #if IUTEST_HAS_CONCAT template<typename Other> iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const { return iuConcatParamHolder<_Myt, Other>(*this, g); } #endif private: size_t m_num; StdGenerator m_g; }; /** * @brief 乱数ジェネレータ */ template<typename T, typename F> class iuRandomFilterParamGenerator { typedef T type; public: iuRandomFilterParamGenerator(const F& fn, unsigned int seed) : m_fn(fn), m_rnd(seed) {} type operator ()() { type val = m_rnd.genrand(); for( ; !(m_fn)(val); val = m_rnd.genrand() ) {} return val; } private: F m_fn; iuTypedRandom<type> m_rnd; }; #endif #if IUTEST_HAS_RANDOMVALUES /** * @brief 乱数パラメータ生成器 */ class iuRandomParamsHolder { public: explicit iuRandomParamsHolder(size_t num, unsigned int seed=0) IUTEST_CXX_NOEXCEPT_SPEC : m_num(num), m_seed(seed) {} public: template<typename T> operator iuIParamGenerator<T>* () const { unsigned int seed = m_seed; if( seed == 0 ) { seed = GetIndefiniteValue(); } iuValuesParamsGeneratorHolder< iuTypedRandom<T> > gen( m_num, iuTypedRandom<T>(seed) ); return gen; } public: #if IUTEST_HAS_CONCAT template<typename Other> iuConcatParamHolder<iuRandomParamsHolder, Other> operator + (const Other& g) const { return iuConcatParamHolder<iuRandomParamsHolder, Other>(*this, g); } #endif private: size_t m_num; unsigned int m_seed; }; #endif } // end of namespace detail } // end of namespace iutest #endif #endif // INCG_IRIS_IUTEST_GENPARAMS_HPP_7845F59A_825C_426A_B451_573245408998_
31.868618
144
0.621382
BuildJet
b4f815035bfbcd3925e92de71c9d44cddd6cd5bf
18,256
cpp
C++
src/chrono_vehicle/tracked_vehicle/ChTrackContactManager.cpp
Ruochun/chrono
7b0f09242ef540ae56cfc8add3a5dc7985c654d2
[ "BSD-3-Clause" ]
1
2021-12-09T05:24:42.000Z
2021-12-09T05:24:42.000Z
src/chrono_vehicle/tracked_vehicle/ChTrackContactManager.cpp
Ruochun/chrono
7b0f09242ef540ae56cfc8add3a5dc7985c654d2
[ "BSD-3-Clause" ]
7
2021-10-20T04:43:35.000Z
2021-12-24T08:44:31.000Z
src/chrono_vehicle/tracked_vehicle/ChTrackContactManager.cpp
Ruochun/chrono
7b0f09242ef540ae56cfc8add3a5dc7985c654d2
[ "BSD-3-Clause" ]
2
2021-12-09T05:32:31.000Z
2021-12-12T17:31:18.000Z
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Classes for monitoring contacts of tracked vehicle subsystems. // // ============================================================================= #include "chrono/physics/ChLoadsBody.h" #include "chrono_vehicle/tracked_vehicle/ChTrackContactManager.h" #include "chrono_vehicle/tracked_vehicle/ChTrackedVehicle.h" namespace chrono { namespace vehicle { // ----------------------------------------------------------------------------- ChTrackContactManager::ChTrackContactManager() : m_initialized(false), m_flags(0), m_collect(false), m_shoe_index_L(0), m_shoe_index_R(0) { } void ChTrackContactManager::Process(ChTrackedVehicle* vehicle) { // Initialize the manager if not already done. if (!m_initialized) { m_chassis = vehicle->GetChassis(); m_sprocket_L = vehicle->GetTrackAssembly(LEFT)->GetSprocket(); m_sprocket_R = vehicle->GetTrackAssembly(RIGHT)->GetSprocket(); if (vehicle->GetTrackAssembly(LEFT)->GetNumTrackShoes() > m_shoe_index_L && vehicle->GetTrackAssembly(RIGHT)->GetNumTrackShoes() > m_shoe_index_R) { m_shoe_L = vehicle->GetTrackAssembly(LEFT)->GetTrackShoe(m_shoe_index_L); m_shoe_R = vehicle->GetTrackAssembly(RIGHT)->GetTrackShoe(m_shoe_index_R); } m_idler_L = vehicle->GetTrackAssembly(LEFT)->GetIdler(); m_idler_R = vehicle->GetTrackAssembly(RIGHT)->GetIdler(); m_initialized = true; } if (m_flags == 0) return; // Clear lists m_chassis_contacts.clear(); m_sprocket_L_contacts.clear(); m_sprocket_R_contacts.clear(); m_shoe_L_contacts.clear(); m_shoe_R_contacts.clear(); m_idler_L_contacts.clear(); m_idler_R_contacts.clear(); // Traverse all system contacts and extract information. std::shared_ptr<ChTrackContactManager> shared_this(this, [](ChTrackContactManager*) {}); vehicle->GetSystem()->GetContactContainer()->ReportAllContacts(shared_this); // Collect contact information data. // Print current time, and number of contacts involving the chassis, left/right sprockets, // left/right idlers, left/right track shoes, followed by the location of the contacts, in the // same order as above, expressed in the local frame of the respective body. if (m_collect) { // Get number of contacts in all lists; size_t n_chassis = m_chassis_contacts.size(); size_t n_sprocket_L = m_sprocket_L_contacts.size(); size_t n_sprocket_R = m_sprocket_R_contacts.size(); size_t n_idler_L = m_idler_L_contacts.size(); size_t n_idler_R = m_idler_R_contacts.size(); size_t n_shoe_L = m_shoe_L_contacts.size(); size_t n_shoe_R = m_shoe_R_contacts.size(); // Only collect data at this time if there is at least one monitored contact size_t n_contacts = n_chassis + n_sprocket_L + n_sprocket_R + n_idler_L + n_idler_R + n_shoe_L + n_shoe_R; if (n_contacts != 0) { // Current simulation time m_csv << vehicle->GetChTime(); // Number of contacts on vehicle parts m_csv << m_chassis_contacts.size(); m_csv << m_sprocket_L_contacts.size(); m_csv << m_sprocket_R_contacts.size(); m_csv << m_idler_L_contacts.size(); m_csv << m_idler_R_contacts.size(); m_csv << m_shoe_L_contacts.size(); m_csv << m_shoe_R_contacts.size(); // Chassis contact points for (const auto& c : m_chassis_contacts) { m_csv << m_chassis->GetBody()->TransformPointParentToLocal(c.m_point); } for (const auto& c : m_sprocket_L_contacts) { m_csv << m_sprocket_L->GetGearBody()->TransformPointParentToLocal(c.m_point); } // Right sprocket contact points for (const auto& c : m_sprocket_R_contacts) { m_csv << m_sprocket_R->GetGearBody()->TransformPointParentToLocal(c.m_point); } // Left idler contact points for (const auto& c : m_idler_L_contacts) { m_csv << m_idler_L->GetWheelBody()->TransformPointParentToLocal(c.m_point); } // Right idler contact points for (const auto& c : m_idler_R_contacts) { m_csv << m_idler_R->GetWheelBody()->TransformPointParentToLocal(c.m_point); } // Left track shoe contact points if (m_shoe_L) { for (const auto& c : m_shoe_L_contacts) { m_csv << m_shoe_L->GetShoeBody()->TransformPointParentToLocal(c.m_point); } } // Right track shoe contact points if (m_shoe_R) { for (const auto& c : m_shoe_R_contacts) { m_csv << m_shoe_R->GetShoeBody()->TransformPointParentToLocal(c.m_point); } } m_csv << std::endl; } } } // ----------------------------------------------------------------------------- bool ChTrackContactManager::InContact(TrackedCollisionFlag::Enum part) const { switch (part) { case TrackedCollisionFlag::CHASSIS: return m_chassis_contacts.size() != 0; case TrackedCollisionFlag::SPROCKET_LEFT: return m_sprocket_L_contacts.size() != 0; case TrackedCollisionFlag::SPROCKET_RIGHT: return m_sprocket_R_contacts.size() != 0; case TrackedCollisionFlag::IDLER_LEFT: return m_idler_L_contacts.size() != 0; case TrackedCollisionFlag::IDLER_RIGHT: return m_idler_R_contacts.size() != 0; case TrackedCollisionFlag::SHOES_LEFT: return m_shoe_L_contacts.size() != 0; case TrackedCollisionFlag::SHOES_RIGHT: return m_shoe_R_contacts.size() != 0; default: return false; } } // ----------------------------------------------------------------------------- ChVector<> ChTrackContactManager::GetSprocketResistiveTorque(VehicleSide side) const { const auto& contacts = (side == VehicleSide::LEFT) ? m_sprocket_L_contacts : m_sprocket_R_contacts; const auto& spoint = (side == VehicleSide::LEFT) ? m_sprocket_L->GetGearBody()->GetPos() : m_sprocket_R->GetGearBody()->GetPos(); ChVector<> torque(0); for (auto& c : contacts) { ChVector<> F = c.m_csys * c.m_force; ChVector<> T = c.m_csys * c.m_torque; torque += (c.m_point - spoint).Cross(F) + T; } return torque; } // ----------------------------------------------------------------------------- bool ChTrackContactManager::OnReportContact(const ChVector<>& pA, const ChVector<>& pB, const ChMatrix33<>& plane_coord, const double& distance, const double& eff_radius, const ChVector<>& react_forces, const ChVector<>& react_torques, ChContactable* modA, ChContactable* modB) { ContactInfo info; // Ignore contacts with zero force or positive separation. if (distance > 0 || react_forces.IsNull()) return true; // Extract contacts on chassis. if (IsFlagSet(TrackedCollisionFlag::CHASSIS)) { if (modA == m_chassis->GetBody().get()) { info.m_point = pA; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_chassis_contacts.push_back(info); } if (modB == m_chassis->GetBody().get()) { info.m_point = pB; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_chassis_contacts.push_back(info); } } // Extract contacts on sprockets. if (IsFlagSet(TrackedCollisionFlag::SPROCKET_LEFT)) { if (modA == m_sprocket_L->GetGearBody().get()) { info.m_point = pA; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_sprocket_L_contacts.push_back(info); } if (modB == m_sprocket_L->GetGearBody().get()) { info.m_point = pB; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_sprocket_L_contacts.push_back(info); } } if (IsFlagSet(TrackedCollisionFlag::SPROCKET_RIGHT)) { if (modA == m_sprocket_R->GetGearBody().get()) { info.m_point = pA; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_sprocket_R_contacts.push_back(info); } if (modB == m_sprocket_R->GetGearBody().get()) { info.m_point = pB; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_sprocket_R_contacts.push_back(info); } } // Extract contacts on track shoes (discard contacts with sprockets) if (IsFlagSet(TrackedCollisionFlag::SHOES_LEFT)) { if (modA == m_shoe_L->GetShoeBody().get() && modB != m_sprocket_L->GetGearBody().get()) { info.m_point = pA; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_shoe_L_contacts.push_back(info); } if (modB == m_shoe_L->GetShoeBody().get() && modA != m_sprocket_L->GetGearBody().get()) { info.m_point = pB; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_shoe_L_contacts.push_back(info); } } if (IsFlagSet(TrackedCollisionFlag::SHOES_RIGHT)) { if (modA == m_shoe_R->GetShoeBody().get() && modB != m_sprocket_R->GetGearBody().get()) { info.m_point = pA; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_shoe_R_contacts.push_back(info); } if (modB == m_shoe_R->GetShoeBody().get() && modA != m_sprocket_R->GetGearBody().get()) { info.m_point = pB; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_shoe_R_contacts.push_back(info); } } // Extract contacts on idler wheels. if (IsFlagSet(TrackedCollisionFlag::IDLER_LEFT)) { if (modA == m_idler_L->GetWheelBody().get()) { info.m_point = pA; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_idler_L_contacts.push_back(info); } if (modB == m_idler_L->GetWheelBody().get()) { info.m_point = pB; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_idler_L_contacts.push_back(info); } } if (IsFlagSet(TrackedCollisionFlag::IDLER_RIGHT)) { if (modA == m_idler_R->GetWheelBody().get()) { info.m_point = pA; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_idler_R_contacts.push_back(info); } if (modB == m_idler_R->GetWheelBody().get()) { info.m_point = pB; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_idler_R_contacts.push_back(info); } } // Continue scanning contacts return true; } void ChTrackContactManager::WriteContacts(const std::string& filename) { if (m_collect && m_flags != 0) m_csv.write_to_file(filename); } // ----------------------------------------------------------------------------- ChTrackCollisionManager::ChTrackCollisionManager(ChTrackedVehicle* vehicle) : m_idler_shoe(true), m_wheel_shoe(true) {} void ChTrackCollisionManager::Reset() { // Empty collision lists m_collisions_idler.clear(); m_collisions_wheel.clear(); } static const double nrm_threshold = 0.8; bool ChTrackCollisionManager::OnNarrowphase(collision::ChCollisionInfo& contactinfo) { ChBody* bodyA = dynamic_cast<ChBody*>(contactinfo.modelA->GetContactable()); ChBody* bodyB = dynamic_cast<ChBody*>(contactinfo.modelB->GetContactable()); if (!bodyA || !bodyB) return true; // Body B is a track shoe body if (bodyB->GetIdentifier() == BodyID::SHOE_BODY) { // Express collision normal in body A (wheel) frame auto nrm = bodyA->TransformDirectionParentToLocal(contactinfo.vN); // Identify "lateral" contacts (assumed to be with a guiding pin) and let Chrono generate contacts if (std::abs(nrm.y()) > nrm_threshold) { return true; } // Intercept and cache collisions between wheels and track pad. // Do not generate Chrono contact for such collisions. if (m_idler_shoe && bodyA->GetIdentifier() == BodyID::IDLER_BODY) { m_collisions_idler.push_back(contactinfo); return false; } if (m_wheel_shoe && bodyA->GetIdentifier() == BodyID::WHEEL_BODY) { m_collisions_wheel.push_back(contactinfo); return false; } } // Body A is a track shoe body if (bodyA->GetIdentifier() == BodyID::SHOE_BODY) { // Express collision normal in body B (wheel) frame auto nrm = bodyB->TransformDirectionParentToLocal(contactinfo.vN); // Identify "lateral" contacts (assumed to be with a guiding pin) and let Chrono generate contacts if (std::abs(nrm.y()) > nrm_threshold) { return true; } // Intercept and cache collisions between wheels and track pad. // Do not generate Chrono contact for such collisions. if (m_idler_shoe && bodyB->GetIdentifier() == BodyID::IDLER_BODY) { auto contactinfoS = contactinfo; contactinfoS.SwapModels(); m_collisions_idler.push_back(contactinfoS); return false; } if (m_wheel_shoe && bodyB->GetIdentifier() == BodyID::WHEEL_BODY) { auto contactinfoS = contactinfo; contactinfoS.SwapModels(); m_collisions_wheel.push_back(contactinfoS); return false; } } // Let Chrono generate contact for any other collision return true; } // ----------------------------------------------------------------------------- void ChTrackCustomContact::Setup() { // Calculate contact forces for all current wheel-shoe collisions, calling the user-supplied callback ApplyForces(); // Perform a full update of the load container ChLoadContainer::Update(ChTime, false); } void ChTrackCustomContact::Update(double mytime, bool update_assets) { // Note: since Update could be called multiple times per time step, we do not invoke the // callback function here to calculate custom contact forces (since they are based on collision // detection information which only occurs once per time step). Instead, we do this in Setup. // We still override this function to prevent unnecessary calculations in the base class Update. ChTime = mytime; } void ChTrackCustomContact::ApplyForces() { // Reset the load list for this load container GetLoadList().clear(); ////std::cout << "Idler-shoe collisions: " << m_collision_manager->m_collisions_idler.size() << std::endl; ////std::cout << "Wheel-shoe collisions: " << m_collision_manager->m_collisions_wheel.size() << std::endl; ChVector<> forceB; for (auto& cInfo : m_collision_manager->m_collisions_idler) { std::shared_ptr<ChBody> bodyA(static_cast<ChBody*>(cInfo.modelA->GetContactable()), [](ChBody*) {}); std::shared_ptr<ChBody> bodyB(static_cast<ChBody*>(cInfo.modelB->GetContactable()), [](ChBody*) {}); // Call user-provided force calculation ComputeForce(cInfo, bodyA, bodyB, true, forceB); // Apply equal and opposite forces on the two bodies (road wheel and track shoe) in contact auto loadA = chrono_types::make_shared<ChLoadBodyForce>(bodyA, -forceB, false, cInfo.vpA, false); auto loadB = chrono_types::make_shared<ChLoadBodyForce>(bodyB, +forceB, false, cInfo.vpB, false); Add(loadA); Add(loadB); } for (auto& cInfo : m_collision_manager->m_collisions_wheel) { std::shared_ptr<ChBody> bodyA(static_cast<ChBody*>(cInfo.modelA->GetContactable()), [](ChBody*) {}); std::shared_ptr<ChBody> bodyB(static_cast<ChBody*>(cInfo.modelB->GetContactable()), [](ChBody*) {}); // Call user-provided force calculation ComputeForce(cInfo, bodyA, bodyB, false, forceB); // Apply equal and opposite forces on the two bodies (wheel and track shoe) in contact auto loadA = chrono_types::make_shared<ChLoadBodyForce>(bodyA, -forceB, false, cInfo.vpA, false); auto loadB = chrono_types::make_shared<ChLoadBodyForce>(bodyB, +forceB, false, cInfo.vpB, false); Add(loadA); Add(loadB); } } } // end namespace vehicle } // end namespace chrono
39.686957
119
0.590436
Ruochun
b4f86e0afbd48cc1074fd52fb7cec438690f9009
10,381
cpp
C++
examples/02Physics/GroundTileMap.cpp
Galhad/firestorm
3c1584b1e5b95f21d963b9cf226f6ec1a469d7af
[ "MIT" ]
null
null
null
examples/02Physics/GroundTileMap.cpp
Galhad/firestorm
3c1584b1e5b95f21d963b9cf226f6ec1a469d7af
[ "MIT" ]
null
null
null
examples/02Physics/GroundTileMap.cpp
Galhad/firestorm
3c1584b1e5b95f21d963b9cf226f6ec1a469d7af
[ "MIT" ]
null
null
null
#include "GroundTileMap.hpp" #include "Obstacle.hpp" #include "Collectable.hpp" namespace fs::scene { void GroundTileMap::create(io::InputManager& inputManager, physics::PhysicsManager& physicsManager, graphics::SpriteSheet& tilesSpriteSheet, graphics::SpriteSheet& itemsSpriteSheet) { GroundTileMap::tilesSpriteSheet = &tilesSpriteSheet; GroundTileMap::itemsSpriteSheet = &itemsSpriteSheet; createSprites(); core::Vector2i size{40, 20}; core::Vector2f tileSize{grassLeftSprite->getWidthUnits(), grassLeftSprite->getHeightUnits()}; TileMapSceneNode::create(inputManager, size, tileSize); setTileBuilderCallback([&](core::fs_int32 id) -> SceneNode* { const graphics::Sprite* sprite = nullptr; if (id == leftId) { return createGroundBrick(grassLeftSprite, physicsManager); } else if (id == midId) { return createGroundBrick(grassMidSprite, physicsManager); } else if (id == rightId) { return createGroundBrick(grassRightSprite, physicsManager); } else if (id == plantId) { auto* spriteSceneNode = new SpriteSceneNode(); spriteSceneNode->create(inputManager, *plantSprite); return spriteSceneNode; } else if (id == weightId) { auto* obstacleSceneNode = new Obstacle(); obstacleSceneNode->create(inputManager, *weightSprite, physicsManager); return obstacleSceneNode; } else if (id == coinId) { auto* collectableSceneNode = new Collectable(); collectableSceneNode->create(inputManager, *coinSprite, physicsManager); return collectableSceneNode; } else { throw std::runtime_error("Undefined ground brick"); } }); //@formatter:off std::vector<std::vector<core::fs_int32>> ids = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, plantId, -1, coinId, -1, plantId, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, leftId, midId, midId, midId, midId, midId, rightId, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, coinId, coinId, coinId, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, leftId, midId, rightId, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, coinId, plantId, coinId, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, leftId, midId, rightId, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, weightId, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, leftId, midId, rightId, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, plantId, coinId, plantId, -1, -1, -1, -1, -1, -1, -1, -1, -1, coinId, coinId, coinId, coinId, -1, -1, coinId, -1, plantId, -1, coinId, -1, plantId, -1, -1, weightId, coinId, -1, -1, coinId, coinId, coinId, coinId}, {leftId, midId, rightId, -1, leftId, midId, midId, midId, rightId, -1, -1, -1, -1, -1, -1, -1, -1, leftId, midId, midId, rightId, -1, -1, leftId, midId, midId, midId, midId, midId, midId, midId, midId, midId, rightId, -1, -1, leftId, midId, midId, rightId}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1} }; //@formatter:on setTilesIds(ids); } GroundBrick* GroundTileMap::createGroundBrick(const graphics::Sprite* sprite, physics::PhysicsManager& physicsManager) const { auto* groundBrick = new GroundBrick(); groundBrick->create(*inputManager, *sprite, physicsManager); return groundBrick; } void GroundTileMap::createSprites() { grassLeftSprite = tilesSpriteSheet->addSprite({504, 648, 70, 70}); grassMidSprite = tilesSpriteSheet->addSprite({504, 576, 70, 70}); grassRightSprite = tilesSpriteSheet->addSprite({504, 504, 70, 70}); plantSprite = itemsSpriteSheet->addSprite({0, 363, 70, 70}); cactusSprite = itemsSpriteSheet->addSprite({360, 216, 70, 70}); weightSprite = itemsSpriteSheet->addSprite({490, 144, 70, 70}); coinSprite = itemsSpriteSheet->addSprite({288, 360, 70, 70}); } void GroundTileMap::destroy() { TileMapSceneNode::destroy(); } void GroundTileMap::setTilesIds(const std::vector<std::vector<core::fs_int32>>& vector) { for (core::fs_int64 y = 0; y < vector.size(); ++y) { for (core::fs_int64 x = 0; x < vector[y].size(); ++x) { setTileId(core::Vector2i{x, y}, vector[y][x]); } } } }
84.398374
320
0.305173
Galhad
b4fa9b3cc4e73e3eab58992c9d15bd1a4a0aa863
782
cpp
C++
2016/Day03/Day03.cpp
jloehr/AdventOfCode
11fa8f52b7ba156cecb729c7a3d24fbec27203d0
[ "MIT" ]
null
null
null
2016/Day03/Day03.cpp
jloehr/AdventOfCode
11fa8f52b7ba156cecb729c7a3d24fbec27203d0
[ "MIT" ]
null
null
null
2016/Day03/Day03.cpp
jloehr/AdventOfCode
11fa8f52b7ba156cecb729c7a3d24fbec27203d0
[ "MIT" ]
null
null
null
// Day03.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "TriangleTest.h" int main() { signed ValidRowTriangles = 0; signed ValidColumnTriangles = 0; StringVectorVector Lines = GetFileLineParts("Input.txt"); TriangleTest RowTest; std::array<TriangleTest, 3> ColumnTest; for (const StringVector & Line : Lines) { for (int i = 0; i < Line.size(); i++) { signed Side = std::atoi(Line[i].c_str()); if (RowTest.PushSide(Side)) { ValidRowTriangles++; } if (ColumnTest[i].PushSide(Side)) { ValidColumnTriangles++; } } } std::cout << "Valid Row Triangels: " << ValidRowTriangles << std::endl; std::cout << "Valid Column Triangels: " << ValidColumnTriangles << std::endl; system("pause"); }
18.619048
78
0.653453
jloehr
b4fd4b37363a84e15e006aa613d78fc3e3d59124
49,241
cpp
C++
Code/Engine/RendererCore/Debug/Implementation/DebugRenderer.cpp
autoint/ezEngine
4fcd72172791d2eeae1146428f3032e0da499f81
[ "MIT" ]
null
null
null
Code/Engine/RendererCore/Debug/Implementation/DebugRenderer.cpp
autoint/ezEngine
4fcd72172791d2eeae1146428f3032e0da499f81
[ "MIT" ]
null
null
null
Code/Engine/RendererCore/Debug/Implementation/DebugRenderer.cpp
autoint/ezEngine
4fcd72172791d2eeae1146428f3032e0da499f81
[ "MIT" ]
1
2022-03-28T15:57:46.000Z
2022-03-28T15:57:46.000Z
#include <RendererCorePCH.h> #include <Core/Graphics/Geometry.h> #include <Core/World/World.h> #include <Foundation/Configuration/Startup.h> #include <RendererCore/Debug/DebugRenderer.h> #include <RendererCore/Debug/SimpleASCIIFont.h> #include <RendererCore/Meshes/MeshBufferResource.h> #include <RendererCore/Pipeline/ViewData.h> #include <RendererCore/RenderContext/RenderContext.h> #include <RendererCore/RenderWorld/RenderWorld.h> #include <RendererCore/Shader/ShaderResource.h> #include <RendererCore/Textures/Texture2DResource.h> ////////////////////////////////////////////////////////////////////////// ezDebugRendererContext::ezDebugRendererContext(const ezWorld* pWorld) : m_Id(pWorld != nullptr ? pWorld->GetIndex() : 0) { } ezDebugRendererContext::ezDebugRendererContext(const ezViewHandle& hView) : m_Id(hView.GetInternalID().m_Data) { } ////////////////////////////////////////////////////////////////////////// namespace { struct EZ_ALIGN_16(Vertex) { ezVec3 m_position; ezColorLinearUB m_color; }; EZ_CHECK_AT_COMPILETIME(sizeof(Vertex) == 16); struct EZ_ALIGN_16(TexVertex) { ezVec3 m_position; ezColorLinearUB m_color; ezVec2 m_texCoord; float padding[2]; }; EZ_CHECK_AT_COMPILETIME(sizeof(TexVertex) == 32); struct EZ_ALIGN_16(BoxData) { ezShaderTransform m_transform; ezColor m_color; }; EZ_CHECK_AT_COMPILETIME(sizeof(BoxData) == 64); struct EZ_ALIGN_16(GlyphData) { ezVec2 m_topLeftCorner; ezColorLinearUB m_color; ezUInt16 m_glyphIndex; ezUInt16 m_sizeInPixel; }; EZ_CHECK_AT_COMPILETIME(sizeof(GlyphData) == 16); struct TextLineData2D { ezString m_text; ezVec2 m_topLeftCorner; ezColorLinearUB m_color; ezUInt32 m_uiSizeInPixel; }; struct TextLineData3D : public TextLineData2D { ezVec3 m_position; }; struct PerContextData { ezDynamicArray<Vertex, ezAlignedAllocatorWrapper> m_lineVertices; ezDynamicArray<Vertex, ezAlignedAllocatorWrapper> m_triangleVertices; ezDynamicArray<Vertex, ezAlignedAllocatorWrapper> m_triangle2DVertices; ezDynamicArray<Vertex, ezAlignedAllocatorWrapper> m_line2DVertices; ezDynamicArray<BoxData, ezAlignedAllocatorWrapper> m_lineBoxes; ezDynamicArray<BoxData, ezAlignedAllocatorWrapper> m_solidBoxes; ezMap<ezTexture2DResourceHandle, ezDynamicArray<TexVertex, ezAlignedAllocatorWrapper>> m_texTriangle2DVertices; ezMap<ezTexture2DResourceHandle, ezDynamicArray<TexVertex, ezAlignedAllocatorWrapper>> m_texTriangle3DVertices; ezDynamicArray<TextLineData2D> m_textLines2D; ezDynamicArray<TextLineData3D> m_textLines3D; ezDynamicArray<GlyphData, ezAlignedAllocatorWrapper> m_glyphs; }; struct DoubleBufferedPerContextData { DoubleBufferedPerContextData() { m_uiLastRenderedFrame = 0; m_pData[0] = nullptr; m_pData[1] = nullptr; } ezUInt64 m_uiLastRenderedFrame; ezUniquePtr<PerContextData> m_pData[2]; }; static ezHashTable<ezDebugRendererContext, DoubleBufferedPerContextData> s_PerContextData; static ezMutex s_Mutex; static PerContextData& GetDataForExtraction(const ezDebugRendererContext& context) { DoubleBufferedPerContextData& doubleBufferedData = s_PerContextData[context]; const ezUInt32 uiDataIndex = ezRenderWorld::IsRenderingThread() && (doubleBufferedData.m_uiLastRenderedFrame != ezRenderWorld::GetFrameCounter()) ? ezRenderWorld::GetDataIndexForRendering() : ezRenderWorld::GetDataIndexForExtraction(); ezUniquePtr<PerContextData>& pData = doubleBufferedData.m_pData[uiDataIndex]; if (pData == nullptr) { doubleBufferedData.m_pData[uiDataIndex] = EZ_DEFAULT_NEW(PerContextData); } return *pData; } static void ClearRenderData() { EZ_LOCK(s_Mutex); for (auto it = s_PerContextData.GetIterator(); it.IsValid(); ++it) { PerContextData* pData = it.Value().m_pData[ezRenderWorld::GetDataIndexForRendering()].Borrow(); if (pData) { pData->m_lineVertices.Clear(); pData->m_line2DVertices.Clear(); pData->m_lineBoxes.Clear(); pData->m_solidBoxes.Clear(); pData->m_triangleVertices.Clear(); pData->m_triangle2DVertices.Clear(); pData->m_texTriangle2DVertices.Clear(); pData->m_texTriangle3DVertices.Clear(); pData->m_textLines2D.Clear(); pData->m_textLines3D.Clear(); } } } static void OnRenderEvent(const ezRenderWorldRenderEvent& e) { if (e.m_Type == ezRenderWorldRenderEvent::Type::EndRender) { ClearRenderData(); } } struct BufferType { enum Enum { Lines, LineBoxes, SolidBoxes, Triangles3D, Triangles2D, TexTriangles2D, TexTriangles3D, Glyphs, Lines2D, Count }; }; static ezGALBufferHandle s_hDataBuffer[BufferType::Count]; static ezMeshBufferResourceHandle s_hLineBoxMeshBuffer; static ezMeshBufferResourceHandle s_hSolidBoxMeshBuffer; static ezVertexDeclarationInfo s_VertexDeclarationInfo; static ezVertexDeclarationInfo s_TexVertexDeclarationInfo; static ezTexture2DResourceHandle s_hDebugFontTexture; static ezShaderResourceHandle s_hDebugGeometryShader; static ezShaderResourceHandle s_hDebugPrimitiveShader; static ezShaderResourceHandle s_hDebugTexturedPrimitiveShader; static ezShaderResourceHandle s_hDebugTextShader; enum { DEBUG_BUFFER_SIZE = 1024 * 256, BOXES_PER_BATCH = DEBUG_BUFFER_SIZE / sizeof(BoxData), LINE_VERTICES_PER_BATCH = DEBUG_BUFFER_SIZE / sizeof(Vertex), TRIANGLE_VERTICES_PER_BATCH = (DEBUG_BUFFER_SIZE / sizeof(Vertex) / 3) * 3, TEX_TRIANGLE_VERTICES_PER_BATCH = (DEBUG_BUFFER_SIZE / sizeof(TexVertex) / 3) * 3, GLYPHS_PER_BATCH = DEBUG_BUFFER_SIZE / sizeof(GlyphData), }; static void CreateDataBuffer(BufferType::Enum bufferType, ezUInt32 uiStructSize) { if (s_hDataBuffer[bufferType].IsInvalidated()) { ezGALBufferCreationDescription desc; desc.m_uiStructSize = uiStructSize; desc.m_uiTotalSize = DEBUG_BUFFER_SIZE; desc.m_BufferType = ezGALBufferType::Generic; desc.m_bUseAsStructuredBuffer = true; desc.m_bAllowShaderResourceView = true; desc.m_ResourceAccess.m_bImmutable = false; s_hDataBuffer[bufferType] = ezGALDevice::GetDefaultDevice()->CreateBuffer(desc); } } static void CreateVertexBuffer(BufferType::Enum bufferType, ezUInt32 uiVertexSize) { if (s_hDataBuffer[bufferType].IsInvalidated()) { ezGALBufferCreationDescription desc; desc.m_uiStructSize = uiVertexSize; desc.m_uiTotalSize = DEBUG_BUFFER_SIZE; desc.m_BufferType = ezGALBufferType::VertexBuffer; desc.m_ResourceAccess.m_bImmutable = false; s_hDataBuffer[bufferType] = ezGALDevice::GetDefaultDevice()->CreateBuffer(desc); } } static void DestroyBuffer(BufferType::Enum bufferType) { ezGALDevice* pDevice = ezGALDevice::GetDefaultDevice(); if (!s_hDataBuffer[bufferType].IsInvalidated()) { pDevice->DestroyBuffer(s_hDataBuffer[bufferType]); s_hDataBuffer[bufferType].Invalidate(); } } template <typename AddFunc> static void AddTextLines(const ezDebugRendererContext& context, ezStringView text, const ezVec2I32& positionInPixel, float fSizeInPixel, ezDebugRenderer::HorizontalAlignment::Enum horizontalAlignment, ezDebugRenderer::VerticalAlignment::Enum verticalAlignment, AddFunc func) { if (text.IsEmpty()) return; ezHybridArray<ezStringView, 8> lines; ezUInt32 maxLineLength = 0; ezStringBuilder sb; if (text.FindSubString("\n")) { sb = text; sb.Split(false, lines, "\n"); for (auto& line : lines) { maxLineLength = ezMath::Max(maxLineLength, line.GetElementCount()); } } else { lines.PushBack(text); maxLineLength = text.GetElementCount(); } // Glyphs only use 8x10 pixels in their 16x16 pixel block, thus we don't advance by full size here. const float fGlyphWidth = ezMath::Ceil(fSizeInPixel * (8.0f / 16.0f)); const float fLineHeight = ezMath::Ceil(fSizeInPixel * (20.0f / 16.0f)); float screenPosX = (float)positionInPixel.x; if (horizontalAlignment == ezDebugRenderer::HorizontalAlignment::Right) screenPosX -= maxLineLength * fGlyphWidth; float screenPosY = (float)positionInPixel.y; if (verticalAlignment == ezDebugRenderer::VerticalAlignment::Center) screenPosY -= ezMath::Ceil(lines.GetCount() * fLineHeight * 0.5f); else if (verticalAlignment == ezDebugRenderer::VerticalAlignment::Bottom) screenPosY -= lines.GetCount() * fLineHeight; { EZ_LOCK(s_Mutex); auto& data = GetDataForExtraction(context); ezVec2 currentPos(screenPosX, screenPosY); for (ezStringView line : lines) { currentPos.x = screenPosX; if (horizontalAlignment == ezDebugRenderer::HorizontalAlignment::Center) currentPos.x -= ezMath::Ceil(line.GetElementCount() * fGlyphWidth * 0.5f); func(data, line, currentPos); currentPos.y += fLineHeight; } } } static void AppendGlyphs(ezDynamicArray<GlyphData, ezAlignedAllocatorWrapper>& glyphs, const TextLineData2D& textLine) { ezVec2 currentPos = textLine.m_topLeftCorner; const float fGlyphWidth = ezMath::Ceil(textLine.m_uiSizeInPixel * (8.0f / 16.0f)); for (ezUInt32 uiCharacter : textLine.m_text) { auto& glyphData = glyphs.ExpandAndGetRef(); glyphData.m_topLeftCorner = currentPos; glyphData.m_color = textLine.m_color; glyphData.m_glyphIndex = uiCharacter < 128 ? uiCharacter : 0; glyphData.m_sizeInPixel = (ezUInt16)textLine.m_uiSizeInPixel; currentPos.x += fGlyphWidth; } } } // namespace // clang-format off EZ_BEGIN_SUBSYSTEM_DECLARATION(RendererCore, DebugRenderer) BEGIN_SUBSYSTEM_DEPENDENCIES "Foundation", "Core" END_SUBSYSTEM_DEPENDENCIES ON_HIGHLEVELSYSTEMS_STARTUP { ezDebugRenderer::OnEngineStartup(); } ON_HIGHLEVELSYSTEMS_SHUTDOWN { ezDebugRenderer::OnEngineShutdown(); } EZ_END_SUBSYSTEM_DECLARATION; // clang-format on // static void ezDebugRenderer::DrawLines(const ezDebugRendererContext& context, ezArrayPtr<const Line> lines, const ezColor& color, const ezTransform& transform /*= ezTransform::IdentityTransform()*/) { if (lines.IsEmpty()) return; EZ_LOCK(s_Mutex); auto& data = GetDataForExtraction(context); for (auto& line : lines) { const ezVec3* pPositions = &line.m_start; const ezColor* pColors = &line.m_startColor; for (ezUInt32 i = 0; i < 2; ++i) { auto& vertex = data.m_lineVertices.ExpandAndGetRef(); vertex.m_position = transform.TransformPosition(pPositions[i]); vertex.m_color = pColors[i] * color; } } } void ezDebugRenderer::Draw2DLines(const ezDebugRendererContext& context, ezArrayPtr<const Line> lines, const ezColor& color) { if (lines.IsEmpty()) return; EZ_LOCK(s_Mutex); auto& data = GetDataForExtraction(context); for (auto& line : lines) { const ezVec3* pPositions = &line.m_start; for (ezUInt32 i = 0; i < 2; ++i) { auto& vertex = data.m_line2DVertices.ExpandAndGetRef(); vertex.m_position = pPositions[i]; vertex.m_color = color; } } } // static void ezDebugRenderer::DrawCross(const ezDebugRendererContext& context, const ezVec3& globalPosition, float fLineLength, const ezColor& color, const ezTransform& transform /*= ezTransform::IdentityTransform()*/) { if (fLineLength <= 0.0f) return; const float fHalfLineLength = fLineLength * 0.5f; const ezVec3 xAxis = ezVec3::UnitXAxis() * fHalfLineLength; const ezVec3 yAxis = ezVec3::UnitYAxis() * fHalfLineLength; const ezVec3 zAxis = ezVec3::UnitZAxis() * fHalfLineLength; Line lines[3] = {{transform.TransformPosition(globalPosition - xAxis), transform.TransformPosition(globalPosition + xAxis)}, {transform.TransformPosition(globalPosition - yAxis), transform.TransformPosition(globalPosition + yAxis)}, {transform.TransformPosition(globalPosition - zAxis), transform.TransformPosition(globalPosition + zAxis)}}; DrawLines(context, lines, color); } // static void ezDebugRenderer::DrawLineBox(const ezDebugRendererContext& context, const ezBoundingBox& box, const ezColor& color, const ezTransform& transform) { EZ_LOCK(s_Mutex); auto& data = GetDataForExtraction(context); auto& boxData = data.m_lineBoxes.ExpandAndGetRef(); ezTransform boxTransform(box.GetCenter(), ezQuat::IdentityQuaternion(), box.GetHalfExtents()); boxData.m_transform = transform * boxTransform; boxData.m_color = color; } // static void ezDebugRenderer::DrawLineBoxCorners(const ezDebugRendererContext& context, const ezBoundingBox& box, float fCornerFraction, const ezColor& color, const ezTransform& transform) { fCornerFraction = ezMath::Clamp(fCornerFraction, 0.0f, 1.0f) * 0.5f; ezVec3 corners[8]; box.GetCorners(corners); for (ezUInt32 i = 0; i < 8; ++i) { corners[i] = transform * corners[i]; } ezVec3 edgeEnds[12]; edgeEnds[0] = corners[1]; // 0 -> 1 edgeEnds[1] = corners[3]; // 1 -> 3 edgeEnds[2] = corners[0]; // 2 -> 0 edgeEnds[3] = corners[2]; // 3 -> 2 edgeEnds[4] = corners[5]; // 4 -> 5 edgeEnds[5] = corners[7]; // 5 -> 7 edgeEnds[6] = corners[4]; // 6 -> 4 edgeEnds[7] = corners[6]; // 7 -> 6 edgeEnds[8] = corners[4]; // 0 -> 4 edgeEnds[9] = corners[5]; // 1 -> 5 edgeEnds[10] = corners[6]; // 2 -> 6 edgeEnds[11] = corners[7]; // 3 -> 7 Line lines[24]; for (ezUInt32 i = 0; i < 12; ++i) { ezVec3 edgeStart = corners[i % 8]; ezVec3 edgeEnd = edgeEnds[i]; ezVec3 edgeDir = edgeEnd - edgeStart; lines[i * 2 + 0].m_start = edgeStart; lines[i * 2 + 0].m_end = edgeStart + edgeDir * fCornerFraction; lines[i * 2 + 1].m_start = edgeEnd; lines[i * 2 + 1].m_end = edgeEnd - edgeDir * fCornerFraction; } DrawLines(context, lines, color); } // static void ezDebugRenderer::DrawLineSphere(const ezDebugRendererContext& context, const ezBoundingSphere& sphere, const ezColor& color, const ezTransform& transform /*= ezTransform::IdentityTransform()*/) { enum { NUM_SEGMENTS = 32 }; const ezVec3 vCenter = sphere.m_vCenter; const float fRadius = sphere.m_fRadius; const ezAngle stepAngle = ezAngle::Degree(360.0f / NUM_SEGMENTS); Line lines[NUM_SEGMENTS * 3]; for (ezUInt32 s = 0; s < NUM_SEGMENTS; ++s) { const float fS1 = (float)s; const float fS2 = (float)(s + 1); const float fCos1 = ezMath::Cos(fS1 * stepAngle); const float fCos2 = ezMath::Cos(fS2 * stepAngle); const float fSin1 = ezMath::Sin(fS1 * stepAngle); const float fSin2 = ezMath::Sin(fS2 * stepAngle); lines[s * 3 + 0].m_start = transform * (vCenter + ezVec3(0.0f, fCos1, fSin1) * fRadius); lines[s * 3 + 0].m_end = transform * (vCenter + ezVec3(0.0f, fCos2, fSin2) * fRadius); lines[s * 3 + 1].m_start = transform * (vCenter + ezVec3(fCos1, 0.0f, fSin1) * fRadius); lines[s * 3 + 1].m_end = transform * (vCenter + ezVec3(fCos2, 0.0f, fSin2) * fRadius); lines[s * 3 + 2].m_start = transform * (vCenter + ezVec3(fCos1, fSin1, 0.0f) * fRadius); lines[s * 3 + 2].m_end = transform * (vCenter + ezVec3(fCos2, fSin2, 0.0f) * fRadius); } DrawLines(context, lines, color); } void ezDebugRenderer::DrawLineCapsuleZ(const ezDebugRendererContext& context, float fLength, float fRadius, const ezColor& color, const ezTransform& transform /*= ezTransform::IdentityTransform()*/) { enum { NUM_SEGMENTS = 32, NUM_HALF_SEGMENTS = 16, NUM_LINES = NUM_SEGMENTS + NUM_SEGMENTS + NUM_SEGMENTS + NUM_SEGMENTS + 4, }; const ezAngle stepAngle = ezAngle::Degree(360.0f / NUM_SEGMENTS); Line lines[NUM_LINES]; const float fOffsetZ = fLength * 0.5f; ezUInt32 curLine = 0; // render 4 straight lines lines[curLine].m_start = transform * ezVec3(-fRadius, 0, fOffsetZ); lines[curLine].m_end = transform * ezVec3(-fRadius, 0, -fOffsetZ); ++curLine; lines[curLine].m_start = transform * ezVec3(+fRadius, 0, fOffsetZ); lines[curLine].m_end = transform * ezVec3(+fRadius, 0, -fOffsetZ); ++curLine; lines[curLine].m_start = transform * ezVec3(0, -fRadius, fOffsetZ); lines[curLine].m_end = transform * ezVec3(0, -fRadius, -fOffsetZ); ++curLine; lines[curLine].m_start = transform * ezVec3(0, +fRadius, fOffsetZ); lines[curLine].m_end = transform * ezVec3(0, +fRadius, -fOffsetZ); ++curLine; // render top and bottom circle for (ezUInt32 s = 0; s < NUM_SEGMENTS; ++s) { const float fS1 = (float)s; const float fS2 = (float)(s + 1); const float fCos1 = ezMath::Cos(fS1 * stepAngle); const float fCos2 = ezMath::Cos(fS2 * stepAngle); const float fSin1 = ezMath::Sin(fS1 * stepAngle); const float fSin2 = ezMath::Sin(fS2 * stepAngle); lines[curLine].m_start = transform * ezVec3(fCos1 * fRadius, fSin1 * fRadius, fOffsetZ); lines[curLine].m_end = transform * ezVec3(fCos2 * fRadius, fSin2 * fRadius, fOffsetZ); ++curLine; lines[curLine].m_start = transform * ezVec3(fCos1 * fRadius, fSin1 * fRadius, -fOffsetZ); lines[curLine].m_end = transform * ezVec3(fCos2 * fRadius, fSin2 * fRadius, -fOffsetZ); ++curLine; } // render top and bottom half circles for (ezUInt32 s = 0; s < NUM_HALF_SEGMENTS; ++s) { const float fS1 = (float)s; const float fS2 = (float)(s + 1); const float fCos1 = ezMath::Cos(fS1 * stepAngle); const float fCos2 = ezMath::Cos(fS2 * stepAngle); const float fSin1 = ezMath::Sin(fS1 * stepAngle); const float fSin2 = ezMath::Sin(fS2 * stepAngle); // top two bows lines[curLine].m_start = transform * ezVec3(0.0f, fCos1 * fRadius, fSin1 * fRadius + fOffsetZ); lines[curLine].m_end = transform * ezVec3(0.0f, fCos2 * fRadius, fSin2 * fRadius + fOffsetZ); ++curLine; lines[curLine].m_start = transform * ezVec3(fCos1 * fRadius, 0.0f, fSin1 * fRadius + fOffsetZ); lines[curLine].m_end = transform * ezVec3(fCos2 * fRadius, 0.0f, fSin2 * fRadius + fOffsetZ); ++curLine; // bottom two bows lines[curLine].m_start = transform * ezVec3(0.0f, fCos1 * fRadius, -fSin1 * fRadius - fOffsetZ); lines[curLine].m_end = transform * ezVec3(0.0f, fCos2 * fRadius, -fSin2 * fRadius - fOffsetZ); ++curLine; lines[curLine].m_start = transform * ezVec3(fCos1 * fRadius, 0.0f, -fSin1 * fRadius - fOffsetZ); lines[curLine].m_end = transform * ezVec3(fCos2 * fRadius, 0.0f, -fSin2 * fRadius - fOffsetZ); ++curLine; } EZ_ASSERT_DEBUG(curLine == NUM_LINES, "Invalid line count"); DrawLines(context, lines, color); } // static void ezDebugRenderer::DrawLineFrustum(const ezDebugRendererContext& context, const ezFrustum& frustum, const ezColor& color, bool bDrawPlaneNormals /*= false*/) { ezVec3 cornerPoints[8]; frustum.ComputeCornerPoints(cornerPoints); Line lines[12] = { Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft], cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft]), Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomRight], cornerPoints[ezFrustum::FrustumCorner::FarBottomRight]), Line(cornerPoints[ezFrustum::FrustumCorner::NearTopLeft], cornerPoints[ezFrustum::FrustumCorner::FarTopLeft]), Line(cornerPoints[ezFrustum::FrustumCorner::NearTopRight], cornerPoints[ezFrustum::FrustumCorner::FarTopRight]), Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft], cornerPoints[ezFrustum::FrustumCorner::NearBottomRight]), Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomRight], cornerPoints[ezFrustum::FrustumCorner::NearTopRight]), Line(cornerPoints[ezFrustum::FrustumCorner::NearTopRight], cornerPoints[ezFrustum::FrustumCorner::NearTopLeft]), Line(cornerPoints[ezFrustum::FrustumCorner::NearTopLeft], cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft]), Line(cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft], cornerPoints[ezFrustum::FrustumCorner::FarBottomRight]), Line(cornerPoints[ezFrustum::FrustumCorner::FarBottomRight], cornerPoints[ezFrustum::FrustumCorner::FarTopRight]), Line(cornerPoints[ezFrustum::FrustumCorner::FarTopRight], cornerPoints[ezFrustum::FrustumCorner::FarTopLeft]), Line(cornerPoints[ezFrustum::FrustumCorner::FarTopLeft], cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft]), }; DrawLines(context, lines, color); if (bDrawPlaneNormals) { ezColor normalColor = color + ezColor(0.4f, 0.4f, 0.4f); float fDrawLength = 0.5f; const ezVec3 nearPlaneNormal = frustum.GetPlane(0).m_vNormal * fDrawLength; const ezVec3 farPlaneNormal = frustum.GetPlane(1).m_vNormal * fDrawLength; const ezVec3 leftPlaneNormal = frustum.GetPlane(2).m_vNormal * fDrawLength; const ezVec3 rightPlaneNormal = frustum.GetPlane(3).m_vNormal * fDrawLength; const ezVec3 bottomPlaneNormal = frustum.GetPlane(4).m_vNormal * fDrawLength; const ezVec3 topPlaneNormal = frustum.GetPlane(5).m_vNormal * fDrawLength; Line normalLines[24] = { Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft], cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft] + nearPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomRight], cornerPoints[ezFrustum::FrustumCorner::NearBottomRight] + nearPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::NearTopLeft], cornerPoints[ezFrustum::FrustumCorner::NearTopLeft] + nearPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::NearTopRight], cornerPoints[ezFrustum::FrustumCorner::NearTopRight] + nearPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft], cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft] + farPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::FarBottomRight], cornerPoints[ezFrustum::FrustumCorner::FarBottomRight] + farPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::FarTopLeft], cornerPoints[ezFrustum::FrustumCorner::FarTopLeft] + farPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::FarTopRight], cornerPoints[ezFrustum::FrustumCorner::FarTopRight] + farPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft], cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft] + leftPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::NearTopLeft], cornerPoints[ezFrustum::FrustumCorner::NearTopLeft] + leftPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft], cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft] + leftPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::FarTopLeft], cornerPoints[ezFrustum::FrustumCorner::FarTopLeft] + leftPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomRight], cornerPoints[ezFrustum::FrustumCorner::NearBottomRight] + rightPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::NearTopRight], cornerPoints[ezFrustum::FrustumCorner::NearTopRight] + rightPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::FarBottomRight], cornerPoints[ezFrustum::FrustumCorner::FarBottomRight] + rightPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::FarTopRight], cornerPoints[ezFrustum::FrustumCorner::FarTopRight] + rightPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft], cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft] + bottomPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomRight], cornerPoints[ezFrustum::FrustumCorner::NearBottomRight] + bottomPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft], cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft] + bottomPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::FarBottomRight], cornerPoints[ezFrustum::FrustumCorner::FarBottomRight] + bottomPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::NearTopLeft], cornerPoints[ezFrustum::FrustumCorner::NearTopLeft] + topPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::NearTopRight], cornerPoints[ezFrustum::FrustumCorner::NearTopRight] + topPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::FarTopLeft], cornerPoints[ezFrustum::FrustumCorner::FarTopLeft] + topPlaneNormal), Line(cornerPoints[ezFrustum::FrustumCorner::FarTopRight], cornerPoints[ezFrustum::FrustumCorner::FarTopRight] + topPlaneNormal), }; DrawLines(context, normalLines, normalColor); } } // static void ezDebugRenderer::DrawSolidBox(const ezDebugRendererContext& context, const ezBoundingBox& box, const ezColor& color, const ezTransform& transform) { EZ_LOCK(s_Mutex); auto& data = GetDataForExtraction(context); auto& boxData = data.m_solidBoxes.ExpandAndGetRef(); ezTransform boxTransform(box.GetCenter(), ezQuat::IdentityQuaternion(), box.GetHalfExtents()); boxData.m_transform = transform * boxTransform; boxData.m_color = color; } // static void ezDebugRenderer::DrawSolidTriangles(const ezDebugRendererContext& context, ezArrayPtr<Triangle> triangles, const ezColor& color) { if (triangles.IsEmpty()) return; EZ_LOCK(s_Mutex); auto& data = GetDataForExtraction(context); for (auto& triangle : triangles) { for (ezUInt32 i = 0; i < 3; ++i) { auto& vertex = data.m_triangleVertices.ExpandAndGetRef(); vertex.m_position = triangle.m_position[i]; vertex.m_color = color; } } } void ezDebugRenderer::DrawTexturedTriangles(const ezDebugRendererContext& context, ezArrayPtr<TexturedTriangle> triangles, const ezColor& color, const ezTexture2DResourceHandle& hTexture) { if (triangles.IsEmpty()) return; EZ_LOCK(s_Mutex); auto& data = GetDataForExtraction(context).m_texTriangle3DVertices[hTexture]; for (auto& triangle : triangles) { for (ezUInt32 i = 0; i < 3; ++i) { auto& vertex = data.ExpandAndGetRef(); vertex.m_position = triangle.m_position[i]; vertex.m_texCoord = triangle.m_texcoord[i]; vertex.m_color = color; } } } void ezDebugRenderer::Draw2DRectangle(const ezDebugRendererContext& context, const ezRectFloat& rectInPixel, float fDepth, const ezColor& color) { Vertex vertices[6]; vertices[0].m_position = ezVec3(rectInPixel.Left(), rectInPixel.Top(), fDepth); vertices[1].m_position = ezVec3(rectInPixel.Right(), rectInPixel.Bottom(), fDepth); vertices[2].m_position = ezVec3(rectInPixel.Left(), rectInPixel.Bottom(), fDepth); vertices[3].m_position = ezVec3(rectInPixel.Left(), rectInPixel.Top(), fDepth); vertices[4].m_position = ezVec3(rectInPixel.Right(), rectInPixel.Top(), fDepth); vertices[5].m_position = ezVec3(rectInPixel.Right(), rectInPixel.Bottom(), fDepth); for (ezUInt32 i = 0; i < EZ_ARRAY_SIZE(vertices); ++i) { vertices[i].m_color = color; } EZ_LOCK(s_Mutex); auto& data = GetDataForExtraction(context); data.m_triangle2DVertices.PushBackRange(ezMakeArrayPtr(vertices)); } void ezDebugRenderer::Draw2DRectangle(const ezDebugRendererContext& context, const ezRectFloat& rectInPixel, float fDepth, const ezColor& color, const ezTexture2DResourceHandle& hTexture) { TexVertex vertices[6]; vertices[0].m_position = ezVec3(rectInPixel.Left(), rectInPixel.Top(), fDepth); vertices[0].m_texCoord = ezVec2(0, 0); vertices[1].m_position = ezVec3(rectInPixel.Right(), rectInPixel.Bottom(), fDepth); vertices[1].m_texCoord = ezVec2(1, 1); vertices[2].m_position = ezVec3(rectInPixel.Left(), rectInPixel.Bottom(), fDepth); vertices[2].m_texCoord = ezVec2(0, 1); vertices[3].m_position = ezVec3(rectInPixel.Left(), rectInPixel.Top(), fDepth); vertices[3].m_texCoord = ezVec2(0, 0); vertices[4].m_position = ezVec3(rectInPixel.Right(), rectInPixel.Top(), fDepth); vertices[4].m_texCoord = ezVec2(1, 0); vertices[5].m_position = ezVec3(rectInPixel.Right(), rectInPixel.Bottom(), fDepth); vertices[5].m_texCoord = ezVec2(1, 1); for (ezUInt32 i = 0; i < EZ_ARRAY_SIZE(vertices); ++i) { vertices[i].m_color = color; } EZ_LOCK(s_Mutex); auto& data = GetDataForExtraction(context); data.m_texTriangle2DVertices[hTexture].PushBackRange(ezMakeArrayPtr(vertices)); } void ezDebugRenderer::Draw2DText(const ezDebugRendererContext& context, const ezStringView& text, const ezVec2I32& positionInPixel, const ezColor& color, ezUInt32 uiSizeInPixel /*= 16*/, HorizontalAlignment::Enum horizontalAlignment /*= HorizontalAlignment::Left*/, VerticalAlignment::Enum verticalAlignment /*= VerticalAlignment::Top*/) { AddTextLines(context, text, positionInPixel, (float)uiSizeInPixel, horizontalAlignment, verticalAlignment, [=](PerContextData& data, ezStringView line, ezVec2 topLeftCorner) { auto& textLine = data.m_textLines2D.ExpandAndGetRef(); textLine.m_text = line; textLine.m_topLeftCorner = topLeftCorner; textLine.m_color = color; textLine.m_uiSizeInPixel = uiSizeInPixel; }); } void ezDebugRenderer::Draw3DText(const ezDebugRendererContext& context, const ezStringView& text, const ezVec3& globalPosition, const ezColor& color, ezUInt32 uiSizeInPixel /*= 16*/, HorizontalAlignment::Enum horizontalAlignment /*= HorizontalAlignment::Left*/, VerticalAlignment::Enum verticalAlignment /*= VerticalAlignment::Top*/) { AddTextLines(context, text, ezVec2I32(0), (float)uiSizeInPixel, horizontalAlignment, verticalAlignment, [=](PerContextData& data, ezStringView line, ezVec2 topLeftCorner) { auto& textLine = data.m_textLines3D.ExpandAndGetRef(); textLine.m_text = line; textLine.m_topLeftCorner = topLeftCorner; textLine.m_color = color; textLine.m_uiSizeInPixel = uiSizeInPixel; textLine.m_position = globalPosition; }); } // static void ezDebugRenderer::Render(const ezRenderViewContext& renderViewContext) { if (renderViewContext.m_pWorldDebugContext != nullptr) { RenderInternal(*renderViewContext.m_pWorldDebugContext, renderViewContext); } if (renderViewContext.m_pViewDebugContext != nullptr) { RenderInternal(*renderViewContext.m_pViewDebugContext, renderViewContext); } } // static void ezDebugRenderer::RenderInternal(const ezDebugRendererContext& context, const ezRenderViewContext& renderViewContext) { DoubleBufferedPerContextData* pDoubleBufferedContextData = nullptr; if (!s_PerContextData.TryGetValue(context, pDoubleBufferedContextData)) { return; } pDoubleBufferedContextData->m_uiLastRenderedFrame = ezRenderWorld::GetFrameCounter(); PerContextData* pData = pDoubleBufferedContextData->m_pData[ezRenderWorld::GetDataIndexForRendering()].Borrow(); if (pData == nullptr) { return; } ezGALDevice* pDevice = ezGALDevice::GetDefaultDevice(); ezGALCommandEncoder* pGALCommandEncoder = renderViewContext.m_pRenderContext->GetCommandEncoder(); // SolidBoxes { ezUInt32 uiNumSolidBoxes = pData->m_solidBoxes.GetCount(); if (uiNumSolidBoxes != 0) { CreateDataBuffer(BufferType::SolidBoxes, sizeof(BoxData)); renderViewContext.m_pRenderContext->BindShader(s_hDebugGeometryShader); renderViewContext.m_pRenderContext->BindBuffer("boxData", pDevice->GetDefaultResourceView(s_hDataBuffer[BufferType::SolidBoxes])); renderViewContext.m_pRenderContext->BindMeshBuffer(s_hSolidBoxMeshBuffer); const BoxData* pSolidBoxData = pData->m_solidBoxes.GetData(); while (uiNumSolidBoxes > 0) { const ezUInt32 uiNumSolidBoxesInBatch = ezMath::Min<ezUInt32>(uiNumSolidBoxes, BOXES_PER_BATCH); pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::SolidBoxes], 0, ezMakeArrayPtr(pSolidBoxData, uiNumSolidBoxesInBatch).ToByteArray()); unsigned int uiRenderedInstances = uiNumSolidBoxesInBatch; if (renderViewContext.m_pCamera->IsStereoscopic()) uiRenderedInstances *= 2; renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult(); uiNumSolidBoxes -= uiNumSolidBoxesInBatch; pSolidBoxData += BOXES_PER_BATCH; } } } // Triangles { ezUInt32 uiNumTriangleVertices = pData->m_triangleVertices.GetCount(); if (uiNumTriangleVertices != 0) { CreateVertexBuffer(BufferType::Triangles3D, sizeof(Vertex)); renderViewContext.m_pRenderContext->SetShaderPermutationVariable("PRE_TRANSFORMED_VERTICES", "FALSE"); renderViewContext.m_pRenderContext->BindShader(s_hDebugPrimitiveShader); const Vertex* pTriangleData = pData->m_triangleVertices.GetData(); while (uiNumTriangleVertices > 0) { const ezUInt32 uiNumTriangleVerticesInBatch = ezMath::Min<ezUInt32>(uiNumTriangleVertices, TRIANGLE_VERTICES_PER_BATCH); EZ_ASSERT_DEV(uiNumTriangleVerticesInBatch % 3 == 0, "Vertex count must be a multiple of 3."); pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::Triangles3D], 0, ezMakeArrayPtr(pTriangleData, uiNumTriangleVerticesInBatch).ToByteArray()); renderViewContext.m_pRenderContext->BindMeshBuffer(s_hDataBuffer[BufferType::Triangles3D], ezGALBufferHandle(), &s_VertexDeclarationInfo, ezGALPrimitiveTopology::Triangles, uiNumTriangleVerticesInBatch / 3); unsigned int uiRenderedInstances = 1; if (renderViewContext.m_pCamera->IsStereoscopic()) uiRenderedInstances *= 2; renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult(); uiNumTriangleVertices -= uiNumTriangleVerticesInBatch; pTriangleData += TRIANGLE_VERTICES_PER_BATCH; } } } // 3D Lines { ezUInt32 uiNumLineVertices = pData->m_lineVertices.GetCount(); if (uiNumLineVertices != 0) { CreateVertexBuffer(BufferType::Lines, sizeof(Vertex)); renderViewContext.m_pRenderContext->SetShaderPermutationVariable("PRE_TRANSFORMED_VERTICES", "FALSE"); renderViewContext.m_pRenderContext->BindShader(s_hDebugPrimitiveShader); const Vertex* pLineData = pData->m_lineVertices.GetData(); while (uiNumLineVertices > 0) { const ezUInt32 uiNumLineVerticesInBatch = ezMath::Min<ezUInt32>(uiNumLineVertices, LINE_VERTICES_PER_BATCH); EZ_ASSERT_DEV(uiNumLineVerticesInBatch % 2 == 0, "Vertex count must be a multiple of 2."); pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::Lines], 0, ezMakeArrayPtr(pLineData, uiNumLineVerticesInBatch).ToByteArray()); renderViewContext.m_pRenderContext->BindMeshBuffer(s_hDataBuffer[BufferType::Lines], ezGALBufferHandle(), &s_VertexDeclarationInfo, ezGALPrimitiveTopology::Lines, uiNumLineVerticesInBatch / 2); unsigned int uiRenderedInstances = 1; if (renderViewContext.m_pCamera->IsStereoscopic()) uiRenderedInstances *= 2; renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult(); uiNumLineVertices -= uiNumLineVerticesInBatch; pLineData += LINE_VERTICES_PER_BATCH; } } } // 2D Lines { ezUInt32 uiNumLineVertices = pData->m_line2DVertices.GetCount(); if (uiNumLineVertices != 0) { CreateVertexBuffer(BufferType::Lines2D, sizeof(Vertex)); renderViewContext.m_pRenderContext->SetShaderPermutationVariable("PRE_TRANSFORMED_VERTICES", "TRUE"); renderViewContext.m_pRenderContext->BindShader(s_hDebugPrimitiveShader); const Vertex* pLineData = pData->m_line2DVertices.GetData(); while (uiNumLineVertices > 0) { const ezUInt32 uiNumLineVerticesInBatch = ezMath::Min<ezUInt32>(uiNumLineVertices, LINE_VERTICES_PER_BATCH); EZ_ASSERT_DEV(uiNumLineVerticesInBatch % 2 == 0, "Vertex count must be a multiple of 2."); pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::Lines2D], 0, ezMakeArrayPtr(pLineData, uiNumLineVerticesInBatch).ToByteArray()); renderViewContext.m_pRenderContext->BindMeshBuffer(s_hDataBuffer[BufferType::Lines2D], ezGALBufferHandle(), &s_VertexDeclarationInfo, ezGALPrimitiveTopology::Lines, uiNumLineVerticesInBatch / 2); unsigned int uiRenderedInstances = 1; if (renderViewContext.m_pCamera->IsStereoscopic()) uiRenderedInstances *= 2; renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult(); uiNumLineVertices -= uiNumLineVerticesInBatch; pLineData += LINE_VERTICES_PER_BATCH; } } } // LineBoxes { ezUInt32 uiNumLineBoxes = pData->m_lineBoxes.GetCount(); if (uiNumLineBoxes != 0) { CreateDataBuffer(BufferType::LineBoxes, sizeof(BoxData)); renderViewContext.m_pRenderContext->BindShader(s_hDebugGeometryShader); renderViewContext.m_pRenderContext->BindBuffer("boxData", pDevice->GetDefaultResourceView(s_hDataBuffer[BufferType::LineBoxes])); renderViewContext.m_pRenderContext->BindMeshBuffer(s_hLineBoxMeshBuffer); const BoxData* pLineBoxData = pData->m_lineBoxes.GetData(); while (uiNumLineBoxes > 0) { const ezUInt32 uiNumLineBoxesInBatch = ezMath::Min<ezUInt32>(uiNumLineBoxes, BOXES_PER_BATCH); pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::LineBoxes], 0, ezMakeArrayPtr(pLineBoxData, uiNumLineBoxesInBatch).ToByteArray()); unsigned int uiRenderedInstances = uiNumLineBoxesInBatch; if (renderViewContext.m_pCamera->IsStereoscopic()) uiRenderedInstances *= 2; renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult(); uiNumLineBoxes -= uiNumLineBoxesInBatch; pLineBoxData += BOXES_PER_BATCH; } } } // 2D Rectangles { ezUInt32 uiNum2DVertices = pData->m_triangle2DVertices.GetCount(); if (uiNum2DVertices != 0) { CreateVertexBuffer(BufferType::Triangles2D, sizeof(Vertex)); renderViewContext.m_pRenderContext->SetShaderPermutationVariable("PRE_TRANSFORMED_VERTICES", "TRUE"); renderViewContext.m_pRenderContext->BindShader(s_hDebugPrimitiveShader); const Vertex* pTriangleData = pData->m_triangle2DVertices.GetData(); while (uiNum2DVertices > 0) { const ezUInt32 uiNum2DVerticesInBatch = ezMath::Min<ezUInt32>(uiNum2DVertices, TRIANGLE_VERTICES_PER_BATCH); EZ_ASSERT_DEV(uiNum2DVerticesInBatch % 3 == 0, "Vertex count must be a multiple of 3."); pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::Triangles2D], 0, ezMakeArrayPtr(pTriangleData, uiNum2DVerticesInBatch).ToByteArray()); renderViewContext.m_pRenderContext->BindMeshBuffer(s_hDataBuffer[BufferType::Triangles2D], ezGALBufferHandle(), &s_VertexDeclarationInfo, ezGALPrimitiveTopology::Triangles, uiNum2DVerticesInBatch / 3); unsigned int uiRenderedInstances = 1; if (renderViewContext.m_pCamera->IsStereoscopic()) uiRenderedInstances *= 2; renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult(); uiNum2DVertices -= uiNum2DVerticesInBatch; pTriangleData += TRIANGLE_VERTICES_PER_BATCH; } } } // Textured 2D triangles { for (auto itTex = pData->m_texTriangle2DVertices.GetIterator(); itTex.IsValid(); ++itTex) { renderViewContext.m_pRenderContext->BindTexture2D("BaseTexture", itTex.Key()); const auto& verts = itTex.Value(); ezUInt32 uiNum2DVertices = verts.GetCount(); if (uiNum2DVertices != 0) { CreateVertexBuffer(BufferType::TexTriangles2D, sizeof(TexVertex)); renderViewContext.m_pRenderContext->SetShaderPermutationVariable("PRE_TRANSFORMED_VERTICES", "TRUE"); renderViewContext.m_pRenderContext->BindShader(s_hDebugTexturedPrimitiveShader); const TexVertex* pTriangleData = verts.GetData(); while (uiNum2DVertices > 0) { const ezUInt32 uiNum2DVerticesInBatch = ezMath::Min<ezUInt32>(uiNum2DVertices, TEX_TRIANGLE_VERTICES_PER_BATCH); EZ_ASSERT_DEV(uiNum2DVerticesInBatch % 3 == 0, "Vertex count must be a multiple of 3."); pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::TexTriangles2D], 0, ezMakeArrayPtr(pTriangleData, uiNum2DVerticesInBatch).ToByteArray()); renderViewContext.m_pRenderContext->BindMeshBuffer(s_hDataBuffer[BufferType::TexTriangles2D], ezGALBufferHandle(), &s_TexVertexDeclarationInfo, ezGALPrimitiveTopology::Triangles, uiNum2DVerticesInBatch / 3); unsigned int uiRenderedInstances = 1; if (renderViewContext.m_pCamera->IsStereoscopic()) uiRenderedInstances *= 2; renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult(); uiNum2DVertices -= uiNum2DVerticesInBatch; pTriangleData += TEX_TRIANGLE_VERTICES_PER_BATCH; } } } } // Textured 3D triangles { for (auto itTex = pData->m_texTriangle3DVertices.GetIterator(); itTex.IsValid(); ++itTex) { renderViewContext.m_pRenderContext->BindTexture2D("BaseTexture", itTex.Key()); const auto& verts = itTex.Value(); ezUInt32 uiNumVertices = verts.GetCount(); if (uiNumVertices != 0) { CreateVertexBuffer(BufferType::TexTriangles3D, sizeof(TexVertex)); renderViewContext.m_pRenderContext->SetShaderPermutationVariable("PRE_TRANSFORMED_VERTICES", "FALSE"); renderViewContext.m_pRenderContext->BindShader(s_hDebugTexturedPrimitiveShader); const TexVertex* pTriangleData = verts.GetData(); while (uiNumVertices > 0) { const ezUInt32 uiNumVerticesInBatch = ezMath::Min<ezUInt32>(uiNumVertices, TEX_TRIANGLE_VERTICES_PER_BATCH); EZ_ASSERT_DEV(uiNumVerticesInBatch % 3 == 0, "Vertex count must be a multiple of 3."); pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::TexTriangles3D], 0, ezMakeArrayPtr(pTriangleData, uiNumVerticesInBatch).ToByteArray()); renderViewContext.m_pRenderContext->BindMeshBuffer(s_hDataBuffer[BufferType::TexTriangles3D], ezGALBufferHandle(), &s_TexVertexDeclarationInfo, ezGALPrimitiveTopology::Triangles, uiNumVerticesInBatch / 3); unsigned int uiRenderedInstances = 1; if (renderViewContext.m_pCamera->IsStereoscopic()) uiRenderedInstances *= 2; renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult(); uiNumVertices -= uiNumVerticesInBatch; pTriangleData += TEX_TRIANGLE_VERTICES_PER_BATCH; } } } } // Text { pData->m_glyphs.Clear(); for (auto& textLine : pData->m_textLines3D) { ezVec3 screenPos; if (renderViewContext.m_pViewData->ComputeScreenSpacePos(textLine.m_position, screenPos).Succeeded() && screenPos.z > 0.0f) { textLine.m_topLeftCorner.x += ezMath::Round(screenPos.x); textLine.m_topLeftCorner.y += ezMath::Round(screenPos.y); AppendGlyphs(pData->m_glyphs, textLine); } } for (auto& textLine : pData->m_textLines2D) { AppendGlyphs(pData->m_glyphs, textLine); } ezUInt32 uiNumGlyphs = pData->m_glyphs.GetCount(); if (uiNumGlyphs != 0) { CreateDataBuffer(BufferType::Glyphs, sizeof(GlyphData)); renderViewContext.m_pRenderContext->BindShader(s_hDebugTextShader); renderViewContext.m_pRenderContext->BindBuffer("glyphData", pDevice->GetDefaultResourceView(s_hDataBuffer[BufferType::Glyphs])); renderViewContext.m_pRenderContext->BindTexture2D("FontTexture", s_hDebugFontTexture); const GlyphData* pGlyphData = pData->m_glyphs.GetData(); while (uiNumGlyphs > 0) { const ezUInt32 uiNumGlyphsInBatch = ezMath::Min<ezUInt32>(uiNumGlyphs, GLYPHS_PER_BATCH); pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::Glyphs], 0, ezMakeArrayPtr(pGlyphData, uiNumGlyphsInBatch).ToByteArray()); renderViewContext.m_pRenderContext->BindMeshBuffer(ezGALBufferHandle(), ezGALBufferHandle(), nullptr, ezGALPrimitiveTopology::Triangles, uiNumGlyphsInBatch * 2); unsigned int uiRenderedInstances = 1; if (renderViewContext.m_pCamera->IsStereoscopic()) uiRenderedInstances *= 2; renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult(); uiNumGlyphs -= uiNumGlyphsInBatch; pGlyphData += GLYPHS_PER_BATCH; } } } } void ezDebugRenderer::OnEngineStartup() { { ezGeometry geom; geom.AddLineBox(ezVec3(2.0f), ezColor::White); ezMeshBufferResourceDescriptor desc; desc.AddStream(ezGALVertexAttributeSemantic::Position, ezGALResourceFormat::XYZFloat); desc.AllocateStreamsFromGeometry(geom, ezGALPrimitiveTopology::Lines); s_hLineBoxMeshBuffer = ezResourceManager::CreateResource<ezMeshBufferResource>("DebugLineBox", std::move(desc), "Mesh for Rendering Debug Line Boxes"); } { ezGeometry geom; geom.AddBox(ezVec3(2.0f), ezColor::White); ezMeshBufferResourceDescriptor desc; desc.AddStream(ezGALVertexAttributeSemantic::Position, ezGALResourceFormat::XYZFloat); desc.AllocateStreamsFromGeometry(geom, ezGALPrimitiveTopology::Triangles); s_hSolidBoxMeshBuffer = ezResourceManager::CreateResource<ezMeshBufferResource>("DebugSolidBox", std::move(desc), "Mesh for Rendering Debug Solid Boxes"); } { // reset, if already used before s_VertexDeclarationInfo.m_VertexStreams.Clear(); { ezVertexStreamInfo& si = s_VertexDeclarationInfo.m_VertexStreams.ExpandAndGetRef(); si.m_Semantic = ezGALVertexAttributeSemantic::Position; si.m_Format = ezGALResourceFormat::XYZFloat; si.m_uiOffset = 0; si.m_uiElementSize = 12; } { ezVertexStreamInfo& si = s_VertexDeclarationInfo.m_VertexStreams.ExpandAndGetRef(); si.m_Semantic = ezGALVertexAttributeSemantic::Color0; si.m_Format = ezGALResourceFormat::RGBAUByteNormalized; si.m_uiOffset = 12; si.m_uiElementSize = 4; } } { // reset, if already used before s_TexVertexDeclarationInfo.m_VertexStreams.Clear(); { ezVertexStreamInfo& si = s_TexVertexDeclarationInfo.m_VertexStreams.ExpandAndGetRef(); si.m_Semantic = ezGALVertexAttributeSemantic::Position; si.m_Format = ezGALResourceFormat::XYZFloat; si.m_uiOffset = 0; si.m_uiElementSize = 12; } { ezVertexStreamInfo& si = s_TexVertexDeclarationInfo.m_VertexStreams.ExpandAndGetRef(); si.m_Semantic = ezGALVertexAttributeSemantic::Color0; si.m_Format = ezGALResourceFormat::RGBAUByteNormalized; si.m_uiOffset = 12; si.m_uiElementSize = 4; } { ezVertexStreamInfo& si = s_TexVertexDeclarationInfo.m_VertexStreams.ExpandAndGetRef(); si.m_Semantic = ezGALVertexAttributeSemantic::TexCoord0; si.m_Format = ezGALResourceFormat::XYFloat; si.m_uiOffset = 16; si.m_uiElementSize = 8; } { ezVertexStreamInfo& si = s_TexVertexDeclarationInfo.m_VertexStreams.ExpandAndGetRef(); si.m_Semantic = ezGALVertexAttributeSemantic::TexCoord1; // padding si.m_Format = ezGALResourceFormat::XYFloat; si.m_uiOffset = 24; si.m_uiElementSize = 8; } } { ezImage debugFontImage; ezGraphicsUtils::CreateSimpleASCIIFontTexture(debugFontImage); ezGALSystemMemoryDescription memoryDesc; memoryDesc.m_pData = debugFontImage.GetPixelPointer<ezUInt8>(); memoryDesc.m_uiRowPitch = static_cast<ezUInt32>(debugFontImage.GetRowPitch()); memoryDesc.m_uiSlicePitch = static_cast<ezUInt32>(debugFontImage.GetDepthPitch()); ezTexture2DResourceDescriptor desc; desc.m_DescGAL.m_uiWidth = debugFontImage.GetWidth(); desc.m_DescGAL.m_uiHeight = debugFontImage.GetHeight(); desc.m_DescGAL.m_Format = ezGALResourceFormat::RGBAUByteNormalized; desc.m_InitialContent = ezMakeArrayPtr(&memoryDesc, 1); s_hDebugFontTexture = ezResourceManager::CreateResource<ezTexture2DResource>("DebugFontTexture", std::move(desc)); } s_hDebugGeometryShader = ezResourceManager::LoadResource<ezShaderResource>("Shaders/Debug/DebugGeometry.ezShader"); s_hDebugPrimitiveShader = ezResourceManager::LoadResource<ezShaderResource>("Shaders/Debug/DebugPrimitive.ezShader"); s_hDebugTexturedPrimitiveShader = ezResourceManager::LoadResource<ezShaderResource>("Shaders/Debug/DebugTexturedPrimitive.ezShader"); s_hDebugTextShader = ezResourceManager::LoadResource<ezShaderResource>("Shaders/Debug/DebugText.ezShader"); ezRenderWorld::GetRenderEvent().AddEventHandler(&OnRenderEvent); } void ezDebugRenderer::OnEngineShutdown() { ezRenderWorld::GetRenderEvent().RemoveEventHandler(&OnRenderEvent); for (ezUInt32 i = 0; i < BufferType::Count; ++i) { DestroyBuffer(static_cast<BufferType::Enum>(i)); } s_hLineBoxMeshBuffer.Invalidate(); s_hSolidBoxMeshBuffer.Invalidate(); s_hDebugFontTexture.Invalidate(); s_hDebugGeometryShader.Invalidate(); s_hDebugPrimitiveShader.Invalidate(); s_hDebugTexturedPrimitiveShader.Invalidate(); s_hDebugTextShader.Invalidate(); s_PerContextData.Clear(); } EZ_STATICLINK_FILE(RendererCore, RendererCore_Debug_Implementation_DebugRenderer);
38.590125
276
0.730347
autoint
b4fec66f6482b86d26b9c51e614b5a28808d92c1
2,697
cpp
C++
src/AcadosSolver.cpp
TorBorve/mpc_local_planner
b237f9df5ff77d4f7282c4df1469ab357e56237e
[ "MIT" ]
3
2021-12-15T06:51:02.000Z
2021-12-20T11:56:11.000Z
src/AcadosSolver.cpp
TorBorve/mpc-local-planner
b237f9df5ff77d4f7282c4df1469ab357e56237e
[ "MIT" ]
3
2021-12-17T12:22:28.000Z
2022-02-19T22:18:44.000Z
src/AcadosSolver.cpp
TorBorve/mpc-local-planner
b237f9df5ff77d4f7282c4df1469ab357e56237e
[ "MIT" ]
4
2021-12-15T06:51:15.000Z
2022-03-05T13:09:51.000Z
#include "mpc_local_planner/AcadosSolver.h" #include <ros/ros.h> namespace mpc { namespace Acados { void Solver::reInit(const State &state) { freeAllocated(); init(); setInitGuess(state); return; } void Solver::setInitCondition(const State &state) { // initial condition auto x0 = state.toArray(); std::vector<int> idxbx0(x0.size()); // int idxbx0[x0.size()]; for (int i = 0; i < x0.size(); i++) { idxbx0[i] = i; } ocp_nlp_constraints_model_set(config_, dims_, in_, 0, "idxbx", &idxbx0[0]); ocp_nlp_constraints_model_set(config_, dims_, in_, 0, "lbx", &x0[0]); ocp_nlp_constraints_model_set(config_, dims_, in_, 0, "ubx", &x0[0]); } MPCReturn Solver::solve(const State &state, const Params &params) { auto start = std::chrono::high_resolution_clock::now(); int N = dims_->N; setInitCondition(state); setParams(params); // prepare evaluation int NTIMINGS = 1; std::vector<double> xtraj(nx_ * (N + 1)); std::vector<double> utraj(nx_ * (N)); // solve ocp in loop int rti_phase = 0; int status; for (int ii = 0; ii < NTIMINGS; ii++) { ocp_nlp_solver_opts_set(config_, opts_, "rti_phase", &rti_phase); status = acadosSolve(); } // get the solution for (int ii = 0; ii <= dims_->N; ii++) ocp_nlp_out_get(config_, dims_, out_, ii, "x", &xtraj[ii * nx_]); for (int ii = 0; ii < dims_->N; ii++) ocp_nlp_out_get(config_, dims_, out_, ii, "u", &utraj[ii * nu_]); if (status != ACADOS_SUCCESS) { ROS_ERROR("acados_solve() failed with status %d.\n", status); reInit(state); } auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); MPCReturn ret; ret.mpcHorizon.resize(N); for (int i = 0; i < N; i++) { State state(&xtraj[nx_ * i], nx_); Input input(&utraj[nu_ * i], nu_); ret.mpcHorizon.at(i) = OptVariables{state, input}; } ret.u0 = ret.mpcHorizon.at(0).u; ret.cost = -1; ret.success = status == ACADOS_SUCCESS; ret.computeTime = duration.count(); return ret; } void Solver::setInitGuess(const State &state) { auto x_init = state.toArray(); assert(x_init.size() == nx_); // initial value for control input std::vector<double> u0(nu_); for (int i = 0; i < nu_; i++) { u0[0] = 0; } // initialize solution for (int i = 0; i <= dims_->N; i++) { ocp_nlp_out_set(config_, dims_, out_, i, "x", &x_init[0]); ocp_nlp_out_set(config_, dims_, out_, i, "u", &u0[0]); } } } // namespace Acados } // namespace mpc
28.389474
87
0.597701
TorBorve
b4fed554f2fa465ed8e518e96ba2280aa1491091
11,816
cc
C++
src/analyzer/protocol/pia/PIA.cc
ThalesGroup/zeek
c28fd3b6108b76059387ddc144a861660af0a20a
[ "Apache-2.0" ]
null
null
null
src/analyzer/protocol/pia/PIA.cc
ThalesGroup/zeek
c28fd3b6108b76059387ddc144a861660af0a20a
[ "Apache-2.0" ]
null
null
null
src/analyzer/protocol/pia/PIA.cc
ThalesGroup/zeek
c28fd3b6108b76059387ddc144a861660af0a20a
[ "Apache-2.0" ]
null
null
null
#include "zeek/analyzer/protocol/pia/PIA.h" #include "zeek/DebugLogger.h" #include "zeek/Event.h" #include "zeek/IP.h" #include "zeek/NetVar.h" #include "zeek/Reporter.h" #include "zeek/RuleMatcher.h" #include "zeek/RunState.h" #include "zeek/analyzer/protocol/tcp/TCP_Flags.h" #include "zeek/analyzer/protocol/tcp/TCP_Reassembler.h" namespace zeek::analyzer::pia { PIA::PIA(analyzer::Analyzer* arg_as_analyzer) : state(INIT), as_analyzer(arg_as_analyzer), conn(), current_packet() { } PIA::~PIA() { ClearBuffer(&pkt_buffer); } void PIA::ClearBuffer(Buffer* buffer) { DataBlock* next = nullptr; for ( DataBlock* b = buffer->head; b; b = next ) { next = b->next; delete b->ip; delete[] b->data; delete b; } buffer->head = buffer->tail = nullptr; buffer->size = 0; } void PIA::AddToBuffer(Buffer* buffer, uint64_t seq, int len, const u_char* data, bool is_orig, const IP_Hdr* ip) { u_char* tmp = nullptr; if ( data ) { tmp = new u_char[len]; memcpy(tmp, data, len); } DataBlock* b = new DataBlock; b->ip = ip ? ip->Copy() : nullptr; b->data = tmp; b->is_orig = is_orig; b->len = len; b->seq = seq; b->next = nullptr; if ( buffer->tail ) { buffer->tail->next = b; buffer->tail = b; } else buffer->head = buffer->tail = b; if ( data ) buffer->size += len; } void PIA::AddToBuffer(Buffer* buffer, int len, const u_char* data, bool is_orig, const IP_Hdr* ip) { AddToBuffer(buffer, -1, len, data, is_orig, ip); } void PIA::ReplayPacketBuffer(analyzer::Analyzer* analyzer) { DBG_LOG(DBG_ANALYZER, "PIA replaying %d total packet bytes", pkt_buffer.size); for ( DataBlock* b = pkt_buffer.head; b; b = b->next ) analyzer->DeliverPacket(b->len, b->data, b->is_orig, -1, b->ip, 0); } void PIA::PIA_Done() { FinishEndpointMatcher(); } void PIA::PIA_DeliverPacket(int len, const u_char* data, bool is_orig, uint64_t seq, const IP_Hdr* ip, int caplen, bool clear_state) { if ( pkt_buffer.state == SKIPPING ) return; current_packet.data = data; current_packet.len = len; current_packet.seq = seq; current_packet.is_orig = is_orig; State new_state = pkt_buffer.state; if ( pkt_buffer.state == INIT ) new_state = BUFFERING; if ( (pkt_buffer.state == BUFFERING || new_state == BUFFERING) && len > 0 ) { AddToBuffer(&pkt_buffer, seq, len, data, is_orig, ip); if ( pkt_buffer.size > zeek::detail::dpd_buffer_size ) new_state = zeek::detail::dpd_match_only_beginning ? SKIPPING : MATCHING_ONLY; } // FIXME: I'm not sure why it does not work with eol=true... DoMatch(data, len, is_orig, true, false, false, ip); if ( clear_state ) zeek::detail::RuleMatcherState::ClearMatchState(is_orig); pkt_buffer.state = new_state; current_packet.data = nullptr; } void PIA::Match(zeek::detail::Rule::PatternType type, const u_char* data, int len, bool is_orig, bool bol, bool eol, bool clear_state) { if ( ! MatcherInitialized(is_orig) ) InitEndpointMatcher(AsAnalyzer(), nullptr, 0, is_orig, this); zeek::detail::RuleMatcherState::Match(type, data, len, is_orig, bol, eol, clear_state); } void PIA::DoMatch(const u_char* data, int len, bool is_orig, bool bol, bool eol, bool clear_state, const IP_Hdr* ip) { if ( ! zeek::detail::rule_matcher ) return; if ( ! zeek::detail::rule_matcher->HasNonFileMagicRule() ) return; if ( ! MatcherInitialized(is_orig) ) InitEndpointMatcher(AsAnalyzer(), ip, len, is_orig, this); zeek::detail::RuleMatcherState::Match(zeek::detail::Rule::PAYLOAD, data, len, is_orig, bol, eol, clear_state); } void PIA_UDP::ActivateAnalyzer(analyzer::Tag tag, const zeek::detail::Rule* rule) { if ( pkt_buffer.state == MATCHING_ONLY ) { DBG_LOG(DBG_ANALYZER, "analyzer found but buffer already exceeded"); // FIXME: This is where to check whether an analyzer // supports partial connections once we get such. if ( protocol_late_match ) { // Queue late match event if ( ! tag ) tag = GetAnalyzerTag(); const auto& tval = tag.AsVal(); event_mgr.Enqueue(protocol_late_match, ConnVal(), tval); } pkt_buffer.state = zeek::detail::dpd_late_match_stop ? SKIPPING : MATCHING_ONLY; return; } if ( Parent()->HasChildAnalyzer(tag) ) return; analyzer::Analyzer* a = Parent()->AddChildAnalyzer(tag); if ( ! a ) return; a->SetSignature(rule); ReplayPacketBuffer(a); } void PIA_UDP::DeactivateAnalyzer(analyzer::Tag tag) { reporter->InternalError("PIA_UDP::Deact not implemented yet"); } //// TCP PIA PIA_TCP::~PIA_TCP() { ClearBuffer(&stream_buffer); } void PIA_TCP::Init() { analyzer::tcp::TCP_ApplicationAnalyzer::Init(); if ( Parent()->IsAnalyzer("TCP") ) { auto* tcp = static_cast<packet_analysis::TCP::TCPSessionAdapter*>(Parent()); SetTCP(tcp); tcp->SetPIA(this); } } void PIA_TCP::FirstPacket(bool is_orig, const IP_Hdr* ip) { static char dummy_packet[sizeof(struct ip) + sizeof(struct tcphdr)]; static struct ip* ip4 = nullptr; static struct tcphdr* tcp4 = nullptr; static IP_Hdr* ip4_hdr = nullptr; DBG_LOG(DBG_ANALYZER, "PIA_TCP[%d] FirstPacket(%s)", GetID(), (is_orig ? "T" : "F")); if ( ! ip ) { // Create a dummy packet. Not very elegant, but everything // else would be *really* ugly ... if ( ! ip4_hdr ) { ip4 = (struct ip*)dummy_packet; tcp4 = (struct tcphdr*)(dummy_packet + sizeof(struct ip)); ip4->ip_len = sizeof(struct ip) + sizeof(struct tcphdr); ip4->ip_hl = sizeof(struct ip) >> 2; ip4->ip_p = IPPROTO_TCP; // Cast to const so that it doesn't delete it. ip4_hdr = new IP_Hdr(ip4, false); } // Locals used to avoid potentil alignment problems // with some archs/compilers when grabbing the address // of the struct member directly in the following. in_addr tmp_src; in_addr tmp_dst; if ( is_orig ) { Conn()->OrigAddr().CopyIPv4(&tmp_src); Conn()->RespAddr().CopyIPv4(&tmp_dst); tcp4->th_sport = htons(Conn()->OrigPort()); tcp4->th_dport = htons(Conn()->RespPort()); } else { Conn()->RespAddr().CopyIPv4(&tmp_src); Conn()->OrigAddr().CopyIPv4(&tmp_dst); tcp4->th_sport = htons(Conn()->RespPort()); tcp4->th_dport = htons(Conn()->OrigPort()); } ip4->ip_src = tmp_src; ip4->ip_dst = tmp_dst; ip = ip4_hdr; } if ( ! MatcherInitialized(is_orig) ) DoMatch((const u_char*)"", 0, is_orig, true, false, false, ip); } void PIA_TCP::DeliverStream(int len, const u_char* data, bool is_orig) { analyzer::tcp::TCP_ApplicationAnalyzer::DeliverStream(len, data, is_orig); if ( stream_buffer.state == SKIPPING ) return; stream_mode = true; State new_state = stream_buffer.state; if ( stream_buffer.state == INIT ) { // FIXME: clear payload-matching state here... new_state = BUFFERING; } if ( stream_buffer.state == BUFFERING || new_state == BUFFERING ) { AddToBuffer(&stream_buffer, len, data, is_orig); if ( stream_buffer.size > zeek::detail::dpd_buffer_size ) new_state = zeek::detail::dpd_match_only_beginning ? SKIPPING : MATCHING_ONLY; } DoMatch(data, len, is_orig, false, false, false, nullptr); stream_buffer.state = new_state; } void PIA_TCP::Undelivered(uint64_t seq, int len, bool is_orig) { analyzer::tcp::TCP_ApplicationAnalyzer::Undelivered(seq, len, is_orig); if ( stream_buffer.state == BUFFERING ) // We use data=nil to mark an undelivered. AddToBuffer(&stream_buffer, seq, len, nullptr, is_orig); // No check for buffer overrun here. I think that's ok. } void PIA_TCP::ActivateAnalyzer(analyzer::Tag tag, const zeek::detail::Rule* rule) { if ( stream_buffer.state == MATCHING_ONLY ) { DBG_LOG(DBG_ANALYZER, "analyzer found but buffer already exceeded"); // FIXME: This is where to check whether an analyzer supports // partial connections once we get such. if ( protocol_late_match ) { // Queue late match event if ( ! tag ) tag = GetAnalyzerTag(); const auto& tval = tag.AsVal(); event_mgr.Enqueue(protocol_late_match, ConnVal(), tval); } stream_buffer.state = zeek::detail::dpd_late_match_stop ? SKIPPING : MATCHING_ONLY; return; } analyzer::Analyzer* a = Parent()->AddChildAnalyzer(tag); if ( ! a ) return; a->SetSignature(rule); // We have two cases here: // // (a) We have already got stream input. // => Great, somebody's already reassembling and we can just // replay our stream buffer to the new analyzer. if ( stream_mode ) { ReplayStreamBuffer(a); return; } // (b) We have only got packet input so far (or none at all). // => We have to switch from packet-mode to stream-mode. // // Here's what we do: // // (1) We create new tcp::TCP_Reassemblers and feed them the buffered // packets. // // (2) The reassembler will give us their results via the // stream-interface and we buffer it as usual. // // (3) We replay the now-filled stream-buffer to the analyzer. // // (4) We hand the two reassemblers to the TCP Analyzer (our parent), // turning reassembly now on for all subsequent data. DBG_LOG(DBG_ANALYZER, "PIA_TCP switching from packet-mode to stream-mode"); stream_mode = true; // FIXME: The reassembler will query the endpoint for state. Not sure // if this is works in all cases... if ( ! Parent()->IsAnalyzer("TCP") ) { // Our parent is not the TCP analyzer, which can only mean // we have been inserted somewhere further down in the // analyzer tree. In this case, we will never have seen // any input at this point (because we don't get packets). assert(! pkt_buffer.head); assert(! stream_buffer.head); return; } auto* tcp = static_cast<packet_analysis::TCP::TCPSessionAdapter*>(Parent()); auto* reass_orig = new tcp::TCP_Reassembler(this, tcp, tcp::TCP_Reassembler::Direct, tcp->Orig()); auto* reass_resp = new tcp::TCP_Reassembler(this, tcp, tcp::TCP_Reassembler::Direct, tcp->Resp()); uint64_t orig_seq = 0; uint64_t resp_seq = 0; for ( DataBlock* b = pkt_buffer.head; b; b = b->next ) { // We don't have the TCP flags here during replay. We could // funnel them through, but it's non-trivial and doesn't seem // worth the effort. if ( b->is_orig ) reass_orig->DataSent(run_state::network_time, orig_seq = b->seq, b->len, b->data, tcp::TCP_Flags(), true); else reass_resp->DataSent(run_state::network_time, resp_seq = b->seq, b->len, b->data, tcp::TCP_Flags(), true); } // We also need to pass the current packet on. DataBlock* current = CurrentPacket(); if ( current->data ) { if ( current->is_orig ) reass_orig->DataSent(run_state::network_time, orig_seq = current->seq, current->len, current->data, analyzer::tcp::TCP_Flags(), true); else reass_resp->DataSent(run_state::network_time, resp_seq = current->seq, current->len, current->data, analyzer::tcp::TCP_Flags(), true); } ClearBuffer(&pkt_buffer); ReplayStreamBuffer(a); reass_orig->AckReceived(orig_seq); reass_resp->AckReceived(resp_seq); reass_orig->SetType(tcp::TCP_Reassembler::Forward); reass_resp->SetType(tcp::TCP_Reassembler::Forward); tcp->SetReassembler(reass_orig, reass_resp); } void PIA_TCP::DeactivateAnalyzer(analyzer::Tag tag) { reporter->InternalError("PIA_TCP::Deact not implemented yet"); } void PIA_TCP::ReplayStreamBuffer(analyzer::Analyzer* analyzer) { DBG_LOG(DBG_ANALYZER, "PIA_TCP replaying %d total stream bytes", stream_buffer.size); for ( DataBlock* b = stream_buffer.head; b; b = b->next ) { if ( b->data ) analyzer->NextStream(b->len, b->data, b->is_orig); else analyzer->NextUndelivered(b->seq, b->len, b->is_orig); } } } // namespace zeek::analyzer::pia
26.672686
98
0.671209
ThalesGroup
37003536421cc7186519a875e41bdbe254461a6d
5,366
hpp
C++
src/graphlab/rpc/object_request_issue.hpp
zgdahai/graphlabapi
7d66bbda82d4d44cded35f9438e1c9359b0ca64e
[ "ECL-2.0", "Apache-2.0" ]
1
2016-11-07T05:47:18.000Z
2016-11-07T05:47:18.000Z
src/graphlab/rpc/object_request_issue.hpp
keerthanashanmugam/graphlabapi
7d66bbda82d4d44cded35f9438e1c9359b0ca64e
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/graphlab/rpc/object_request_issue.hpp
keerthanashanmugam/graphlabapi
7d66bbda82d4d44cded35f9438e1c9359b0ca64e
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2009 Carnegie Mellon University. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * * For more about this software visit: * * http://www.graphlab.ml.cmu.edu * */ #ifndef OBJECT_REQUEST_ISSUE_HPP #define OBJECT_REQUEST_ISSUE_HPP #include <sstream> #include <iostream> #include <string> #include <graphlab/serialization/serialization_includes.hpp> #include <graphlab/rpc/dc_types.hpp> #include <graphlab/rpc/dc_internal_types.hpp> #include <graphlab/rpc/reply_increment_counter.hpp> #include <graphlab/rpc/object_request_dispatch.hpp> #include <graphlab/rpc/function_ret_type.hpp> #include <graphlab/rpc/mem_function_arg_types_def.hpp> #include <graphlab/rpc/request_future.hpp> #include <graphlab/rpc/archive_memory_pool.hpp> #include <graphlab/rpc/dc_compile_parameters.hpp> #include <boost/preprocessor.hpp> namespace graphlab { namespace dc_impl { #define GENARGS(Z,N,_) BOOST_PP_CAT(const T, N) BOOST_PP_CAT(&i, N) #define GENT(Z,N,_) BOOST_PP_CAT(T, N) #define GENARC(Z,N,_) arc << BOOST_PP_CAT(i, N); /** \internal \ingroup rpc \file object_request_issue.hpp This is an internal function and should not be used directly This is the marshall function for the an object member function call. This is very similar to the standard function request issue in request_issue.hpp , with the only difference that an object id has to be transmitted An annoyingly long sequence of type manipulations are needed to identify the return type. \code template<typename T, typename F , typename T0> class object_request_issue1 { public: static request_future<typename function_ret_type< typename boost::remove_const< typename boost::remove_reference< typename boost::function< typename boost::remove_member_pointer<F> ::type>::result_type>::type>::type>::type (void)> exec(dc_send* sender, unsigned char flags, procid_t target,size_t objid, F remote_function , const T0 &i0 ) { oarchive arc; arc.advance(sizeof(packet_hdr)); reply_ret_type reply(1); dispatch_type d = dc_impl::OBJECT_NONINTRUSIVE_REQUESTDISPATCH1<distributed_control,T,F , T0 >; arc << reinterpret_cast<size_t>(d); serialize(arc, (char*)(&remote_function), sizeof(remote_function)); arc << objid; arc << reinterpret_cast<size_t>(reply.reply.get()); arc << i0; sender->send_data(target, flags, arc.buf, arc.off); reply.wait(); iarchive iarc(reply.val.c, reply.val.len); typename function_ret_type< typename boost::remove_const< typename boost::remove_reference< typename boost::function< typename boost::remove_member_pointer<F> ::type>::result_type>::type>::type>::type result; iarc >> result; reply.val.free(); return result; } }; \endcode */ #define REMOTE_REQUEST_ISSUE_GENERATOR(Z,N,FNAME_AND_CALL) \ template<typename T,typename F BOOST_PP_COMMA_IF(N) BOOST_PP_ENUM_PARAMS(N, typename T)> \ class BOOST_PP_CAT(FNAME_AND_CALL, N) { \ public: \ static request_future<__GLRPC_FRESULT> exec(dc_dist_object_base* rmi, dc_send* sender, unsigned char flags, procid_t target,size_t objid, F remote_function BOOST_PP_COMMA_IF(N) BOOST_PP_ENUM(N,GENARGS ,_) ) { \ oarchive* ptr = oarchive_from_pool(); \ oarchive& arc = *ptr; \ arc.advance(sizeof(size_t) + sizeof(packet_hdr)); \ request_future<__GLRPC_FRESULT> reply; \ dispatch_type d = BOOST_PP_CAT(dc_impl::OBJECT_NONINTRUSIVE_REQUESTDISPATCH,N)<distributed_control,T,F BOOST_PP_COMMA_IF(N) BOOST_PP_ENUM(N, GENT ,_) >; \ arc << reinterpret_cast<size_t>(d); \ serialize(arc, (char*)(&remote_function), sizeof(remote_function)); \ arc << objid; \ arc << reinterpret_cast<size_t>(reply.reply.get()); \ BOOST_PP_REPEAT(N, GENARC, _) \ if (arc.off >= BUFFER_RELINQUISH_LIMIT) { \ sender->send_data(target,flags , arc.buf, arc.off); \ arc.buf = NULL; arc.len = 0; \ } else { \ char* newbuf = (char*)malloc(arc.off); memcpy(newbuf, arc.buf, arc.off); \ sender->send_data(target,flags , newbuf, arc.off); \ } \ release_oarchive_to_pool(ptr); \ if ((flags & CONTROL_PACKET) == 0) \ rmi->inc_bytes_sent(target, arc.off - sizeof(size_t)); \ return reply; \ }\ }; BOOST_PP_REPEAT(6, REMOTE_REQUEST_ISSUE_GENERATOR, object_request_issue ) #undef GENARC #undef GENT #undef GENARGS #undef REMOTE_REQUEST_ISSUE_GENERATOR } // namespace dc_impl } // namespace graphlab #include <graphlab/rpc/mem_function_arg_types_undef.hpp> #endif
36.013423
213
0.684122
zgdahai
3700ffd26095888ed88e80f7014e9b3c1a5932db
3,723
cpp
C++
YSQFace/src/main/cpp/facedetectcnn-jni.cpp
zhu260824/FaceDetection
99d5170dbcdac0da6c0c21b717b0ff42214790f0
[ "Apache-2.0" ]
2
2019-06-22T09:44:19.000Z
2019-06-27T00:58:12.000Z
YSQFace/src/main/cpp/facedetectcnn-jni.cpp
zhu260824/FaceDetection
99d5170dbcdac0da6c0c21b717b0ff42214790f0
[ "Apache-2.0" ]
null
null
null
YSQFace/src/main/cpp/facedetectcnn-jni.cpp
zhu260824/FaceDetection
99d5170dbcdac0da6c0c21b717b0ff42214790f0
[ "Apache-2.0" ]
2
2019-06-27T00:58:13.000Z
2021-01-04T18:11:30.000Z
#include <jni.h> #include <string> #include <android/log.h> #include "facedetectcnn.h" #include <opencv2/opencv.hpp> //define the buffer size. Do not change the size! #define DETECT_BUFFER_SIZE 0x20000 using namespace cv; extern "C" { char *JNITag = const_cast<char *>("face-jni"); JNIEXPORT jobjectArray JNICALL Java_com_zl_face_YSQFaceUtil_detectCNN(JNIEnv *env, jobject /* this */, jlong matAddr) { jobjectArray faceArgs = nullptr; Mat &img = *(Mat *) matAddr; Mat bgr = img.clone(); cvtColor(img, bgr, COLOR_RGBA2BGR); __android_log_print(ANDROID_LOG_INFO, JNITag, "convert RGBA to RGB"); if (bgr.empty()) { fprintf(stderr, "Can not convert image"); return faceArgs; } int *pResults = NULL; //pBuffer is used in the detection functions. //If you call functions in multiple threads, please create one buffer for each thread! unsigned char *pBuffer = (unsigned char *) malloc(DETECT_BUFFER_SIZE); if (!pBuffer) { fprintf(stderr, "Can not alloc buffer.\n"); return faceArgs; } /////////////////////////////////////////// // CNN face detection // Best detection rate ////////////////////////////////////////// //!!! The input image must be a RGB one (three-channel) //!!! DO NOT RELEASE pResults !!! pResults = facedetect_cnn(pBuffer, (unsigned char *) (bgr.ptr(0)), bgr.cols, bgr.rows,(int) bgr.step); int numOfFaces = pResults ? *pResults : 0; __android_log_print(ANDROID_LOG_INFO, JNITag, "%d faces detected.\n", numOfFaces); /** * 获取Face类以及其对于参数的签名 */ jclass faceClass = env->FindClass("com/zl/face/YSQFaceInfo");//获取Face类 jmethodID faceClassInitID = (env)->GetMethodID(faceClass, "<init>", "()V"); jfieldID faceConfidence = env->GetFieldID(faceClass, "faceConfidence","I");//获取int类型参数confidence jfieldID faceAngle = env->GetFieldID(faceClass, "faceAngle", "I");//获取int数组类型参数angle jfieldID faceRect = env->GetFieldID(faceClass, "faceRect","Landroid/graphics/Rect;");//获取faceRect的签名 /** * 获取RECT类以及对应参数的签名 */ jclass rectClass = env->FindClass("android/graphics/Rect");//获取到RECT类 jmethodID rectClassInitID = (env)->GetMethodID(rectClass, "<init>", "()V"); jfieldID rect_left = env->GetFieldID(rectClass, "left", "I");//获取x的签名 jfieldID rect_top = env->GetFieldID(rectClass, "top", "I");//获取y的签名 jfieldID rect_right = env->GetFieldID(rectClass, "right", "I");//获取width的签名 jfieldID rect_bottom = env->GetFieldID(rectClass, "bottom", "I");//获取height的签名 faceArgs = (env)->NewObjectArray(numOfFaces, faceClass, 0); //print the detection results for (int i = 0; i < (pResults ? *pResults : 0); i++) { short *p = ((short *) (pResults + 1)) + 142 * i; int x = p[0]; int y = p[1]; int w = p[2]; int h = p[3]; int confidence = p[4]; int angle = p[5]; __android_log_print(ANDROID_LOG_INFO, JNITag,"face_rect=[%d, %d, %d, %d], confidence=%d, angle=%d\n", x, y, w, h,confidence, angle); jobject newFace = (env)->NewObject(faceClass, faceClassInitID); jobject newRect = (env)->NewObject(rectClass, rectClassInitID); (env)->SetIntField(newRect, rect_left, x); (env)->SetIntField(newRect, rect_top, y); (env)->SetIntField(newRect, rect_right, x + w); (env)->SetIntField(newRect, rect_bottom, y + h); (env)->SetObjectField(newFace, faceRect, newRect); (env)->SetIntField(newFace, faceConfidence, confidence); (env)->SetIntField(newFace, faceAngle, angle); (env)->SetObjectArrayElement(faceArgs, i, newFace); } //release the buffer free(pBuffer); return faceArgs; } };
43.290698
140
0.633629
zhu260824
37044b7c153036b9e11efa48a25888f5832b52fe
27,213
cpp
C++
extras/Projucer/Source/Project/jucer_Module.cpp
Hanley1/JUCE
e583f7b9927cd5b47cf151b9f7210a727b68b572
[ "ISC" ]
null
null
null
extras/Projucer/Source/Project/jucer_Module.cpp
Hanley1/JUCE
e583f7b9927cd5b47cf151b9f7210a727b68b572
[ "ISC" ]
null
null
null
extras/Projucer/Source/Project/jucer_Module.cpp
Hanley1/JUCE
e583f7b9927cd5b47cf151b9f7210a727b68b572
[ "ISC" ]
null
null
null
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 5 End-User License Agreement and JUCE 5 Privacy Policy (both updated and effective as of the 27th April 2017). End User License Agreement: www.juce.com/juce-5-licence Privacy Policy: www.juce.com/juce-5-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ #include "../Application/jucer_Headers.h" #include "../ProjectSaving/jucer_ProjectSaver.h" #include "../ProjectSaving/jucer_ProjectExport_Xcode.h" #include "../Application/jucer_Application.h" //============================================================================== ModuleDescription::ModuleDescription (const File& folder) : moduleFolder (folder), moduleInfo (parseJUCEHeaderMetadata (getHeader())) { } File ModuleDescription::getHeader() const { if (moduleFolder != File()) { const char* extensions[] = { ".h", ".hpp", ".hxx" }; for (auto e : extensions) { auto header = moduleFolder.getChildFile (moduleFolder.getFileName() + e); if (header.existsAsFile()) return header; } } return {}; } StringArray ModuleDescription::getDependencies() const { auto deps = StringArray::fromTokens (moduleInfo ["dependencies"].toString(), " \t;,", "\"'"); deps.trim(); deps.removeEmptyStrings(); return deps; } //============================================================================== static bool tryToAddModuleFromFolder (const File& path, ModuleIDAndFolderList& list) { ModuleDescription m (path); if (m.isValid()) { list.push_back ({ m.getID(), path }); return true; } return false; } static void addAllModulesInSubfoldersRecursively (const File& path, int depth, ModuleIDAndFolderList& list) { if (depth > 0) { for (DirectoryIterator iter (path, false, "*", File::findDirectories); iter.next();) { if (auto* job = ThreadPoolJob::getCurrentThreadPoolJob()) if (job->shouldExit()) return; auto childPath = iter.getFile(); if (! tryToAddModuleFromFolder (childPath, list)) addAllModulesInSubfoldersRecursively (childPath, depth - 1, list); } } } static void addAllModulesInFolder (const File& path, ModuleIDAndFolderList& list) { if (! tryToAddModuleFromFolder (path, list)) { int subfolders = 3; addAllModulesInSubfoldersRecursively (path, subfolders, list); } } static void sort (ModuleIDAndFolderList& listToSort) { std::sort (listToSort.begin(), listToSort.end(), [] (const ModuleIDAndFolder& m1, const ModuleIDAndFolder& m2) { return m1.first.compareIgnoreCase (m2.first) < 0; }); } //============================================================================== struct ModuleScannerJob : public ThreadPoolJob { ModuleScannerJob (const Array<File>& paths, std::function<void (const ModuleIDAndFolderList&)>&& callback) : ThreadPoolJob ("ModuleScannerJob"), pathsToScan (paths), completionCallback (std::move (callback)) { } JobStatus runJob() override { ModuleIDAndFolderList list; for (auto& p : pathsToScan) addAllModulesInFolder (p, list); if (! shouldExit()) { sort (list); completionCallback (list); } return jobHasFinished; } Array<File> pathsToScan; std::function<void (const ModuleIDAndFolderList&)> completionCallback; }; AvailableModuleList::AvailableModuleList() { } ThreadPoolJob* AvailableModuleList::createScannerJob (const Array<File>& paths) { return new ModuleScannerJob (paths, [this] (ModuleIDAndFolderList scannedModuleList) { { const ScopedLock swapLock (lock); moduleList.swap (scannedModuleList); } listeners.call ([] (Listener& l) { MessageManager::callAsync ([&] { l.availableModulesChanged(); }); }); }); } void AvailableModuleList::removePendingAndAddJob (ThreadPoolJob* jobToAdd) { scanPool.removeAllJobs (false, 100); scanPool.addJob (jobToAdd, true); } void AvailableModuleList::scanPaths (const Array<File>& paths) { auto* job = createScannerJob (paths); removePendingAndAddJob (job); scanPool.waitForJobToFinish (job, -1); } void AvailableModuleList::scanPathsAsync (const Array<File>& paths) { removePendingAndAddJob (createScannerJob (paths)); } ModuleIDAndFolderList AvailableModuleList::getAllModules() const { const ScopedLock readLock (lock); return moduleList; } ModuleIDAndFolder AvailableModuleList::getModuleWithID (const String& id) const { const ScopedLock readLock (lock); for (auto& mod : moduleList) if (mod.first == id) return mod; return {}; } void AvailableModuleList::removeDuplicates (const ModuleIDAndFolderList& other) { const ScopedLock readLock (lock); for (auto& m : other) { auto pos = std::find (moduleList.begin(), moduleList.end(), m); if (pos != moduleList.end()) moduleList.erase (pos); } } //============================================================================== LibraryModule::LibraryModule (const ModuleDescription& d) : moduleInfo (d) { } //============================================================================== void LibraryModule::writeIncludes (ProjectSaver& projectSaver, OutputStream& out) { auto& project = projectSaver.project; auto& modules = project.getEnabledModules(); auto id = getID(); if (modules.shouldCopyModuleFilesLocally (id).getValue()) { auto juceModuleFolder = moduleInfo.getFolder(); auto localModuleFolder = project.getLocalModuleFolder (id); localModuleFolder.createDirectory(); projectSaver.copyFolder (juceModuleFolder, localModuleFolder); } out << "#include <" << moduleInfo.moduleFolder.getFileName() << "/" << moduleInfo.getHeader().getFileName() << ">" << newLine; } //============================================================================== static void parseAndAddLibs (StringArray& libList, const String& libs) { libList.addTokens (libs, ", ", {}); libList.trim(); libList.removeDuplicates (false); } void LibraryModule::addSettingsForModuleToExporter (ProjectExporter& exporter, ProjectSaver& projectSaver) const { auto& project = exporter.getProject(); auto moduleRelativePath = exporter.getModuleFolderRelativeToProject (getID()); exporter.addToExtraSearchPaths (moduleRelativePath.getParentDirectory()); String libDirPlatform; if (exporter.isLinux()) libDirPlatform = "Linux"; else if (exporter.isCodeBlocks() && exporter.isWindows()) libDirPlatform = "MinGW"; else libDirPlatform = exporter.getTargetFolder().getFileName(); auto libSubdirPath = moduleRelativePath.toUnixStyle() + "/libs/" + libDirPlatform; auto moduleLibDir = File (project.getProjectFolder().getFullPathName() + "/" + libSubdirPath); if (moduleLibDir.exists()) exporter.addToModuleLibPaths ({ libSubdirPath, moduleRelativePath.getRoot() }); auto extraInternalSearchPaths = moduleInfo.getExtraSearchPaths().trim(); if (extraInternalSearchPaths.isNotEmpty()) { auto paths = StringArray::fromTokens (extraInternalSearchPaths, true); for (auto& path : paths) exporter.addToExtraSearchPaths (moduleRelativePath.getChildFile (path.unquoted())); } { auto extraDefs = moduleInfo.getPreprocessorDefs().trim(); if (extraDefs.isNotEmpty()) exporter.getExporterPreprocessorDefsValue() = exporter.getExporterPreprocessorDefsString() + "\n" + extraDefs; } { Array<File> compiled; auto& modules = project.getEnabledModules(); auto id = getID(); auto localModuleFolder = modules.shouldCopyModuleFilesLocally (id).getValue() ? project.getLocalModuleFolder (id) : moduleInfo.getFolder(); findAndAddCompiledUnits (exporter, &projectSaver, compiled); if (modules.shouldShowAllModuleFilesInProject (id).getValue()) addBrowseableCode (exporter, compiled, localModuleFolder); } if (exporter.isXcode()) { auto& xcodeExporter = dynamic_cast<XcodeProjectExporter&> (exporter); if (project.isAUPluginHost()) xcodeExporter.xcodeFrameworks.addTokens (xcodeExporter.isOSX() ? "AudioUnit CoreAudioKit" : "CoreAudioKit", false); auto frameworks = moduleInfo.moduleInfo [xcodeExporter.isOSX() ? "OSXFrameworks" : "iOSFrameworks"].toString(); xcodeExporter.xcodeFrameworks.addTokens (frameworks, ", ", {}); parseAndAddLibs (xcodeExporter.xcodeLibs, moduleInfo.moduleInfo [exporter.isOSX() ? "OSXLibs" : "iOSLibs"].toString()); } else if (exporter.isLinux()) { parseAndAddLibs (exporter.linuxLibs, moduleInfo.moduleInfo ["linuxLibs"].toString()); parseAndAddLibs (exporter.linuxPackages, moduleInfo.moduleInfo ["linuxPackages"].toString()); } else if (exporter.isWindows()) { if (exporter.isCodeBlocks()) parseAndAddLibs (exporter.mingwLibs, moduleInfo.moduleInfo ["mingwLibs"].toString()); else parseAndAddLibs (exporter.windowsLibs, moduleInfo.moduleInfo ["windowsLibs"].toString()); } else if (exporter.isAndroid()) { parseAndAddLibs (exporter.androidLibs, moduleInfo.moduleInfo ["androidLibs"].toString()); } } void LibraryModule::getConfigFlags (Project& project, OwnedArray<Project::ConfigFlag>& flags) const { auto header = moduleInfo.getHeader(); jassert (header.exists()); StringArray lines; header.readLines (lines); for (int i = 0; i < lines.size(); ++i) { auto line = lines[i].trim(); if (line.startsWith ("/**") && line.containsIgnoreCase ("Config:")) { std::unique_ptr<Project::ConfigFlag> config (new Project::ConfigFlag()); config->sourceModuleID = getID(); config->symbol = line.fromFirstOccurrenceOf (":", false, false).trim(); if (config->symbol.length() > 2) { ++i; while (! (lines[i].contains ("*/") || lines[i].contains ("@see"))) { if (lines[i].trim().isNotEmpty()) config->description = config->description.trim() + " " + lines[i].trim(); ++i; } config->description = config->description.upToFirstOccurrenceOf ("*/", false, false); config->value = project.getConfigFlag (config->symbol); i += 2; if (lines[i].contains ("#define " + config->symbol)) { auto value = lines[i].fromFirstOccurrenceOf ("#define " + config->symbol, false, true).trim(); config->value.setDefault (value == "0" ? false : true); } auto currentValue = config->value.get().toString(); if (currentValue == "enabled") config->value = true; else if (currentValue == "disabled") config->value = false; flags.add (config.release()); } } } } //============================================================================== struct FileSorter { static int compareElements (const File& f1, const File& f2) { return f1.getFileName().compareNatural (f2.getFileName()); } }; bool LibraryModule::CompileUnit::hasSuffix (const File& f, const char* suffix) { auto fileWithoutSuffix = f.getFileNameWithoutExtension() + "."; return fileWithoutSuffix.containsIgnoreCase (suffix + String (".")) || fileWithoutSuffix.containsIgnoreCase (suffix + String ("_")); } void LibraryModule::CompileUnit::writeInclude (MemoryOutputStream&) const { } bool LibraryModule::CompileUnit::isNeededForExporter (ProjectExporter& exporter) const { if ((hasSuffix (file, "_OSX") && ! exporter.isOSX()) || (hasSuffix (file, "_iOS") && ! exporter.isiOS()) || (hasSuffix (file, "_Windows") && ! exporter.isWindows()) || (hasSuffix (file, "_Linux") && ! exporter.isLinux()) || (hasSuffix (file, "_Android") && ! exporter.isAndroid())) return false; auto targetType = Project::getTargetTypeFromFilePath (file, false); if (targetType != ProjectType::Target::unspecified && ! exporter.shouldBuildTargetType (targetType)) return false; return exporter.usesMMFiles() ? isCompiledForObjC : isCompiledForNonObjC; } String LibraryModule::CompileUnit::getFilenameForProxyFile() const { return "include_" + file.getFileName(); } Array<LibraryModule::CompileUnit> LibraryModule::getAllCompileUnits (ProjectType::Target::Type forTarget) const { auto files = getFolder().findChildFiles (File::findFiles, false); FileSorter sorter; files.sort (sorter); Array<LibraryModule::CompileUnit> units; for (auto& file : files) { if (file.getFileName().startsWithIgnoreCase (getID()) && file.hasFileExtension (sourceFileExtensions)) { if (forTarget == ProjectType::Target::unspecified || forTarget == Project::getTargetTypeFromFilePath (file, true)) { CompileUnit cu; cu.file = file; units.add (cu); } } } for (auto& cu : units) { cu.isCompiledForObjC = true; cu.isCompiledForNonObjC = ! cu.file.hasFileExtension ("mm;m"); if (cu.isCompiledForNonObjC) if (files.contains (cu.file.withFileExtension ("mm"))) cu.isCompiledForObjC = false; jassert (cu.isCompiledForObjC || cu.isCompiledForNonObjC); } return units; } void LibraryModule::findAndAddCompiledUnits (ProjectExporter& exporter, ProjectSaver* projectSaver, Array<File>& result, ProjectType::Target::Type forTarget) const { for (auto& cu : getAllCompileUnits (forTarget)) { if (cu.isNeededForExporter (exporter)) { auto localFile = exporter.getProject().getGeneratedCodeFolder() .getChildFile (cu.getFilenameForProxyFile()); result.add (localFile); if (projectSaver != nullptr) projectSaver->addFileToGeneratedGroup (localFile); } } } static void addFileWithGroups (Project::Item& group, const RelativePath& file, const String& path) { auto slash = path.indexOfChar (File::getSeparatorChar()); if (slash >= 0) { auto topLevelGroup = path.substring (0, slash); auto remainingPath = path.substring (slash + 1); auto newGroup = group.getOrCreateSubGroup (topLevelGroup); addFileWithGroups (newGroup, file, remainingPath); } else { if (! group.containsChildForFile (file)) group.addRelativeFile (file, -1, false); } } void LibraryModule::findBrowseableFiles (const File& folder, Array<File>& filesFound) const { Array<File> tempList; FileSorter sorter; DirectoryIterator iter (folder, true, "*", File::findFiles); bool isHiddenFile; while (iter.next (nullptr, &isHiddenFile, nullptr, nullptr, nullptr, nullptr)) if (! isHiddenFile && iter.getFile().hasFileExtension (browseableFileExtensions)) tempList.addSorted (sorter, iter.getFile()); filesFound.addArray (tempList); } void LibraryModule::addBrowseableCode (ProjectExporter& exporter, const Array<File>& compiled, const File& localModuleFolder) const { if (sourceFiles.isEmpty()) findBrowseableFiles (localModuleFolder, sourceFiles); auto sourceGroup = Project::Item::createGroup (exporter.getProject(), getID(), "__mainsourcegroup" + getID(), false); auto moduleFromProject = exporter.getModuleFolderRelativeToProject (getID()); auto moduleHeader = moduleInfo.getHeader(); for (auto& sourceFile : sourceFiles) { auto pathWithinModule = FileHelpers::getRelativePathFrom (sourceFile, localModuleFolder); // (Note: in exporters like MSVC we have to avoid adding the same file twice, even if one of those instances // is flagged as being excluded from the build, because this overrides the other and it fails to compile) if ((exporter.canCopeWithDuplicateFiles() || ! compiled.contains (sourceFile)) && sourceFile != moduleHeader) addFileWithGroups (sourceGroup, moduleFromProject.getChildFile (pathWithinModule), pathWithinModule); } sourceGroup.sortAlphabetically (true, true); sourceGroup.addFileAtIndex (moduleHeader, -1, false); exporter.getModulesGroup().state.appendChild (sourceGroup.state.createCopy(), nullptr); } //============================================================================== EnabledModuleList::EnabledModuleList (Project& p, const ValueTree& s) : project (p), state (s) { } ModuleDescription EnabledModuleList::getModuleInfo (const String& moduleID) { return ModuleDescription (project.getModuleWithID (moduleID).second); } bool EnabledModuleList::isModuleEnabled (const String& moduleID) const { return state.getChildWithProperty (Ids::ID, moduleID).isValid(); } bool EnabledModuleList::isAudioPluginModuleMissing() const { return project.getProjectType().isAudioPlugin() && ! isModuleEnabled ("juce_audio_plugin_client"); } bool EnabledModuleList::shouldUseGlobalPath (const String& moduleID) const { return static_cast<bool> (state.getChildWithProperty (Ids::ID, moduleID) .getProperty (Ids::useGlobalPath)); } Value EnabledModuleList::getShouldUseGlobalPathValue (const String& moduleID) const { return state.getChildWithProperty (Ids::ID, moduleID) .getPropertyAsValue (Ids::useGlobalPath, getUndoManager()); } Value EnabledModuleList::shouldShowAllModuleFilesInProject (const String& moduleID) { return state.getChildWithProperty (Ids::ID, moduleID) .getPropertyAsValue (Ids::showAllCode, getUndoManager()); } struct ModuleTreeSorter { static int compareElements (const ValueTree& m1, const ValueTree& m2) { return m1[Ids::ID].toString().compareIgnoreCase (m2[Ids::ID]); } }; void EnabledModuleList::sortAlphabetically() { ModuleTreeSorter sorter; state.sort (sorter, getUndoManager(), false); } Value EnabledModuleList::shouldCopyModuleFilesLocally (const String& moduleID) const { return state.getChildWithProperty (Ids::ID, moduleID) .getPropertyAsValue (Ids::useLocalCopy, getUndoManager()); } void EnabledModuleList::addModule (const File& moduleFolder, bool copyLocally, bool useGlobalPath, bool sendAnalyticsEvent) { ModuleDescription info (moduleFolder); if (info.isValid()) { auto moduleID = info.getID(); if (! isModuleEnabled (moduleID)) { ValueTree module (Ids::MODULE); module.setProperty (Ids::ID, moduleID, getUndoManager()); state.appendChild (module, getUndoManager()); sortAlphabetically(); shouldShowAllModuleFilesInProject (moduleID) = true; shouldCopyModuleFilesLocally (moduleID) = copyLocally; getShouldUseGlobalPathValue (moduleID) = useGlobalPath; RelativePath path (moduleFolder.getParentDirectory(), project.getProjectFolder(), RelativePath::projectFolder); for (Project::ExporterIterator exporter (project); exporter.next();) exporter->getPathForModuleValue (moduleID) = path.toUnixStyle(); if (! useGlobalPath) project.rescanExporterPathModules (false); if (sendAnalyticsEvent) { StringPairArray data; data.set ("label", moduleID); Analytics::getInstance()->logEvent ("Module Added", data, ProjucerAnalyticsEvent::projectEvent); } } } } void EnabledModuleList::removeModule (String moduleID) // must be pass-by-value, and not a const ref! { for (auto i = state.getNumChildren(); --i >= 0;) if (state.getChild(i) [Ids::ID] == moduleID) state.removeChild (i, getUndoManager()); for (Project::ExporterIterator exporter (project); exporter.next();) exporter->removePathForModule (moduleID); } void EnabledModuleList::createRequiredModules (OwnedArray<LibraryModule>& modules) { for (int i = 0; i < getNumModules(); ++i) modules.add (new LibraryModule (getModuleInfo (getModuleID (i)))); } StringArray EnabledModuleList::getAllModules() const { StringArray moduleIDs; for (int i = 0; i < getNumModules(); ++i) moduleIDs.add (getModuleID (i)); return moduleIDs; } static void getDependencies (Project& project, const String& moduleID, StringArray& dependencies) { auto info = project.getEnabledModules().getModuleInfo (moduleID); for (auto uid : info.getDependencies()) { if (! dependencies.contains (uid, true)) { dependencies.add (uid); getDependencies (project, uid, dependencies); } } } StringArray EnabledModuleList::getExtraDependenciesNeeded (const String& moduleID) const { StringArray dependencies, extraDepsNeeded; getDependencies (project, moduleID, dependencies); for (auto dep : dependencies) if (dep != moduleID && ! isModuleEnabled (dep)) extraDepsNeeded.add (dep); return extraDepsNeeded; } bool EnabledModuleList::doesModuleHaveHigherCppStandardThanProject (const String& moduleID) { auto projectCppStandard = project.getCppStandardString(); if (projectCppStandard == "latest") return false; auto moduleCppStandard = getModuleInfo (moduleID).getMinimumCppStandard(); return (moduleCppStandard.getIntValue() > projectCppStandard.getIntValue()); } bool EnabledModuleList::areMostModulesUsingGlobalPath() const { int numYes = 0, numNo = 0; for (auto i = getNumModules(); --i >= 0;) { if (shouldUseGlobalPath (getModuleID (i))) ++numYes; else ++numNo; } return numYes > numNo; } bool EnabledModuleList::areMostModulesCopiedLocally() const { int numYes = 0, numNo = 0; for (auto i = getNumModules(); --i >= 0;) { if (shouldCopyModuleFilesLocally (getModuleID (i)).getValue()) ++numYes; else ++numNo; } return numYes > numNo; } void EnabledModuleList::setLocalCopyModeForAllModules (bool copyLocally) { for (auto i = getNumModules(); --i >= 0;) shouldCopyModuleFilesLocally (project.getEnabledModules().getModuleID (i)) = copyLocally; } File EnabledModuleList::findDefaultModulesFolder (Project& project) { File globalPath (getAppSettings().getStoredPath (Ids::defaultJuceModulePath, TargetOS::getThisOS()).get().toString()); if (globalPath.exists()) return globalPath; for (auto& exporterPathModule : project.getExporterPathsModuleList().getAllModules()) { auto f = exporterPathModule.second; if (f.isDirectory()) return f.getParentDirectory(); } return File::getCurrentWorkingDirectory(); } void EnabledModuleList::addModuleFromUserSelectedFile() { static auto lastLocation = findDefaultModulesFolder (project); FileChooser fc ("Select a module to add...", lastLocation, {}); if (fc.browseForDirectory()) { lastLocation = fc.getResult(); addModuleOfferingToCopy (lastLocation, true); } } void EnabledModuleList::addModuleInteractive (const String& moduleID) { auto f = project.getModuleWithID (moduleID).second; if (f != File()) { addModule (f, areMostModulesCopiedLocally(), areMostModulesUsingGlobalPath(), true); return; } addModuleFromUserSelectedFile(); } void EnabledModuleList::addModuleOfferingToCopy (const File& f, bool isFromUserSpecifiedFolder) { ModuleDescription m (f); if (! m.isValid()) { AlertWindow::showMessageBoxAsync (AlertWindow::InfoIcon, "Add Module", "This wasn't a valid module folder!"); return; } if (isModuleEnabled (m.getID())) { AlertWindow::showMessageBoxAsync (AlertWindow::InfoIcon, "Add Module", "The project already contains this module!"); return; } addModule (m.moduleFolder, areMostModulesCopiedLocally(), isFromUserSpecifiedFolder ? false : areMostModulesUsingGlobalPath(), true); } bool isJUCEFolder (const File& f) { return isJUCEModulesFolder (f.getChildFile ("modules")); } bool isJUCEModulesFolder (const File& f) { return f.isDirectory() && f.getChildFile ("juce_core").isDirectory(); }
33.065614
149
0.597656
Hanley1
370527f4c4f225ea2964f50f2366c75eb69827f9
5,592
cxx
C++
Qt/Testing/pqTestUtility.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
1
2016-05-09T00:36:44.000Z
2016-05-09T00:36:44.000Z
Qt/Testing/pqTestUtility.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
null
null
null
Qt/Testing/pqTestUtility.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
3
2015-05-14T21:18:53.000Z
2022-03-07T02:53:45.000Z
/*========================================================================= Program: ParaView Module: $RCSfile: pqTestUtility.cxx,v $ Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc. All rights reserved. ParaView is a free software; you can redistribute it and/or modify it under the terms of the ParaView license version 1.1. See License_v1.1.txt for the full ParaView license. A copy of this license can be obtained by contacting Kitware Inc. 28 Corporate Drive Clifton Park, NY 12065 USA 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include "pqTestUtility.h" #include <QFileInfo> #include <QApplication> #include "pqEventSource.h" #include "pqEventObserver.h" #include "pqRecordEventsDialog.h" #include "QtTestingConfigure.h" #ifdef QT_TESTING_WITH_XML #include "pqXMLEventSource.h" #include "pqXMLEventObserver.h" #endif #ifdef QT_TESTING_WITH_PYTHON #include "pqPythonEventSource.h" #include "pqPythonEventObserver.h" #endif pqTestUtility::pqTestUtility(QObject* p) : QObject(p) { QObject::connect( &this->Dispatcher, SIGNAL(succeeded()), this, SLOT(testSucceeded())); QObject::connect( &this->Dispatcher, SIGNAL(failed()), this, SLOT(testFailed())); this->Translator.addDefaultWidgetEventTranslators(); this->Player.addDefaultWidgetEventPlayers(); #ifdef QT_TESTING_WITH_XML // add an XML source this->addEventSource("xml", new pqXMLEventSource(this)); this->addEventObserver("xml", new pqXMLEventObserver(this)); #endif #ifdef QT_TESTING_WITH_PYTHON // add a python event source this->addEventSource("py", new pqPythonEventSource(this)); this->addEventObserver("py", new pqPythonEventObserver(this)); #endif } pqTestUtility::~pqTestUtility() { } pqEventDispatcher* pqTestUtility::dispatcher() { return &this->Dispatcher; } pqEventPlayer* pqTestUtility::eventPlayer() { return &this->Player; } pqEventTranslator* pqTestUtility::eventTranslator() { return &this->Translator; } void pqTestUtility::addEventSource(const QString& fileExtension, pqEventSource* source) { QMap<QString, pqEventSource*>::iterator iter; iter = this->EventSources.find(fileExtension); if(iter != this->EventSources.end()) { pqEventSource* src = iter.value(); this->EventSources.erase(iter); delete src; } this->EventSources.insert(fileExtension, source); source->setParent(this); } void pqTestUtility::addEventObserver(const QString& fileExtension, pqEventObserver* observer) { QMap<QString, pqEventObserver*>::iterator iter; iter = this->EventObservers.find(fileExtension); if(iter != this->EventObservers.end() && iter.value() != observer) { pqEventObserver* src = iter.value(); this->EventObservers.erase(iter); delete src; } if(iter != this->EventObservers.end() && iter.value() == observer) { return; } this->EventObservers.insert(fileExtension, observer); observer->setParent(this); } void pqTestUtility::playTests(const QString& filename) { QFileInfo info(filename); QString suffix = info.completeSuffix(); QMap<QString, pqEventSource*>::iterator iter; iter = this->EventSources.find(suffix); if(info.isReadable() && iter != this->EventSources.end()) { iter.value()->setContent(filename); this->Dispatcher.playEvents(*iter.value(), this->Player); } } void pqTestUtility::playTests(const QStringList& filenames) { foreach(QString filename, filenames) { this->playTests(filename); } } void pqTestUtility::recordTests(const QString& filename) { #if defined(Q_WS_MAC) // check for native or non-native menu bar. // testing framework doesn't work with native menu bar, so let's warn if we // get that. if(!getenv("QT_MAC_NO_NATIVE_MENUBAR")) { qWarning("Recording menu events for native Mac menus doesn't work.\n" "Set the QT_MAC_NO_NATIVE_MENUBAR environment variable to" " correctly record menus"); } #endif QMap<QString, pqEventObserver*>::iterator iter; QFileInfo info(filename); QString suffix = info.completeSuffix(); pqEventObserver* observer = NULL; iter = this->EventObservers.find(suffix); if(iter != this->EventObservers.end()) { observer = iter.value(); } if(!observer) { // cannot find observer for type of file return; } pqRecordEventsDialog* dialog = new pqRecordEventsDialog(this->Translator, *observer, filename, QApplication::activeWindow()); dialog->setAttribute(Qt::WA_QuitOnClose, false); dialog->show(); } void pqTestUtility::testSucceeded() { } void pqTestUtility::testFailed() { }
27.014493
87
0.683476
certik
3705f4b9f010683aaf4e480e36899e6f259b758f
487
hpp
C++
lib/ldcp_sdk/third_party/Asio/asio-1.12.1/include/asio/yield.hpp
MoveXBot/ltme_node
988f5c8a7ccc3f962e1c46ea61d7805f7d30bfe5
[ "Apache-2.0" ]
27
2019-10-24T11:09:06.000Z
2022-03-22T10:00:51.000Z
lib/ldcp_sdk/third_party/Asio/asio-1.12.1/include/asio/yield.hpp
MoveXBot/ltme_node
988f5c8a7ccc3f962e1c46ea61d7805f7d30bfe5
[ "Apache-2.0" ]
1
2019-12-09T06:15:01.000Z
2019-12-09T06:15:01.000Z
lib/ldcp_sdk/third_party/Asio/asio-1.12.1/include/asio/yield.hpp
MoveXBot/ltme_node
988f5c8a7ccc3f962e1c46ea61d7805f7d30bfe5
[ "Apache-2.0" ]
10
2020-01-10T09:10:57.000Z
2020-06-26T11:03:11.000Z
// // yield.hpp // ~~~~~~~~~ // // Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "coroutine.hpp" #ifndef reenter # define reenter(c) ASIO_CORO_REENTER(c) #endif #ifndef yield # define yield ASIO_CORO_YIELD #endif #ifndef fork # define fork ASIO_CORO_FORK #endif
20.291667
80
0.687885
MoveXBot
370845949294c2a5a41ce9bdf6dc86ad624575f2
24,507
cpp
C++
modules/videostab/samples/videostab.cpp
Kriston-SCT/opencv_contrib
65abc7090dedc84bbedec4dfd143f0340e52114f
[ "BSD-3-Clause" ]
3
2020-01-02T11:53:17.000Z
2021-04-10T14:02:20.000Z
modules/videostab/samples/videostab.cpp
Kriston-SCT/opencv_contrib
65abc7090dedc84bbedec4dfd143f0340e52114f
[ "BSD-3-Clause" ]
1
2020-12-08T15:15:26.000Z
2020-12-08T15:15:26.000Z
modules/videostab/samples/videostab.cpp
Kriston-SCT/opencv_contrib
65abc7090dedc84bbedec4dfd143f0340e52114f
[ "BSD-3-Clause" ]
3
2019-09-04T02:01:31.000Z
2020-01-02T11:53:23.000Z
#include <string> #include <iostream> #include <fstream> #include <sstream> #include <stdexcept> #include "opencv2/core.hpp" #include <opencv2/core/utility.hpp> #include "opencv2/video.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/videoio.hpp" #include "opencv2/highgui.hpp" #include "opencv2/videostab.hpp" #include "opencv2/opencv_modules.hpp" #define arg(name) cmd.get<string>(name) #define argb(name) cmd.get<bool>(name) #define argi(name) cmd.get<int>(name) #define argf(name) cmd.get<float>(name) #define argd(name) cmd.get<double>(name) using namespace std; using namespace cv; using namespace cv::videostab; Ptr<IFrameSource> stabilizedFrames; string saveMotionsPath; double outputFps; string outputPath; bool quietMode; void run(); void saveMotionsIfNecessary(); void printHelp(); MotionModel motionModel(const string &str); void run() { VideoWriter writer; Mat stabilizedFrame; int nframes = 0; // for each stabilized frame while (!(stabilizedFrame = stabilizedFrames->nextFrame()).empty()) { nframes++; // init writer (once) and save stabilized frame if (!outputPath.empty()) { if (!writer.isOpened()) writer.open(outputPath, VideoWriter::fourcc('X','V','I','D'), outputFps, stabilizedFrame.size()); writer << stabilizedFrame; } // show stabilized frame if (!quietMode) { imshow("stabilizedFrame", stabilizedFrame); char key = static_cast<char>(waitKey(3)); if (key == 27) { cout << endl; break; } } } cout << "processed frames: " << nframes << endl << "finished\n"; } void printHelp() { cout << "OpenCV video stabilizer.\n" "Usage: videostab <file_path> [arguments]\n\n" "Arguments:\n" " -m=, --model=(transl|transl_and_scale|rigid|similarity|affine|homography)\n" " Set motion model. The default is affine.\n" " -lp=, --lin-prog-motion-est=(yes|no)\n" " Turn on/off LP based motion estimation. The default is no.\n" " --subset=(<int_number>|auto)\n" " Number of random samples per one motion hypothesis. The default is auto.\n" " --thresh=(<float_number>|auto)\n" " Maximum error to classify match as inlier. The default is auto.\n" " --outlier-ratio=<float_number>\n" " Motion estimation outlier ratio hypothesis. The default is 0.5.\n" " --min-inlier-ratio=<float_number>\n" " Minimum inlier ratio to decide if estimated motion is OK. The default is 0.1.\n" " --nkps=<int_number>\n" " Number of keypoints to find in each frame. The default is 1000.\n" " --local-outlier-rejection=(yes|no)\n" " Perform local outlier rejection. The default is no.\n\n" " --feature-masks=(file_path|no)\n" " Load masks from file. The default is no.\n\n" " -sm=, --save-motions=(<file_path>|no)\n" " Save estimated motions into file. The default is no.\n" " -lm=, --load-motions=(<file_path>|no)\n" " Load motions from file. The default is no.\n\n" " -r=, --radius=<int_number>\n" " Set sliding window radius. The default is 15.\n" " --stdev=(<float_number>|auto)\n" " Set smoothing weights standard deviation. The default is auto\n" " (i.e. sqrt(radius)).\n" " -lps=, --lin-prog-stab=(yes|no)\n" " Turn on/off linear programming based stabilization method.\n" " --lps-trim-ratio=(<float_number>|auto)\n" " Trimming ratio used in linear programming based method.\n" " --lps-w1=(<float_number>|1)\n" " 1st derivative weight. The default is 1.\n" " --lps-w2=(<float_number>|10)\n" " 2nd derivative weight. The default is 10.\n" " --lps-w3=(<float_number>|100)\n" " 3rd derivative weight. The default is 100.\n" " --lps-w4=(<float_number>|100)\n" " Non-translation motion components weight. The default is 100.\n\n" " --deblur=(yes|no)\n" " Do deblurring.\n" " --deblur-sens=<float_number>\n" " Set deblurring sensitivity (from 0 to +inf). The default is 0.1.\n\n" " -t=, --trim-ratio=<float_number>\n" " Set trimming ratio (from 0 to 0.5). The default is 0.1.\n" " -et=, --est-trim=(yes|no)\n" " Estimate trim ratio automatically. The default is yes.\n" " -ic=, --incl-constr=(yes|no)\n" " Ensure the inclusion constraint is always satisfied. The default is no.\n\n" " -bm=, --border-mode=(replicate|reflect|const)\n" " Set border extrapolation mode. The default is replicate.\n\n" " --mosaic=(yes|no)\n" " Do consistent mosaicing. The default is no.\n" " --mosaic-stdev=<float_number>\n" " Consistent mosaicing stdev threshold. The default is 10.0.\n\n" " -mi=, --motion-inpaint=(yes|no)\n" " Do motion inpainting (requires CUDA support). The default is no.\n" " --mi-dist-thresh=<float_number>\n" " Estimated flow distance threshold for motion inpainting. The default is 5.0.\n\n" " -ci=, --color-inpaint=(no|average|ns|telea)\n" " Do color inpainting. The default is no.\n" " --ci-radius=<float_number>\n" " Set color inpainting radius (for ns and telea options only).\n" " The default is 2.0\n\n" " -ws=, --wobble-suppress=(yes|no)\n" " Perform wobble suppression. The default is no.\n" " --ws-lp=(yes|no)\n" " Turn on/off LP based motion estimation. The default is no.\n" " --ws-period=<int_number>\n" " Set wobble suppression period. The default is 30.\n" " --ws-model=(transl|transl_and_scale|rigid|similarity|affine|homography)\n" " Set wobble suppression motion model (must have more DOF than motion \n" " estimation model). The default is homography.\n" " --ws-subset=(<int_number>|auto)\n" " Number of random samples per one motion hypothesis. The default is auto.\n" " --ws-thresh=(<float_number>|auto)\n" " Maximum error to classify match as inlier. The default is auto.\n" " --ws-outlier-ratio=<float_number>\n" " Motion estimation outlier ratio hypothesis. The default is 0.5.\n" " --ws-min-inlier-ratio=<float_number>\n" " Minimum inlier ratio to decide if estimated motion is OK. The default is 0.1.\n" " --ws-nkps=<int_number>\n" " Number of keypoints to find in each frame. The default is 1000.\n" " --ws-local-outlier-rejection=(yes|no)\n" " Perform local outlier rejection. The default is no.\n\n" " -sm2=, --save-motions2=(<file_path>|no)\n" " Save motions estimated for wobble suppression. The default is no.\n" " -lm2=, --load-motions2=(<file_path>|no)\n" " Load motions for wobble suppression from file. The default is no.\n\n" " -gpu=(yes|no)\n" " Use CUDA optimization whenever possible. The default is no.\n\n" " -o=, --output=(no|<file_path>)\n" " Set output file path explicitly. The default is stabilized.avi.\n" " --fps=(<float_number>|auto)\n" " Set output video FPS explicitly. By default the source FPS is used (auto).\n" " -q, --quiet\n" " Don't show output video frames.\n\n" " -h, --help\n" " Print help.\n\n" "Note: some argument configurations lead to two passes, some to single pass.\n\n"; } // motion estimator builders are for concise creation of motion estimators class IMotionEstimatorBuilder { public: virtual ~IMotionEstimatorBuilder() {} virtual Ptr<ImageMotionEstimatorBase> build() = 0; protected: IMotionEstimatorBuilder(CommandLineParser &command) : cmd(command) {} CommandLineParser cmd; }; class MotionEstimatorRansacL2Builder : public IMotionEstimatorBuilder { public: MotionEstimatorRansacL2Builder(CommandLineParser &command, bool use_gpu, const string &_prefix = "") : IMotionEstimatorBuilder(command), gpu(use_gpu), prefix(_prefix) {} virtual Ptr<ImageMotionEstimatorBase> build() CV_OVERRIDE { Ptr<MotionEstimatorRansacL2> est = makePtr<MotionEstimatorRansacL2>(motionModel(arg(prefix + "model"))); RansacParams ransac = est->ransacParams(); if (arg(prefix + "subset") != "auto") ransac.size = argi(prefix + "subset"); if (arg(prefix + "thresh") != "auto") ransac.thresh = argf(prefix + "thresh"); ransac.eps = argf(prefix + "outlier-ratio"); est->setRansacParams(ransac); est->setMinInlierRatio(argf(prefix + "min-inlier-ratio")); Ptr<IOutlierRejector> outlierRejector = makePtr<NullOutlierRejector>(); if (arg(prefix + "local-outlier-rejection") == "yes") { Ptr<TranslationBasedLocalOutlierRejector> tblor = makePtr<TranslationBasedLocalOutlierRejector>(); RansacParams ransacParams = tblor->ransacParams(); if (arg(prefix + "thresh") != "auto") ransacParams.thresh = argf(prefix + "thresh"); tblor->setRansacParams(ransacParams); outlierRejector = tblor; } #if defined(HAVE_OPENCV_CUDAIMGPROC) && defined(HAVE_OPENCV_CUDAOPTFLOW) if (gpu) { Ptr<KeypointBasedMotionEstimatorGpu> kbest = makePtr<KeypointBasedMotionEstimatorGpu>(est); kbest->setOutlierRejector(outlierRejector); return kbest; } #else CV_Assert(gpu == false && "CUDA modules are not available"); #endif Ptr<KeypointBasedMotionEstimator> kbest = makePtr<KeypointBasedMotionEstimator>(est); kbest->setDetector(GFTTDetector::create(argi(prefix + "nkps"))); kbest->setOutlierRejector(outlierRejector); return kbest; } private: bool gpu; string prefix; }; class MotionEstimatorL1Builder : public IMotionEstimatorBuilder { public: MotionEstimatorL1Builder(CommandLineParser &command, bool use_gpu, const string &_prefix = "") : IMotionEstimatorBuilder(command), gpu(use_gpu), prefix(_prefix) {} virtual Ptr<ImageMotionEstimatorBase> build() CV_OVERRIDE { Ptr<MotionEstimatorL1> est = makePtr<MotionEstimatorL1>(motionModel(arg(prefix + "model"))); Ptr<IOutlierRejector> outlierRejector = makePtr<NullOutlierRejector>(); if (arg(prefix + "local-outlier-rejection") == "yes") { Ptr<TranslationBasedLocalOutlierRejector> tblor = makePtr<TranslationBasedLocalOutlierRejector>(); RansacParams ransacParams = tblor->ransacParams(); if (arg(prefix + "thresh") != "auto") ransacParams.thresh = argf(prefix + "thresh"); tblor->setRansacParams(ransacParams); outlierRejector = tblor; } #if defined(HAVE_OPENCV_CUDAIMGPROC) && defined(HAVE_OPENCV_CUDAOPTFLOW) if (gpu) { Ptr<KeypointBasedMotionEstimatorGpu> kbest = makePtr<KeypointBasedMotionEstimatorGpu>(est); kbest->setOutlierRejector(outlierRejector); return kbest; } #else CV_Assert(gpu == false && "CUDA modules are not available"); #endif Ptr<KeypointBasedMotionEstimator> kbest = makePtr<KeypointBasedMotionEstimator>(est); kbest->setDetector(GFTTDetector::create(argi(prefix + "nkps"))); kbest->setOutlierRejector(outlierRejector); return kbest; } private: bool gpu; string prefix; }; int main(int argc, const char **argv) { try { const char *keys = "{ @1 | | }" "{ m model | affine | }" "{ lp lin-prog-motion-est | no | }" "{ subset | auto | }" "{ thresh | auto | }" "{ outlier-ratio | 0.5 | }" "{ min-inlier-ratio | 0.1 | }" "{ nkps | 1000 | }" "{ extra-kps | 0 | }" "{ local-outlier-rejection | no | }" "{ feature-masks | no | }" "{ sm save-motions | no | }" "{ lm load-motions | no | }" "{ r radius | 15 | }" "{ stdev | auto | }" "{ lps lin-prog-stab | no | }" "{ lps-trim-ratio | auto | }" "{ lps-w1 | 1 | }" "{ lps-w2 | 10 | }" "{ lps-w3 | 100 | }" "{ lps-w4 | 100 | }" "{ deblur | no | }" "{ deblur-sens | 0.1 | }" "{ et est-trim | yes | }" "{ t trim-ratio | 0.1 | }" "{ ic incl-constr | no | }" "{ bm border-mode | replicate | }" "{ mosaic | no | }" "{ ms mosaic-stdev | 10.0 | }" "{ mi motion-inpaint | no | }" "{ mi-dist-thresh | 5.0 | }" "{ ci color-inpaint | no | }" "{ ci-radius | 2 | }" "{ ws wobble-suppress | no | }" "{ ws-period | 30 | }" "{ ws-model | homography | }" "{ ws-subset | auto | }" "{ ws-thresh | auto | }" "{ ws-outlier-ratio | 0.5 | }" "{ ws-min-inlier-ratio | 0.1 | }" "{ ws-nkps | 1000 | }" "{ ws-extra-kps | 0 | }" "{ ws-local-outlier-rejection | no | }" "{ ws-lp | no | }" "{ sm2 save-motions2 | no | }" "{ lm2 load-motions2 | no | }" "{ gpu | no | }" "{ o output | stabilized.avi | }" "{ fps | auto | }" "{ q quiet | | }" "{ h help | | }"; CommandLineParser cmd(argc, argv, keys); // parse command arguments if (argb("help")) { printHelp(); return 0; } if (arg("gpu") == "yes") { cout << "initializing GPU..."; cout.flush(); Mat hostTmp = Mat::zeros(1, 1, CV_32F); cuda::GpuMat deviceTmp; deviceTmp.upload(hostTmp); cout << endl; } StabilizerBase *stabilizer = 0; // check if source video is specified string inputPath = arg(0); if (inputPath.empty()) throw runtime_error("specify video file path"); // get source video parameters Ptr<VideoFileSource> source = makePtr<VideoFileSource>(inputPath); cout << "frame count (rough): " << source->count() << endl; if (arg("fps") == "auto") outputFps = source->fps(); else outputFps = argd("fps"); // prepare motion estimation builders Ptr<IMotionEstimatorBuilder> motionEstBuilder; if (arg("lin-prog-motion-est") == "yes") motionEstBuilder.reset(new MotionEstimatorL1Builder(cmd, arg("gpu") == "yes")); else motionEstBuilder.reset(new MotionEstimatorRansacL2Builder(cmd, arg("gpu") == "yes")); Ptr<IMotionEstimatorBuilder> wsMotionEstBuilder; if (arg("ws-lp") == "yes") wsMotionEstBuilder.reset(new MotionEstimatorL1Builder(cmd, arg("gpu") == "yes", "ws-")); else wsMotionEstBuilder.reset(new MotionEstimatorRansacL2Builder(cmd, arg("gpu") == "yes", "ws-")); // determine whether we must use one pass or two pass stabilizer bool isTwoPass = arg("est-trim") == "yes" || arg("wobble-suppress") == "yes" || arg("lin-prog-stab") == "yes"; if (isTwoPass) { // we must use two pass stabilizer TwoPassStabilizer *twoPassStabilizer = new TwoPassStabilizer(); stabilizer = twoPassStabilizer; twoPassStabilizer->setEstimateTrimRatio(arg("est-trim") == "yes"); // determine stabilization technique if (arg("lin-prog-stab") == "yes") { Ptr<LpMotionStabilizer> stab = makePtr<LpMotionStabilizer>(); stab->setFrameSize(Size(source->width(), source->height())); stab->setTrimRatio(arg("lps-trim-ratio") == "auto" ? argf("trim-ratio") : argf("lps-trim-ratio")); stab->setWeight1(argf("lps-w1")); stab->setWeight2(argf("lps-w2")); stab->setWeight3(argf("lps-w3")); stab->setWeight4(argf("lps-w4")); twoPassStabilizer->setMotionStabilizer(stab); } else if (arg("stdev") == "auto") twoPassStabilizer->setMotionStabilizer(makePtr<GaussianMotionFilter>(argi("radius"))); else twoPassStabilizer->setMotionStabilizer(makePtr<GaussianMotionFilter>(argi("radius"), argf("stdev"))); // init wobble suppressor if necessary if (arg("wobble-suppress") == "yes") { Ptr<MoreAccurateMotionWobbleSuppressorBase> ws = makePtr<MoreAccurateMotionWobbleSuppressor>(); if (arg("gpu") == "yes") #ifdef HAVE_OPENCV_CUDAWARPING ws = makePtr<MoreAccurateMotionWobbleSuppressorGpu>(); #else throw runtime_error("OpenCV is built without CUDA support"); #endif ws->setMotionEstimator(wsMotionEstBuilder->build()); ws->setPeriod(argi("ws-period")); twoPassStabilizer->setWobbleSuppressor(ws); MotionModel model = ws->motionEstimator()->motionModel(); if (arg("load-motions2") != "no") { ws->setMotionEstimator(makePtr<FromFileMotionReader>(arg("load-motions2"))); ws->motionEstimator()->setMotionModel(model); } if (arg("save-motions2") != "no") { ws->setMotionEstimator(makePtr<ToFileMotionWriter>(arg("save-motions2"), ws->motionEstimator())); ws->motionEstimator()->setMotionModel(model); } } } else { // we must use one pass stabilizer OnePassStabilizer *onePassStabilizer = new OnePassStabilizer(); stabilizer = onePassStabilizer; if (arg("stdev") == "auto") onePassStabilizer->setMotionFilter(makePtr<GaussianMotionFilter>(argi("radius"))); else onePassStabilizer->setMotionFilter(makePtr<GaussianMotionFilter>(argi("radius"), argf("stdev"))); } stabilizer->setFrameSource(source); stabilizer->setMotionEstimator(motionEstBuilder->build()); if (arg("feature-masks") != "no") { Ptr<MaskFrameSource> maskSource = makePtr<MaskFrameSource>( makePtr<VideoFileSource>(arg("feature-masks"))); std::function<void(Mat&)> maskCallback = [](Mat & inputFrame) { cv::cvtColor(inputFrame, inputFrame, cv::COLOR_BGR2GRAY); threshold(inputFrame, inputFrame, 127, 255, THRESH_BINARY); }; maskSource->setMaskCallback(maskCallback); stabilizer->setMaskSource(maskSource); } // cast stabilizer to simple frame source interface to read stabilized frames stabilizedFrames.reset(dynamic_cast<IFrameSource*>(stabilizer)); MotionModel model = stabilizer->motionEstimator()->motionModel(); if (arg("load-motions") != "no") { stabilizer->setMotionEstimator(makePtr<FromFileMotionReader>(arg("load-motions"))); stabilizer->motionEstimator()->setMotionModel(model); } if (arg("save-motions") != "no") { stabilizer->setMotionEstimator(makePtr<ToFileMotionWriter>(arg("save-motions"), stabilizer->motionEstimator())); stabilizer->motionEstimator()->setMotionModel(model); } stabilizer->setRadius(argi("radius")); // init deblurer if (arg("deblur") == "yes") { Ptr<WeightingDeblurer> deblurer = makePtr<WeightingDeblurer>(); deblurer->setRadius(argi("radius")); deblurer->setSensitivity(argf("deblur-sens")); stabilizer->setDeblurer(deblurer); } // set up trimming parameters stabilizer->setTrimRatio(argf("trim-ratio")); stabilizer->setCorrectionForInclusion(arg("incl-constr") == "yes"); if (arg("border-mode") == "reflect") stabilizer->setBorderMode(BORDER_REFLECT); else if (arg("border-mode") == "replicate") stabilizer->setBorderMode(BORDER_REPLICATE); else if (arg("border-mode") == "const") stabilizer->setBorderMode(BORDER_CONSTANT); else throw runtime_error("unknown border extrapolation mode: " + cmd.get<string>("border-mode")); // init inpainter InpaintingPipeline *inpainters = new InpaintingPipeline(); Ptr<InpainterBase> inpainters_(inpainters); if (arg("mosaic") == "yes") { Ptr<ConsistentMosaicInpainter> inp = makePtr<ConsistentMosaicInpainter>(); inp->setStdevThresh(argf("mosaic-stdev")); inpainters->pushBack(inp); } if (arg("motion-inpaint") == "yes") { Ptr<MotionInpainter> inp = makePtr<MotionInpainter>(); inp->setDistThreshold(argf("mi-dist-thresh")); inpainters->pushBack(inp); } if (arg("color-inpaint") == "average") inpainters->pushBack(makePtr<ColorAverageInpainter>()); else if (arg("color-inpaint") == "ns") inpainters->pushBack(makePtr<ColorInpainter>(int(INPAINT_NS), argd("ci-radius"))); else if (arg("color-inpaint") == "telea") inpainters->pushBack(makePtr<ColorInpainter>(int(INPAINT_TELEA), argd("ci-radius"))); else if (arg("color-inpaint") != "no") throw runtime_error("unknown color inpainting method: " + arg("color-inpaint")); if (!inpainters->empty()) { inpainters->setRadius(argi("radius")); stabilizer->setInpainter(inpainters_); } if (arg("output") != "no") outputPath = arg("output"); quietMode = argb("quiet"); run(); } catch (const exception &e) { cout << "error: " << e.what() << endl; stabilizedFrames.release(); return -1; } stabilizedFrames.release(); return 0; } MotionModel motionModel(const string &str) { if (str == "transl") return MM_TRANSLATION; if (str == "transl_and_scale") return MM_TRANSLATION_AND_SCALE; if (str == "rigid") return MM_RIGID; if (str == "similarity") return MM_SIMILARITY; if (str == "affine") return MM_AFFINE; if (str == "homography") return MM_HOMOGRAPHY; throw runtime_error("unknown motion model: " + str); }
42.036021
124
0.540907
Kriston-SCT
3708613729c793f8c46cbf6bf09d74e2cc8949b1
2,622
cpp
C++
src/Conversion/SeqToMemref/KrnlSeqStore.cpp
philass/onnx-mlir
09965003137f82d8891676c986ec6403faa9c3cb
[ "Apache-2.0" ]
1
2022-03-23T06:41:14.000Z
2022-03-23T06:41:14.000Z
src/Conversion/SeqToMemref/KrnlSeqStore.cpp
philass/onnx-mlir
09965003137f82d8891676c986ec6403faa9c3cb
[ "Apache-2.0" ]
1
2022-03-31T23:58:31.000Z
2022-03-31T23:58:31.000Z
src/Conversion/SeqToMemref/KrnlSeqStore.cpp
philass/onnx-mlir
09965003137f82d8891676c986ec6403faa9c3cb
[ "Apache-2.0" ]
null
null
null
/* * SPDX-License-Identifier: Apache-2.0 */ //===------ KrnlSeqStore.cpp - Lower KrnlSeqStoreOp ----------------------===// // // Copyright 2019-2022 The IBM Research Authors. // // ============================================================================= // // This file lowers the KrnlSeqStoreOp operator. // //===----------------------------------------------------------------------===// #include "mlir/Conversion/LLVMCommon/Pattern.h" #include "mlir/Conversion/LLVMCommon/TypeConverter.h" #include "mlir/Dialect/Func/IR/FuncOps.h" #include "mlir/Dialect/LLVMIR/LLVMDialect.h" #include "src/Conversion/KrnlToLLVM/KrnlToLLVMHelper.hpp" #include "src/Dialect/Krnl/KrnlHelper.hpp" #include "src/Dialect/Krnl/KrnlOps.hpp" #include "llvm/Support/Debug.h" #define DEBUG_TYPE "krnl_to_llvm" using namespace mlir; using namespace onnx_mlir; namespace onnx_mlir { namespace krnl { class KrnlSeqStoreOpLowering : public ConversionPattern { public: explicit KrnlSeqStoreOpLowering( TypeConverter &typeConverter, MLIRContext *context) : ConversionPattern( typeConverter, KrnlSeqStoreOp::getOperationName(), 1, context) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { KrnlSeqStoreOpAdaptor operandAdaptor(operands); auto loc = op->getLoc(); MultiDialectBuilder<MathBuilder, MemRefBuilder> create(rewriter, loc); // Allocate a new tensor and copy input tensor into it auto inputType = operandAdaptor.input().getType().cast<MemRefType>(); SmallVector<mlir::Value, 4> allocParams; for (size_t i = 0; i < inputType.getShape().size(); i++) { if (inputType.getShape()[i] == -1) { allocParams.emplace_back(create.mem.dim(operandAdaptor.input(), i)); } } Value alloc = create.mem.alignedAlloc(inputType, allocParams); rewriter.create<memref::CopyOp>(loc, operandAdaptor.input(), alloc); // Cast the input tensor to the element type of the sequence auto seq = operandAdaptor.seq(); auto seqElementType = seq.getType().cast<MemRefType>().getElementType().cast<MemRefType>(); auto casted = create.mem.cast(alloc, seqElementType); // Store the tensor rewriter.create<memref::StoreOp>(loc, casted, seq, operandAdaptor.index()); rewriter.eraseOp(op); return success(); } }; void populateLoweringKrnlSeqStoreOpPattern(TypeConverter &typeConverter, RewritePatternSet &patterns, MLIRContext *ctx) { patterns.insert<KrnlSeqStoreOpLowering>(typeConverter, ctx); } } // namespace krnl } // namespace onnx_mlir
34.051948
80
0.673913
philass
37091c43e13e4fb56373d968db8f11a0fc473f62
9,754
cpp
C++
cmds/stagefright/record.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
null
null
null
cmds/stagefright/record.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
null
null
null
cmds/stagefright/record.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
2
2021-07-08T07:42:11.000Z
2021-07-09T21:56:10.000Z
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "SineSource.h" #include <binder/ProcessState.h> #include <datasource/FileSource.h> #include <media/stagefright/foundation/ADebug.h> #include <media/stagefright/foundation/ALooper.h> #include <media/stagefright/foundation/AMessage.h> #include <media/stagefright/CameraSource.h> #include <media/stagefright/MediaBufferGroup.h> #include <media/stagefright/MediaDefs.h> #include <media/stagefright/MediaCodecSource.h> #include <media/stagefright/MetaData.h> #include <media/stagefright/MediaExtractor.h> #include <media/stagefright/MediaExtractorFactory.h> #include <media/stagefright/MPEG4Writer.h> #include <media/stagefright/SimpleDecodingSource.h> #include <media/MediaPlayerInterface.h> #include "AudioPlayer.h" using namespace android; static const int32_t kAudioBitRate = 12200; #if 0 static const int32_t kFramerate = 24; // fps static const int32_t kIFramesIntervalSec = 1; static const int32_t kVideoBitRate = 512 * 1024; static const int64_t kDurationUs = 10000000LL; // 10 seconds class DummySource : public MediaSource { public: DummySource(int width, int height, int colorFormat) : mWidth(width), mHeight(height), mColorFormat(colorFormat), mSize((width * height * 3) / 2) { mGroup.add_buffer(new MediaBuffer(mSize)); // Check the color format to make sure // that the buffer size mSize it set correctly above. CHECK(colorFormat == OMX_COLOR_FormatYUV420SemiPlanar || colorFormat == OMX_COLOR_FormatYUV420Planar); } virtual sp<MetaData> getFormat() { sp<MetaData> meta = new MetaData; meta->setInt32(kKeyWidth, mWidth); meta->setInt32(kKeyHeight, mHeight); meta->setInt32(kKeyColorFormat, mColorFormat); meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW); return meta; } virtual status_t start(MetaData *params) { mNumFramesOutput = 0; return OK; } virtual status_t stop() { return OK; } virtual status_t read( MediaBuffer **buffer, const MediaSource::ReadOptions *options) { if (mNumFramesOutput == kFramerate * 10) { // Stop returning data after 10 secs. return ERROR_END_OF_STREAM; } // printf("DummySource::read\n"); status_t err = mGroup.acquire_buffer(buffer); if (err != OK) { return err; } char x = (char)((double)rand() / RAND_MAX * 255); memset((*buffer)->data(), x, mSize); (*buffer)->set_range(0, mSize); (*buffer)->meta_data()->clear(); (*buffer)->meta_data()->setInt64( kKeyTime, (mNumFramesOutput * 1000000) / kFramerate); ++mNumFramesOutput; // printf("DummySource::read - returning buffer\n"); // ALOGI("DummySource::read - returning buffer"); return OK; } protected: virtual ~DummySource() {} private: MediaBufferGroup mGroup; int mWidth, mHeight; int mColorFormat; size_t mSize; int64_t mNumFramesOutput;; DummySource(const DummySource &); DummySource &operator=(const DummySource &); }; sp<MediaSource> createSource(const char *filename) { sp<MediaSource> source; sp<MediaExtractor> extractor = MediaExtractorFactory::Create(new FileSource(filename)); if (extractor == NULL) { return NULL; } size_t num_tracks = extractor->countTracks(); sp<MetaData> meta; for (size_t i = 0; i < num_tracks; ++i) { meta = extractor->getTrackMetaData(i); CHECK(meta.get() != NULL); const char *mime; if (!meta->findCString(kKeyMIMEType, &mime)) { continue; } if (strncasecmp(mime, "video/", 6)) { continue; } source = extractor->getTrack(i); break; } return source; } enum { kYUV420SP = 0, kYUV420P = 1, }; // returns -1 if mapping of the given color is unsuccessful // returns an omx color enum value otherwise static int translateColorToOmxEnumValue(int color) { switch (color) { case kYUV420SP: return OMX_COLOR_FormatYUV420SemiPlanar; case kYUV420P: return OMX_COLOR_FormatYUV420Planar; default: fprintf(stderr, "Unsupported color: %d\n", color); return -1; } } int main(int argc, char **argv) { android::ProcessState::self()->startThreadPool(); #if 1 if (argc != 3) { fprintf(stderr, "usage: %s <filename> <input_color_format>\n", argv[0]); fprintf(stderr, " <input_color_format>: 0 (YUV420SP) or 1 (YUV420P)\n"); return 1; } int colorFormat = translateColorToOmxEnumValue(atoi(argv[2])); if (colorFormat == -1) { fprintf(stderr, "input color format must be 0 (YUV420SP) or 1 (YUV420P)\n"); return 1; } status_t err = OK; #if 0 sp<MediaSource> source = createSource(argv[1]); if (source == NULL) { fprintf(stderr, "Unable to find a suitable video track.\n"); return 1; } sp<MetaData> meta = source->getFormat(); sp<MediaSource> decoder = SimpleDecodingSource::Create(source); int width, height; bool success = meta->findInt32(kKeyWidth, &width); success = success && meta->findInt32(kKeyHeight, &height); CHECK(success); #else int width = 720; int height = 480; sp<MediaSource> decoder = new DummySource(width, height, colorFormat); #endif sp<AMessage> enc_meta = new AMessage; // enc_meta->setString("mime", MEDIA_MIMETYPE_VIDEO_H263); // enc_meta->setString("mime", MEDIA_MIMETYPE_VIDEO_MPEG4); enc_meta->setString("mime", MEDIA_MIMETYPE_VIDEO_AVC); enc_meta->setInt32("width", width); enc_meta->setInt32("height", height); enc_meta->setInt32("sample-rate", kFramerate); enc_meta->setInt32("bitrate", kVideoBitRate); // enc_meta->setInt32("stride", width); // enc_meta->setInt32("slice-height", height); enc_meta->setInt32("i-frame-interval", kIFramesIntervalSec); enc_meta->setInt32("color-format", colorFormat); sp<MediaSource> encoder = MediaCodecSource::Create(looper, format, decoder); #if 1 sp<MPEG4Writer> writer = new MPEG4Writer("/sdcard/output.mp4"); writer->addSource(encoder); writer->setMaxFileDuration(kDurationUs); CHECK_EQ((status_t)OK, writer->start()); while (!writer->reachedEOS()) { fprintf(stderr, "."); usleep(100000); } err = writer->stop(); #else CHECK_EQ((status_t)OK, encoder->start()); MediaBuffer *buffer; while (encoder->read(&buffer) == OK) { printf("."); fflush(stdout); int32_t isSync; if (!buffer->meta_data()->findInt32(kKeyIsSyncFrame, &isSync)) { isSync = false; } printf("got an output frame of size %d%s\n", buffer->range_length(), isSync ? " (SYNC)" : ""); buffer->release(); buffer = NULL; } err = encoder->stop(); #endif printf("$\n"); #endif #if 0 CameraSource *source = CameraSource::Create( String16(argv[0], strlen(argv[0]))); source->start(); printf("source = %p\n", source); for (int i = 0; i < 100; ++i) { MediaBuffer *buffer; status_t err = source->read(&buffer); CHECK_EQ(err, (status_t)OK); printf("got a frame, data=%p, size=%d\n", buffer->data(), buffer->range_length()); buffer->release(); buffer = NULL; } err = source->stop(); delete source; source = NULL; #endif if (err != OK && err != ERROR_END_OF_STREAM) { fprintf(stderr, "record failed: %d\n", err); return 1; } return 0; } #else int main(int /* argc */, char ** /* argv */) { android::ProcessState::self()->startThreadPool(); const int32_t kSampleRate = 22050; const int32_t kNumChannels = 2; sp<MediaSource> audioSource = new SineSource(kSampleRate, kNumChannels); #if 0 sp<MediaPlayerBase::AudioSink> audioSink; AudioPlayer *player = new AudioPlayer(audioSink); player->setSource(audioSource); player->start(); sleep(10); player->stop(); #endif sp<AMessage> encMeta = new AMessage; encMeta->setString("mime", 0 ? MEDIA_MIMETYPE_AUDIO_AMR_WB : MEDIA_MIMETYPE_AUDIO_AAC); encMeta->setInt32("sample-rate", kSampleRate); encMeta->setInt32("channel-count", kNumChannels); encMeta->setInt32("max-input-size", 8192); encMeta->setInt32("bitrate", kAudioBitRate); sp<ALooper> looper = new ALooper; looper->setName("record"); looper->start(); sp<MediaSource> encoder = MediaCodecSource::Create(looper, encMeta, audioSource); encoder->start(); int32_t n = 0; status_t err; MediaBufferBase *buffer; while ((err = encoder->read(&buffer)) == OK) { printf("."); fflush(stdout); buffer->release(); buffer = NULL; if (++n == 100) { break; } } printf("$\n"); encoder->stop(); return 0; } #endif
27.789174
87
0.629588
Dreadwyrm
37095ddb49b305a3229a1b8d5ff281f1c9a3463f
529
cpp
C++
xfa/fxfa/app/xfa_ffdraw.cpp
ADVAN-ELAA-8QM-PRC1/platform-external-pdfium
e67ae11a46c7b9f48ebc2efab8ca58cc9982cb38
[ "BSD-3-Clause" ]
18
2015-01-07T21:02:47.000Z
2021-01-19T02:14:58.000Z
xfa/fxfa/app/xfa_ffdraw.cpp
ADVAN-ELAA-8QM-PRC1/platform-external-pdfium
e67ae11a46c7b9f48ebc2efab8ca58cc9982cb38
[ "BSD-3-Clause" ]
1
2017-02-14T01:38:56.000Z
2017-02-15T06:01:13.000Z
xfa/fxfa/app/xfa_ffdraw.cpp
ADVAN-ELAA-8QM-PRC1/platform-external-pdfium
e67ae11a46c7b9f48ebc2efab8ca58cc9982cb38
[ "BSD-3-Clause" ]
10
2015-07-04T06:37:40.000Z
2021-04-08T09:31:20.000Z
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "xfa/fxfa/app/xfa_ffdraw.h" #include "xfa/fxfa/xfa_ffapp.h" #include "xfa/fxfa/xfa_ffdoc.h" #include "xfa/fxfa/xfa_ffpageview.h" #include "xfa/fxfa/xfa_ffwidget.h" CXFA_FFDraw::CXFA_FFDraw(CXFA_WidgetAcc* pDataAcc) : CXFA_FFWidget(pDataAcc) {} CXFA_FFDraw::~CXFA_FFDraw() {}
31.117647
80
0.761815
ADVAN-ELAA-8QM-PRC1
370a1b6d2d4bccf45fe401b1685cee1054ff769f
28,376
cpp
C++
wrappers/Modelica/src/coolpropsolver.cpp
friederikeboehm/CoolProp
44325d9e6abd9e6f88f428720f4f64a0c1962784
[ "MIT" ]
null
null
null
wrappers/Modelica/src/coolpropsolver.cpp
friederikeboehm/CoolProp
44325d9e6abd9e6f88f428720f4f64a0c1962784
[ "MIT" ]
null
null
null
wrappers/Modelica/src/coolpropsolver.cpp
friederikeboehm/CoolProp
44325d9e6abd9e6f88f428720f4f64a0c1962784
[ "MIT" ]
null
null
null
#include "coolpropsolver.h" #include "CoolPropTools.h" #include "CoolProp.h" #include "CPState.h" #include <iostream> #include <string> #include <stdlib.h> CoolPropSolver::CoolPropSolver(const std::string& mediumName, const std::string& libraryName, const std::string& substanceName) : BaseSolver(mediumName, libraryName, substanceName) { // Fluid name can be used to pass in other parameters. // The string can be composed like "Propane|enable_TTSE=1|calc_transport=0" std::vector<std::string> name_options = strsplit(substanceName, '|'); // Set the defaults fluidType = -1; enable_TTSE = false; debug_level = 0; calc_transport = false; extend_twophase = false; twophase_derivsmoothing_xend = 0; rho_smoothing_xend = 0; if (name_options.size() > 1) { for (unsigned int i = 1; i < name_options.size(); i++) { // Split around the equals sign std::vector<std::string> param_val = strsplit(name_options[i], '='); if (param_val.size() != 2) { errorMessage((char*)format("Could not parse the option [%s], must be in the form param=value", name_options[i].c_str()).c_str()); } // Check each of the options in turn if (!param_val[0].compare("enable_TTSE")) { if (!param_val[1].compare("1") || !param_val[1].compare("true")) { std::cout << "TTSE is on\n"; enable_TTSE = true; } else if (!param_val[1].compare("0") || !param_val[1].compare("false")) { std::cout << "TTSE is off\n"; enable_TTSE = false; } else errorMessage((char*)format("I don't know how to handle this option [%s]", name_options[i].c_str()).c_str()); //throw NotImplementedError((char*)format("I don't know how to handle this option [%s]",name_options[i].c_str()).c_str()); } else if (!param_val[0].compare("calc_transport")) { if (!param_val[1].compare("1") || !param_val[1].compare("true")) calc_transport = true; else if (!param_val[1].compare("0") || !param_val[1].compare("false")) calc_transport = false; else errorMessage((char*)format("I don't know how to handle this option [%s]", name_options[i].c_str()).c_str()); } else if (!param_val[0].compare("enable_EXTTP")) { if (!param_val[1].compare("1") || !param_val[1].compare("true")) extend_twophase = true; else if (!param_val[1].compare("0") || !param_val[1].compare("false")) extend_twophase = false; else errorMessage((char*)format("I don't know how to handle this option [%s]", name_options[i].c_str()).c_str()); } else if (!param_val[0].compare("twophase_derivsmoothing_xend")) { twophase_derivsmoothing_xend = strtod(param_val[1].c_str(), NULL); if (twophase_derivsmoothing_xend < 0 || twophase_derivsmoothing_xend > 1) errorMessage( (char*)format("I don't know how to handle this twophase_derivsmoothing_xend value [%d]", param_val[0].c_str()).c_str()); } else if (!param_val[0].compare("rho_smoothing_xend")) { rho_smoothing_xend = strtod(param_val[1].c_str(), NULL); if (rho_smoothing_xend < 0 || rho_smoothing_xend > 1) errorMessage((char*)format("I don't know how to handle this rho_smoothing_xend value [%d]", param_val[0].c_str()).c_str()); } else if (!param_val[0].compare("debug")) { debug_level = (int)strtol(param_val[1].c_str(), NULL, 0); if (debug_level < 0 || debug_level > 1000) errorMessage((char*)format("I don't know how to handle this debug level [%s]", param_val[0].c_str()).c_str()); } else { errorMessage((char*)format("This option [%s] was not understood", name_options[i].c_str()).c_str()); } // Some options were passed in, lets see what we have std::cout << param_val[0] << " has the value of " << param_val[1] << std::endl; } } // Handle the name and fill the fluid type if (debug_level > 5) std::cout << "Checking fluid " << name_options[0] << " against database." << std::endl; fluidType = getFluidType(name_options[0]); // Throws an error if unknown fluid if (debug_level > 5) std::cout << "Check passed, reducing " << substanceName << " to " << name_options[0] << std::endl; this->substanceName = name_options[0]; state = new CoolPropStateClassSI(name_options[0]); setFluidConstants(); } void CoolPropSolver::setFluidConstants() { if ((fluidType == FLUID_TYPE_PURE) || (fluidType == FLUID_TYPE_PSEUDOPURE) || (fluidType == FLUID_TYPE_REFPROP)) { if (debug_level > 5) std::cout << format("Setting constants for fluid %s \n", substanceName.c_str()); _fluidConstants.pc = PropsSI((char*)"pcrit", (char*)"T", 0, (char*)"P", 0, (char*)substanceName.c_str()); _fluidConstants.Tc = PropsSI((char*)"Tcrit", (char*)"T", 0, (char*)"P", 0, (char*)substanceName.c_str()); _fluidConstants.MM = PropsSI((char*)"molemass", (char*)"T", 0, (char*)"P", 0, (char*)substanceName.c_str()); _fluidConstants.dc = PropsSI((char*)"rhocrit", (char*)"T", 0, (char*)"P", 0, (char*)substanceName.c_str()); return; } if ((fluidType == FLUID_TYPE_INCOMPRESSIBLE_LIQUID) || (fluidType == FLUID_TYPE_INCOMPRESSIBLE_SOLUTION)) { if (debug_level > 5) std::cout << format("Setting constants for incompressible fluid %s \n", substanceName.c_str()); _fluidConstants.pc = -1; _fluidConstants.Tc = -1; _fluidConstants.MM = -1; _fluidConstants.dc = -1; return; } } void CoolPropSolver::preStateChange(void) { /// Some common code to avoid pitfalls from incompressibles if ((fluidType == FLUID_TYPE_PURE) || (fluidType == FLUID_TYPE_PSEUDOPURE) || (fluidType == FLUID_TYPE_REFPROP)) { try { if (enable_TTSE) state->enable_TTSE_LUT(); else state->disable_TTSE_LUT(); if (extend_twophase) state->enable_EXTTP(); else state->disable_EXTTP(); } catch (std::exception& e) { errorMessage((char*)e.what()); std::cout << format("Exception from state object: %s \n", (char*)e.what()); } } } void CoolPropSolver::postStateChange(ExternalThermodynamicState* const properties) { /// Some common code to avoid pitfalls from incompressibles switch (fluidType) { case FLUID_TYPE_PURE: case FLUID_TYPE_PSEUDOPURE: case FLUID_TYPE_REFPROP: try { // Set the values in the output structure properties->p = state->p(); properties->T = state->T(); properties->d = state->rho(); properties->h = state->h(); properties->s = state->s(); if (state->TwoPhase) { properties->phase = 2; } else { properties->phase = 1; } properties->cp = state->cp(); properties->cv = state->cv(); properties->a = state->speed_sound(); if (state->TwoPhase && state->Q() >= 0 && state->Q() <= twophase_derivsmoothing_xend) { // Use the smoothed derivatives between a quality of 0 and twophase_derivsmoothing_xend properties->ddhp = state->drhodh_constp_smoothed(twophase_derivsmoothing_xend); // [1/kPa -- > 1/Pa] properties->ddph = state->drhodp_consth_smoothed(twophase_derivsmoothing_xend); // [1/(kJ/kg) -- > 1/(J/kg)] } else if (state->TwoPhase && state->Q() >= 0 && state->Q() <= rho_smoothing_xend) { // Use the smoothed density between a quality of 0 and rho_smoothing_xend double rho_spline; double dsplinedh; double dsplinedp; state->rho_smoothed(rho_smoothing_xend, rho_spline, dsplinedh, dsplinedp); properties->ddhp = dsplinedh; properties->ddph = dsplinedp; properties->d = rho_spline; } else { properties->ddhp = state->drhodh_constp(); properties->ddph = state->drhodp_consth(); } properties->kappa = state->isothermal_compressibility(); properties->beta = state->isobaric_expansion_coefficient(); if (calc_transport) { properties->eta = state->viscosity(); properties->lambda = state->conductivity(); //[kW/m/K --> W/m/K] } else { properties->eta = -_HUGE; properties->lambda = -_HUGE; } } catch (std::exception& e) { errorMessage((char*)e.what()); } break; case FLUID_TYPE_INCOMPRESSIBLE_LIQUID: case FLUID_TYPE_INCOMPRESSIBLE_SOLUTION: try { // Set the values in the output structure properties->p = state->p(); properties->T = state->T(); properties->d = state->rho(); properties->h = state->h(); properties->s = state->s(); properties->phase = 1; properties->cp = state->cp(); properties->cv = state->cv(); properties->a = -_HUGE; properties->ddhp = state->drhodh_constp(); properties->ddph = 0.0; // TODO: Fix this properties->kappa = -_HUGE; properties->beta = -_HUGE; if (calc_transport) { properties->eta = state->viscosity(); properties->lambda = state->conductivity(); //[kW/m/K --> W/m/K] } else { properties->eta = -_HUGE; properties->lambda = -_HUGE; } } catch (std::exception& e) { errorMessage((char*)e.what()); } break; default: errorMessage((char*)"Invalid fluid type!"); break; } } void CoolPropSolver::setSat_p(double& p, ExternalSaturationProperties* const properties) { if (debug_level > 5) std::cout << format("setSat_p(%0.16e)\n", p); this->preStateChange(); try { state->update(iP, p, iQ, 0); // quality only matters for pseudo-pure fluids //! Saturation temperature properties->Tsat = state->TL(); // Not correct for pseudo-pure fluids //! Derivative of Ts wrt pressure properties->dTp = state->dTdp_along_sat(); //! Derivative of dls wrt pressure properties->ddldp = state->drhodp_along_sat_liquid(); //! Derivative of dvs wrt pressure properties->ddvdp = state->drhodp_along_sat_vapor(); //! Derivative of hls wrt pressure properties->dhldp = state->dhdp_along_sat_liquid(); //! Derivative of hvs wrt pressure properties->dhvdp = state->dhdp_along_sat_vapor(); //! Density at bubble line (for pressure ps) properties->dl = state->rhoL(); //! Density at dew line (for pressure ps) properties->dv = state->rhoV(); //! Specific enthalpy at bubble line (for pressure ps) properties->hl = state->hL(); //! Specific enthalpy at dew line (for pressure ps) properties->hv = state->hV(); //! Saturation pressure properties->psat = p; //! Surface tension properties->sigma = state->surface_tension(); //! Specific entropy at bubble line (for pressure ps) properties->sl = state->sL(); //! Specific entropy at dew line (for pressure ps) properties->sv = state->sV(); } catch (std::exception& e) { errorMessage((char*)e.what()); } } void CoolPropSolver::setSat_T(double& T, ExternalSaturationProperties* const properties) { if (debug_level > 5) std::cout << format("setSat_T(%0.16e)\n", T); this->preStateChange(); try { state->update(iT, T, iQ, 0); // Quality only matters for pseudo-pure fluids properties->Tsat = T; properties->psat = state->p(); properties->dl = state->rhoL(); properties->dv = state->rhoV(); properties->hl = state->hL(); properties->hv = state->hV(); properties->dTp = state->dTdp_along_sat(); properties->ddldp = state->drhodp_along_sat_liquid(); properties->ddvdp = state->drhodp_along_sat_vapor(); properties->dhldp = state->dhdp_along_sat_liquid(); properties->dhvdp = state->dhdp_along_sat_vapor(); } catch (std::exception& e) { errorMessage((char*)e.what()); } } // Note: the phase input is currently not supported void CoolPropSolver::setState_ph(double& p, double& h, int& phase, ExternalThermodynamicState* const properties) { if (debug_level > 5) std::cout << format("setState_ph(p=%0.16e,h=%0.16e)\n", p, h); this->preStateChange(); try { // Update the internal variables in the state instance state->update(iP, p, iH, h); if (!ValidNumber(state->rho()) || !ValidNumber(state->T())) { throw ValueError(format("p-h [%g, %g] failed for update", p, h)); } // Set the values in the output structure this->postStateChange(properties); } catch (std::exception& e) { errorMessage((char*)e.what()); } } void CoolPropSolver::setState_pT(double& p, double& T, ExternalThermodynamicState* const properties) { if (debug_level > 5) std::cout << format("setState_pT(p=%0.16e,T=%0.16e)\n", p, T); this->preStateChange(); try { // Update the internal variables in the state instance state->update(iP, p, iT, T); // Set the values in the output structure this->postStateChange(properties); } catch (std::exception& e) { errorMessage((char*)e.what()); } } // Note: the phase input is currently not supported void CoolPropSolver::setState_dT(double& d, double& T, int& phase, ExternalThermodynamicState* const properties) { if (debug_level > 5) std::cout << format("setState_dT(d=%0.16e,T=%0.16e)\n", d, T); this->preStateChange(); try { // Update the internal variables in the state instance state->update(iD, d, iT, T); // Set the values in the output structure this->postStateChange(properties); } catch (std::exception& e) { errorMessage((char*)e.what()); } } // Note: the phase input is currently not supported void CoolPropSolver::setState_ps(double& p, double& s, int& phase, ExternalThermodynamicState* const properties) { if (debug_level > 5) std::cout << format("setState_ps(p=%0.16e,s=%0.16e)\n", p, s); this->preStateChange(); try { // Update the internal variables in the state instance state->update(iP, p, iS, s); // Set the values in the output structure this->postStateChange(properties); } catch (std::exception& e) { errorMessage((char*)e.what()); } } // Note: the phase input is currently not supported void CoolPropSolver::setState_hs(double& h, double& s, int& phase, ExternalThermodynamicState* const properties) { if (debug_level > 5) std::cout << format("setState_hs(h=%0.16e,s=%0.16e)\n", h, s); this->preStateChange(); try { // Update the internal variables in the state instance state->update(iH, h, iS, s); // Set the values in the output structure this->postStateChange(properties); } catch (std::exception& e) { errorMessage((char*)e.what()); } } double CoolPropSolver::Pr(ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: Pr() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: Pr() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::T(ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: T() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: T() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::a(ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: a() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: a() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::beta(ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: beta() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: beta() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::cp(ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: cp() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: cp() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::cv(ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: cv() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: cv() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::d(ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: d() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: d() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::ddhp(ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: ddhp() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: ddhp() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::ddph(ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: ddph() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: ddph() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::eta(ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: eta() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: eta() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::h(ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: h() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: h() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::kappa(ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: kappa() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: kappa() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::lambda(ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: lambda() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: lambda() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::p(ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: p() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: p() not implemented in the Solver object"); return -_HUGE; } int CoolPropSolver::phase(ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: phase() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: phase() not implemented in the Solver object"); return -1; } double CoolPropSolver::s(ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: s() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: s() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::d_der(ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: d_der() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: d_der() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::isentropicEnthalpy(double& p, ExternalThermodynamicState* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: isentropicEnthalpy() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: isentropicEnthalpy() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::dTp(ExternalSaturationProperties* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: dTp() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: dTp() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::ddldp(ExternalSaturationProperties* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: ddldp() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: ddldp() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::ddvdp(ExternalSaturationProperties* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: ddvdp() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: ddvdp() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::dhldp(ExternalSaturationProperties* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: dhldp() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: dhldp() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::dhvdp(ExternalSaturationProperties* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: dhvdp() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: dhvdp() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::dl(ExternalSaturationProperties* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: dl() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: dl() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::dv(ExternalSaturationProperties* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: dv() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: dv() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::hl(ExternalSaturationProperties* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: hl() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: hl() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::hv(ExternalSaturationProperties* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: hv() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: hv() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::sigma(ExternalSaturationProperties* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: sigma() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: sigma() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::sl(ExternalSaturationProperties* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: sl() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: sl() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::sv(ExternalSaturationProperties* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: sv() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: sv() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::psat(ExternalSaturationProperties* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: psat() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: psat() not implemented in the Solver object"); return -_HUGE; } double CoolPropSolver::Tsat(ExternalSaturationProperties* const properties) { // Base function returns an error if called - should be redeclared by the solver object errorMessage((char*)"Internal error: Tsat() not implemented in the Solver object"); //throw NotImplementedError((char*)"Internal error: Tsat() not implemented in the Solver object"); return -_HUGE; }
47.451505
145
0.646673
friederikeboehm
370aff99bee3a95c0464f7040a326c5702bf2ac5
1,151
cpp
C++
Sorting/SelectionSort.cpp
ukayaj620/learn-algorithm
6437dcb4ac0f97faf6ffcfbbb2a18cb3a284ed96
[ "MIT" ]
null
null
null
Sorting/SelectionSort.cpp
ukayaj620/learn-algorithm
6437dcb4ac0f97faf6ffcfbbb2a18cb3a284ed96
[ "MIT" ]
null
null
null
Sorting/SelectionSort.cpp
ukayaj620/learn-algorithm
6437dcb4ac0f97faf6ffcfbbb2a18cb3a284ed96
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main () { int n, arr[10000]; // INPUT HOW MUCH NUMBER TO INPUT cout << "Numbers?: "; cin >> n; // INPUT THE NUMBERS for (int i=0; i<n; i++) { cin >> arr[i]; } // SELECTION SORT ALGORITHM (ASCENDING) for (int i=0; i<n-1; i++) { int min_index = i; for(int j=i+1; j<n; j++) { if (arr[j] < arr[min_index]) // CHECKING GREATER OR SMALLER { min_index = j; } int temp = arr[min_index]; arr[min_index] = arr[i]; arr[i] = temp; } } cout << "ASCENDING: "; // THE RESULT AFTER ASCENDING SORTING USING SELECTION SORT for (int i=0; i<n; i++) { cout << arr[i] << " "; } cout << "\n"; // SELECTION SORT ALGORITHM (DESCENDING) for (int i=0; i<n-1; i++) { int min_index = i; for(int j=i+1; j<n; j++) { if (arr[j] > arr[min_index]) // CHECKING GREATER OR SMALLER { min_index = j; } int temp = arr[min_index]; arr[min_index] = arr[i]; arr[i] = temp; } } cout << "DESCENDING: "; // THE RESULT AFTER DESCENDING SORTING USING SELECTION SORT for (int i=0; i<n; i++) { cout << arr[i] << " "; } cout << "\n"; return 0; }
16.926471
62
0.54735
ukayaj620
37115c56046fb2143589d2ab1124d2d65a1c62ba
3,717
cpp
C++
src/logging.cpp
CESNET/lldp-systemd-networkd-sysrepo
6d79dede96f720b77aa5bf132e7f16787002f6ce
[ "Apache-2.0" ]
null
null
null
src/logging.cpp
CESNET/lldp-systemd-networkd-sysrepo
6d79dede96f720b77aa5bf132e7f16787002f6ce
[ "Apache-2.0" ]
1
2020-10-31T23:05:17.000Z
2022-02-16T13:37:00.000Z
src/logging.cpp
CESNET/lldp-systemd-networkd-sysrepo
6d79dede96f720b77aa5bf132e7f16787002f6ce
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2020 CESNET, https://photonics.cesnet.cz/ * * Written by Jan Kundrát <jan.kundrat@cesnet.cz>, Tomáš Pecka <tomas.pecka@fit.cvut.cz> * */ extern "C" { #include <sysrepo.h> } #include <cinttypes> #include <cstdio> #include <cxxabi.h> #include <spdlog/sinks/systemd_sink.h> #include <sys/stat.h> #include <unistd.h> #include "logging.h" extern "C" { /** @short Propagate sysrepo events to spdlog */ static void spdlog_sr_log_cb(sr_log_level_t level, const char* message) { // Thread safety note: this is, as far as I know, thread safe: // - the static initialization itself is OK // - all loggers which we instantiate are thread-safe // - std::shared_ptr::operator-> is const, and all const members of that class are documented to be thread-safe static auto log = spdlog::get("sysrepo"); assert(log); switch (level) { case SR_LL_NONE: case SR_LL_ERR: log->error(message); break; case SR_LL_WRN: log->warn(message); break; case SR_LL_INF: log->info(message); break; case SR_LL_DBG: log->debug(message); break; } } } namespace lldp::utils { /** @short Initialize logging Creates and registers all required loggers and connect them to the provided sink. */ void initLogs(std::shared_ptr<spdlog::sinks::sink> sink) { auto defaultLogger = std::make_shared<spdlog::logger>("lldp-systemd-sysrepo", sink); spdlog::register_logger(defaultLogger); spdlog::set_default_logger(defaultLogger); spdlog::register_logger(std::make_shared<spdlog::logger>("sysrepo", sink)); sr_log_set_cb(spdlog_sr_log_cb); } /** @short Is stderr connected to journald? Not thread safe. */ bool isJournaldActive() { const auto stream = ::getenv("JOURNAL_STREAM"); if (!stream) { return false; } uintmax_t dev; uintmax_t inode; if (::sscanf(stream, "%" SCNuMAX ":%" SCNuMAX, &dev, &inode) != 2) { return false; } struct stat buf; if (fstat(STDERR_FILENO, &buf)) { return false; } return static_cast<uintmax_t>(buf.st_dev) == dev && static_cast<uintmax_t>(buf.st_ino) == inode; } namespace impl { /** @short Provide better levels, see https://github.com/gabime/spdlog/pull/1292#discussion_r340777258 */ template <typename Mutex> class journald_sink : public spdlog::sinks::systemd_sink<Mutex> { public: journald_sink() { this->syslog_levels_ = {/* spdlog::level::trace */ LOG_DEBUG, /* spdlog::level::debug */ LOG_INFO, /* spdlog::level::info */ LOG_NOTICE, /* spdlog::level::warn */ LOG_WARNING, /* spdlog::level::err */ LOG_ERR, /* spdlog::level::critical */ LOG_CRIT, /* spdlog::level::off */ LOG_ALERT}; } }; } std::shared_ptr<spdlog::sinks::sink> create_journald_sink() { return std::make_shared<impl::journald_sink<std::mutex>>(); } /** @short Log that everything is screwed up and rethrow The purpose is to make sure that a nicely formatted error message gets stored into the journald buffer with a high enough priority. */ void fatalException [[noreturn]] (std::shared_ptr<spdlog::logger> log, const std::exception& e, const std::string& when) { int demangled; char* classname = __cxxabiv1::__cxa_demangle(typeid(e).name(), nullptr, 0, &demangled); log->critical("Fatal error in {}: {}", when, demangled == 0 ? classname : typeid(e).name()); log->critical("{}", e.what()); free(classname); throw; } } /* namespace lldp::utils */
30.719008
131
0.626581
CESNET
3712559010b696fc5e1e43045dd56302b79daed1
2,571
inl
C++
src/cunumeric/matrix/tile_template.inl
marcinz/cunumeric
c40b038d4eb0611f7bb16d5bd11891a633ef7892
[ "Apache-2.0" ]
118
2021-04-12T18:06:59.000Z
2021-10-12T21:30:24.000Z
src/cunumeric/matrix/tile_template.inl
marcinz/cunumeric
c40b038d4eb0611f7bb16d5bd11891a633ef7892
[ "Apache-2.0" ]
51
2021-04-21T10:40:13.000Z
2021-09-10T22:09:26.000Z
src/cunumeric/matrix/tile_template.inl
marcinz/cunumeric
c40b038d4eb0611f7bb16d5bd11891a633ef7892
[ "Apache-2.0" ]
9
2021-04-14T03:07:42.000Z
2021-09-22T17:02:53.000Z
/* Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "cunumeric/pitches.h" namespace cunumeric { using namespace Legion; using namespace legate; template <int32_t OUT_DIM, int32_t IN_DIM> __CUDA_HD__ inline Point<IN_DIM> get_tile_point(const Point<OUT_DIM>& point, const Point<IN_DIM>& strides) { Point<IN_DIM> result; for (int32_t out_idx = OUT_DIM - 1, in_idx = IN_DIM - 1; in_idx >= 0; --out_idx, --in_idx) result[in_idx] = point[out_idx] % strides[in_idx]; return result; } template <VariantKind KIND, typename VAL, int32_t OUT_DIM, int32_t IN_DIM> struct TileImplBody; template <VariantKind KIND, typename VAL> struct TileImpl { template <int32_t OUT_DIM, int32_t IN_DIM, std::enable_if_t<IN_DIM <= OUT_DIM>* = nullptr> void operator()(TileArgs& args) const { const auto out_rect = args.out.shape<OUT_DIM>(); Pitches<OUT_DIM - 1> out_pitches; auto out_volume = out_pitches.flatten(out_rect); if (out_volume == 0) return; const auto in_rect = args.in.shape<IN_DIM>(); Point<IN_DIM> in_strides = in_rect.hi + Point<IN_DIM>::ONES(); auto out = args.out.write_accessor<VAL, OUT_DIM>(); auto in = args.in.read_accessor<VAL, IN_DIM>(); TileImplBody<KIND, VAL, OUT_DIM, IN_DIM>{}( out_rect, out_pitches, out_volume, in_strides, out, in); } template <int32_t OUT_DIM, int32_t IN_DIM, std::enable_if_t<!(IN_DIM <= OUT_DIM)>* = nullptr> void operator()(TileArgs& args) const { assert(false); } }; template <VariantKind KIND> struct TileDispatch { template <LegateTypeCode CODE> void operator()(TileArgs& args) const { using VAL = legate_type_of<CODE>; double_dispatch(args.out.dim(), args.in.dim(), TileImpl<KIND, VAL>{}, args); } }; template <VariantKind KIND> static void tile_template(TaskContext& context) { TileArgs args{context.inputs()[0], context.outputs()[0]}; type_dispatch(args.in.code(), TileDispatch<KIND>{}, args); } } // namespace cunumeric
30.975904
95
0.698561
marcinz
371484c32adb41d06fec45db2cc24a093f1875b0
4,009
cpp
C++
src/ros_tutorials/roscpp_tutorials/custom_callback_processing/custom_callback_processing.cpp
duken72/ros2wsTest
4fa8f7aaf9ec8e70a8b6d7554ced373300a38a71
[ "MIT" ]
742
2017-07-05T02:49:36.000Z
2022-03-30T12:55:43.000Z
src/ros_tutorials/roscpp_tutorials/custom_callback_processing/custom_callback_processing.cpp
duken72/ros2wsTest
4fa8f7aaf9ec8e70a8b6d7554ced373300a38a71
[ "MIT" ]
73
2017-07-06T12:50:51.000Z
2022-03-07T08:07:07.000Z
src/ros_tutorials/roscpp_tutorials/custom_callback_processing/custom_callback_processing.cpp
duken72/ros2wsTest
4fa8f7aaf9ec8e70a8b6d7554ced373300a38a71
[ "MIT" ]
425
2017-07-04T22:03:29.000Z
2022-03-29T06:59:06.000Z
/* * Copyright (C) 2009, Willow Garage, Inc. * * 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 Stanford University or Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "ros/ros.h" #include "ros/callback_queue.h" #include "std_msgs/String.h" #include <boost/thread.hpp> /** * This tutorial demonstrates the use of custom separate callback queues that can be processed * independently, whether in different threads or just at different times. */ /** * This callback gets called from the main queue processed in spin() */ void chatterCallbackMainQueue(const std_msgs::String::ConstPtr& msg) { ROS_INFO_STREAM("I heard: [ " << msg->data << "] in thread [" << boost::this_thread::get_id() << "] (Main thread)"); } /** * This callback gets called from the custom queue */ void chatterCallbackCustomQueue(const std_msgs::String::ConstPtr& msg) { ROS_INFO_STREAM("I heard: [ " << msg->data << "] in thread [" << boost::this_thread::get_id() << "]"); } /** * The custom queue used for one of the subscription callbacks */ ros::CallbackQueue g_queue; void callbackThread() { ROS_INFO_STREAM("Callback thread id=" << boost::this_thread::get_id()); ros::NodeHandle n; while (n.ok()) { g_queue.callAvailable(ros::WallDuration(0.01)); } } int main(int argc, char **argv) { ros::init(argc, argv, "listener_with_custom_callback_processing"); ros::NodeHandle n; /** * The SubscribeOptions structure lets you specify a custom queue to use for a specific subscription. * You can also set a default queue on a NodeHandle using the NodeHandle::setCallbackQueue() function. * * AdvertiseOptions and AdvertiseServiceOptions offer similar functionality. */ ros::SubscribeOptions ops = ros::SubscribeOptions::create<std_msgs::String>("chatter", 1000, chatterCallbackCustomQueue, ros::VoidPtr(), &g_queue); ros::Subscriber sub = n.subscribe(ops); /** * Now we subscribe using the normal method, to demonstrate the difference. */ ros::Subscriber sub2 = n.subscribe("chatter", 1000, chatterCallbackMainQueue); /** * Start a thread to service the custom queue */ boost::thread chatter_thread(callbackThread); ROS_INFO_STREAM("Main thread id=" << boost::this_thread::get_id()); /** * Now do a custom spin, to demonstrate the difference. */ ros::Rate r(1); while (n.ok()) { ros::spinOnce(); r.sleep(); } chatter_thread.join(); return 0; }
36.117117
118
0.694936
duken72
3715fd906a7cf0cf89a6e98fbc665d31ccabf64b
3,479
cpp
C++
libs/libgui/src/animation.cpp
mbits-os/JiraDesktop
eb9b66b9c11b2fba1079f03a6f90aea425ce6138
[ "MIT" ]
null
null
null
libs/libgui/src/animation.cpp
mbits-os/JiraDesktop
eb9b66b9c11b2fba1079f03a6f90aea425ce6138
[ "MIT" ]
null
null
null
libs/libgui/src/animation.cpp
mbits-os/JiraDesktop
eb9b66b9c11b2fba1079f03a6f90aea425ce6138
[ "MIT" ]
null
null
null
/* * Copyright (C) 2015 midnightBITS * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "pch.h" #include <gui/animation.hpp> namespace ani { struct actor { actor(const std::shared_ptr<animation>& target, std::chrono::milliseconds duration, uint32_t counts); ~actor(); const std::shared_ptr<animation>& target() const; void start(); bool step(); private: using clock = std::chrono::high_resolution_clock; std::shared_ptr<animation> m_target; clock::duration m_duration; uint32_t m_counts; clock::time_point m_startTime; }; actor::actor(const std::shared_ptr<animation>& target, std::chrono::milliseconds duration, uint32_t counts) : m_target(target) , m_duration(duration) , m_counts(counts) { } actor::~actor() { m_target->shutdown(); } const std::shared_ptr<animation>& actor::target() const { return m_target; } void actor::start() { m_target->init(); m_startTime = clock::now(); } bool actor::step() { auto now = clock::now(); auto running = now - m_startTime; if (m_counts && (running / m_duration > m_counts)) return false; auto timeframe = running % m_duration; auto frame = animation::step_max * timeframe / m_duration; m_target->step((uint32_t)frame); return true; } void scene::animate(const std::shared_ptr<animation>& target, std::chrono::milliseconds duration, uint32_t counts) { if (!target) return; remove(target); std::lock_guard<std::mutex> guard(m_mtx); auto animator = std::make_shared<actor>(target, duration, counts); animator->start(); m_actors.push_back(std::move(animator)); } void scene::animate(const std::shared_ptr<animation>& target, std::chrono::milliseconds duration) { return animate(target, duration, 0); } void scene::remove(const std::shared_ptr<animation>& target) { if (!target) return; std::lock_guard<std::mutex> guard(m_mtx); auto it = std::find_if(std::begin(m_actors), std::end(m_actors), [&](const std::shared_ptr<actor>& ptr) { return ptr->target() == target; }); if (it == std::end(m_actors)) return; m_actors.erase(it); return; } bool scene::step() { std::lock_guard<std::mutex> guard(m_mtx); auto it = std::begin(m_actors), end = std::end(m_actors); while (it != end) { auto& actor = *it; if (!actor->step()) { it = m_actors.erase(it); end = std::end(m_actors); } else { ++it; } } return !m_actors.empty(); } }
25.580882
115
0.694452
mbits-os
37165a40dad2e0075a25d5412d3e053e86f06868
12,830
cpp
C++
QtRPT-Example/QtRptProject/QtRptDesigner/TContainerLine.cpp
salim97/QtRPT
0bb1cb7e2c8d5c638f53092625b00bb608d9ede3
[ "MIT" ]
null
null
null
QtRPT-Example/QtRptProject/QtRptDesigner/TContainerLine.cpp
salim97/QtRPT
0bb1cb7e2c8d5c638f53092625b00bb608d9ede3
[ "MIT" ]
null
null
null
QtRPT-Example/QtRptProject/QtRptDesigner/TContainerLine.cpp
salim97/QtRPT
0bb1cb7e2c8d5c638f53092625b00bb608d9ede3
[ "MIT" ]
3
2019-12-23T12:51:20.000Z
2022-03-17T03:36:53.000Z
/* Name: QtRpt Version: 1.5.5 Web-site: http://www.qtrpt.tk Programmer: Aleksey Osipov E-mail: aliks-os@ukr.net Web-site: http://www.aliks-os.tk Copyright 2012-2015 Aleksey Osipov Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "TContainerLine.h" #include "ReportBand.h" TContainerLine::TContainerLine(QWidget *parent, QPoint p, QWidget *cWidget) : RptContainer(parent,p,cWidget) { QString stl = "TContainerLine#lbl {;" "border-width:1px;" "border-style:solid;" "border-color:rgba(0,0,0,255);" "border-top-color:rgba(0,0,0,255);" "border-left-color:rgba(0,0,0,255);" "border-right-color:rgba(0,0,0,255);" "border-bottom-color:rgba(0,0,0,255);" "color:rgba(0,0,0,255);" "background-color:rgba(255,255,255,0);" "}"; cs = 0; ce = 0; m_arrowStart = false; m_arrowEnd = true; this->setStyleSheet(stl); this->resize(10,10); this->setBaseSize(width(),height()); this->allowResize(false); this->allowDrawSelection(false); this->setAutoFillBackground(true); this->move(-50,-50); line.setP1( QPoint() ); line.setP2( QPoint() ); QPalette Pal(palette()); Pal.setColor(QPalette::Background, Qt::blue); cs = new XYZContainer(parent,QPoint(line.p1().x(), line.p2().y())); cs->setObjectName("CS"); cs->resize(6,6); cs->allowResize(false); cs->allowDrawSelection(false); cs->setVisible(false); cs->setAutoFillBackground(true); cs->setPalette(Pal); ce = new XYZContainer(parent,QPoint(line.p2().x(), line.p2().y())); ce->setObjectName("CE"); ce->resize(6,6); ce->allowResize(false); ce->allowDrawSelection(false); ce->setVisible(false); ce->setAutoFillBackground(true); ce->setPalette(Pal); QObject::connect(cs, SIGNAL(newGeometry(QRect, QRect)), this, SIGNAL(newGeometry(QRect, QRect))); QObject::connect(ce, SIGNAL(newGeometry(QRect, QRect)), this, SIGNAL(newGeometry(QRect, QRect))); QObject::connect(ce, SIGNAL(newGeometry(QRect, QRect)), this, SLOT(lineChanged(QRect, QRect))); QObject::connect(cs, SIGNAL(newGeometry(QRect, QRect)), this, SLOT(lineChanged(QRect, QRect))); //QObject::connect(cs, SIGNAL(geomChanged(QRect, QRect)), this, SIGNAL(geomChanged(QRect, QRect))); //QObject::connect(ce, SIGNAL(geomChanged(QRect, QRect)), this, SIGNAL(geomChanged(QRect, QRect))); QObject::connect(cs, SIGNAL(geomChanged(QRect, QRect)), this, SLOT(geomContChanged(QRect, QRect))); QObject::connect(ce, SIGNAL(geomChanged(QRect, QRect)), this, SLOT(geomContChanged(QRect, QRect))); QObject::connect(cs, SIGNAL(destroyed()), this, SLOT(delItemInTree())); QObject::connect(ce, SIGNAL(destroyed()), this, SLOT(delItemInTree())); QObject::connect(this, SIGNAL(delCont(QTreeWidgetItem *)), this, SLOT(delItemInTree())); QObject::connect(cs, SIGNAL(inFocus(bool)), this, SLOT(m_inFocus(bool))); QObject::connect(ce, SIGNAL(inFocus(bool)), this, SLOT(m_inFocus(bool))); //QObject::connect(this, SIGNAL(inFocus(bool)), cs, SIGNAL(inFocus(bool))); //QObject::connect(this, SIGNAL(inFocus(bool)), ce, SIGNAL(inFocus(bool))); this->show(); } void TContainerLine::geomContChanged(QRect oldRect, QRect newRect) { if (sender() == cs) { m_oldP1 = oldRect; m_oldP2 = ce->geometry(); } if (sender() == ce) { m_oldP1 = cs->geometry(); m_oldP2 = oldRect; } emit geomChanged(oldRect,newRect); } void TContainerLine::delItemInTree() { delete this; } void TContainerLine::setArrow(Command command, QVariant value) { if (command == ArrowStart) m_arrowStart = value.toBool(); if (command ==ArrowEnd) m_arrowEnd = value.toBool(); this->parentWidget()->repaint(); } bool TContainerLine::getArrow(Command command) { bool result = false; if (command == ArrowStart) result = m_arrowStart; if (command ==ArrowEnd) result = m_arrowEnd; return result; } void TContainerLine::focusInEvent(QFocusEvent *e) { XYZContainer::focusInEvent(e); setLine(true); } void TContainerLine::focusOutEvent(QFocusEvent *e) { XYZContainer::focusInEvent(e); if (cs != 0 && ce != 0) setSelectedLine(QPoint(0,0)); } void TContainerLine::m_inFocus(bool value) { setLine(value); emit inFocus(value); } void TContainerLine::setLine(bool value) { QPalette pal(Qt::white); bool selected = false; if (value) { pal.setColor(QPalette::Background, Qt::blue); selected = true; } ce->setPalette(pal); cs->setPalette(pal); ce->setVisible(selected); cs->setVisible(selected); } void TContainerLine::setSelectedLine(QPoint point) { QList<TContainerLine *> contLineList = this->parentWidget()->findChildren<TContainerLine *>(); foreach (TContainerLine *contLine, contLineList) { bool selected = false; QPointF intersectPnt; QLineF line(point.x()-5, point.y()-5, point.x()+5, point.y()+5); if (contLine->line.intersect(line, &intersectPnt) == QLineF::BoundedIntersection) { if (!contLine->hasFocus()) { contLine->setFocus(); } selected = true; } if (contLine->ce->hasFocus() && this->ce->rect().contains(point)) { selected = true; } if (contLine->cs->hasFocus() && this->cs->rect().contains(point)) { selected = true; } contLine->setLine(selected); } } void TContainerLine::lineChanged(QRect, QRect) { if (cs != 0 && !cs->pos().isNull()) line.setP1( cs->pos()+QPoint(3,3) ); if (ce != 0 && !ce->pos().isNull()) line.setP2( ce->pos()+QPoint(3,3) ); } void TContainerLine::movePoint(XYZContainer *cont, QRect rect) { cont->move(rect.x(),rect.y()); lineChanged(QRect(),QRect()); this->parentWidget()->repaint(); } void TContainerLine::setParent(QWidget *parent) { RptContainer::setParent(parent); ce->setParent(parent); cs->setParent(parent); } void TContainerLine::setObjectName(const QString &name) { const QString old_name = this->objectName(); QObject::setObjectName(name); QString str = this->styleSheet().replace("lbl",name).replace(old_name,name); this->setStyleSheet(str); } void TContainerLine::loadParamFromXML(QDomElement e) { RptContainer::loadParamFromXML(e); //this->setSheetValue(BackgroundColor,e.attribute("backgroundColor","rgba(255,255,255,0)")); this->setSheetValue(BorderColor,e.attribute("borderColor","rgba(0,0,0,255)")); this->line.setP1(QPointF(e.attribute("lineStartX","0").toDouble(), e.attribute("lineStartY","0" ).toDouble())); this->line.setP2(QPointF(e.attribute("lineEndX","0").toDouble(), e.attribute("lineEndY","0" ).toDouble())); this->m_arrowStart = e.attribute("arrowStart","0").toInt(); this->m_arrowEnd = e.attribute("arrowEnd","0").toInt(); this->cs->move(this->line.toLine().p1()-QPoint(3,3)); this->ce->move(this->line.toLine().p2()-QPoint(3,3)); } QDomElement TContainerLine::saveParamToXML(QDomDocument *xmlDoc) { QDomElement elem = RptContainer::saveParamToXML(xmlDoc); QString borderColor = colorToString(getColorValue(BorderColor)); elem.setAttribute("borderColor",borderColor); elem.setAttribute("borderStyle",getBorderStyleStr()); elem.setAttribute("lineStartX",this->line.p1().x()); elem.setAttribute("lineStartY",this->line.p1().y()); elem.setAttribute("lineEndX",this->line.p2().x()); elem.setAttribute("lineEndY",this->line.p2().y()); elem.setAttribute("arrowStart",this->m_arrowStart); elem.setAttribute("arrowEnd",this->m_arrowEnd); return elem; } void TContainerLine::setMenu(QMenu *menu_) { QIcon icon; QAction *actContDel = new QAction(tr("Delete"),this); icon.addPixmap(QPixmap(QString::fromUtf8(":/new/prefix1/images/delete.png")), QIcon::Normal, QIcon::On); actContDel->setObjectName("actContDel"); actContDel->setIcon(icon); QObject::connect(actContDel, SIGNAL(triggered()), this, SIGNAL(deleteByUser())); QObject::connect(actContDel, SIGNAL(triggered()), this, SLOT(deleteLater())); menu->clear(); menu->insertActions(0,menu_->actions()); menu->addAction(actContDel); } TContainerLine *TContainerLine::clone() { TContainerLine *newContField = new TContainerLine(this->parentWidget(),QPoint(0,0),0); newContField->setType(this->getType()); newContField->setStyleSheet(this->styleSheet()); newContField->setGeometry(this->geometry()); newContField->setBaseSize(this->baseSize()); newContField->setVisible(true); newContField->move(-10,-10); newContField->line.setP1( this->line.p1()+QPointF(5,5)); newContField->line.setP2( this->line.p2()+QPointF(5,5)); newContField->cs->move( this->cs->pos()+QPoint(5,5) ); newContField->ce->move( this->ce->pos()+QPoint(5,5) ); newContField->setArrow(ArrowStart, this->getArrow(ArrowStart)); newContField->setArrow(ArrowEnd, this->getArrow(ArrowEnd)); newContField->setColorValue(BorderColor,this->getColorValue(BorderColor)); newContField->setBorderWidth(this->getBorderWidth()); return newContField; } qreal TContainerLine::getLength() { return line.length(); } void TContainerLine::drawArrow(QPainter *painter) { // Draw the arrows static const double Pi = 3.14159265358979323846264338327950288419717; static double TwoPi = 2.0 * Pi; double angle = ::acos(line.dx() / line.length()); if (line.dy() >= 0) angle = TwoPi - angle; QPointF sourcePoint = line.p1(); QPointF destPoint = line.p2(); int arrowSize= 10; painter->setBrush(getColorValue(BorderColor)); if (m_arrowStart) { QPointF sourceArrowP1 = sourcePoint + QPointF(sin(angle + Pi / 3) * arrowSize, cos(angle + Pi / 3) * arrowSize); QPointF sourceArrowP2 = sourcePoint + QPointF(sin(angle + Pi - Pi / 3) * arrowSize, cos(angle + Pi - Pi / 3) * arrowSize); painter->drawPolygon(QPolygonF() << line.p1() << sourceArrowP1 << sourceArrowP2); } if (m_arrowEnd) { QPointF destArrowP1 = destPoint + QPointF(sin(angle - Pi / 3) * arrowSize, cos(angle - Pi / 3) * arrowSize); QPointF destArrowP2 = destPoint + QPointF(sin(angle - Pi + Pi / 3) * arrowSize, cos(angle - Pi + Pi / 3) * arrowSize); painter->drawPolygon(QPolygonF() << line.p2() << destArrowP1 << destArrowP2); } } TContainerLine::~TContainerLine() { if (cs != 0) { cs->deleteLater(); cs = 0; } if (ce != 0) { ce->deleteLater(); ce = 0; } } void TContainerLine::setProperties() { this->setProperty("FieldType",m_type); } //Restore fields from properties void TContainerLine::setParamFromProperties() { m_type = (FieldType)this->property("FieldType").toInt(); } QDataStream &operator<<(QDataStream &stream, const TContainerLine &obj) { for(int i=0; i<obj.metaObject()->propertyCount(); ++i) { if(obj.metaObject()->property(i).isStored(&obj)) { stream << obj.metaObject()->property(i).read(&obj); } } QList<QByteArray> list = obj.dynamicPropertyNames(); for (int i=0; i<list.size(); i++) { stream << obj.property(list.at(i)); } stream << *obj.cs; stream << *obj.ce; return stream; } QDataStream &operator>>(QDataStream &stream, TContainerLine &obj) { QVariant var; for(int i=0; i<obj.metaObject()->propertyCount(); ++i) { if(obj.metaObject()->property(i).isStored(&obj)) { stream >> var; if (!var.isNull()) obj.metaObject()->property(i).write(&obj, var); } } obj.setProperties(); QList<QByteArray> list = obj.dynamicPropertyNames(); for (int i=0; i<list.size(); i++) { stream >> var; obj.setProperty(list.at(i),QVariant(var)); } obj.setParamFromProperties(); stream >> *obj.cs; stream >> *obj.ce; return stream; }
35.150685
115
0.633983
salim97
3717cf8ec69118ea296ade4607ef88216db07397
7,573
cpp
C++
td/telegram/net/SessionProxy.cpp
sintyaaaaa/td
0e930c15d3cd65dc5cc3fa6e8492684038129510
[ "BSL-1.0" ]
1
2019-10-12T18:08:04.000Z
2019-10-12T18:08:04.000Z
td/telegram/net/SessionProxy.cpp
sintyaaaaa/td
0e930c15d3cd65dc5cc3fa6e8492684038129510
[ "BSL-1.0" ]
null
null
null
td/telegram/net/SessionProxy.cpp
sintyaaaaa/td
0e930c15d3cd65dc5cc3fa6e8492684038129510
[ "BSL-1.0" ]
1
2020-08-14T12:43:30.000Z
2020-08-14T12:43:30.000Z
// // Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2019 // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "td/telegram/net/SessionProxy.h" #include "td/telegram/Global.h" #include "td/telegram/net/ConnectionCreator.h" #include "td/telegram/net/DcId.h" #include "td/telegram/net/NetQueryDispatcher.h" #include "td/telegram/net/Session.h" #include "td/telegram/UniqueId.h" #include "td/actor/PromiseFuture.h" #include "td/utils/common.h" #include "td/utils/logging.h" #include "td/utils/Slice.h" #include <functional> namespace td { namespace mtproto { class RawConnection; } // namespace mtproto class SessionCallback : public Session::Callback { public: SessionCallback(ActorShared<SessionProxy> parent, DcId dc_id, bool allow_media_only, bool is_media, size_t hash) : parent_(std::move(parent)) , dc_id_(dc_id) , allow_media_only_(allow_media_only) , is_media_(is_media) , hash_(hash) { } void on_failed() override { send_closure(parent_, &SessionProxy::on_failed); } void on_closed() override { send_closure(parent_, &SessionProxy::on_closed); } void request_raw_connection(unique_ptr<mtproto::AuthData> auth_data, Promise<unique_ptr<mtproto::RawConnection>> promise) override { send_closure(G()->connection_creator(), &ConnectionCreator::request_raw_connection, dc_id_, allow_media_only_, is_media_, std::move(promise), hash_, std::move(auth_data)); } void on_tmp_auth_key_updated(mtproto::AuthKey auth_key) override { send_closure(parent_, &SessionProxy::on_tmp_auth_key_updated, std::move(auth_key)); } void on_server_salt_updated(std::vector<mtproto::ServerSalt> server_salts) override { send_closure(parent_, &SessionProxy::on_server_salt_updated, std::move(server_salts)); } void on_result(NetQueryPtr query) override { if (UniqueId::extract_type(query->id()) != UniqueId::BindKey && query->id() != 0) { // not bind key query and not an update send_closure(parent_, &SessionProxy::on_query_finished); } G()->net_query_dispatcher().dispatch(std::move(query)); } private: ActorShared<SessionProxy> parent_; DcId dc_id_; bool allow_media_only_ = false; bool is_media_ = false; size_t hash_ = 0; }; SessionProxy::SessionProxy(unique_ptr<Callback> callback, std::shared_ptr<AuthDataShared> shared_auth_data, bool is_main, bool allow_media_only, bool is_media, bool use_pfs, bool is_cdn, bool need_destroy) : callback_(std::move(callback)) , auth_data_(std::move(shared_auth_data)) , is_main_(is_main) , allow_media_only_(allow_media_only) , is_media_(is_media) , use_pfs_(use_pfs) , is_cdn_(is_cdn) , need_destroy_(need_destroy) { } void SessionProxy::start_up() { class Listener : public AuthDataShared::Listener { public: explicit Listener(ActorShared<SessionProxy> session_proxy) : session_proxy_(std::move(session_proxy)) { } bool notify() override { if (!session_proxy_.is_alive()) { return false; } send_closure(session_proxy_, &SessionProxy::update_auth_key_state); return true; } private: ActorShared<SessionProxy> session_proxy_; }; auth_key_state_ = auth_data_->get_auth_key_state().first; auth_data_->add_auth_key_listener(make_unique<Listener>(actor_shared(this))); open_session(); } void SessionProxy::tear_down() { for (auto &query : pending_queries_) { query->resend(); callback_->on_query_finished(); G()->net_query_dispatcher().dispatch(std::move(query)); } pending_queries_.clear(); } void SessionProxy::send(NetQueryPtr query) { if (query->auth_flag() == NetQuery::AuthFlag::On && auth_key_state_ != AuthKeyState::OK) { query->debug(PSTRING() << get_name() << ": wait for auth"); pending_queries_.emplace_back(std::move(query)); return; } open_session(true); query->debug(PSTRING() << get_name() << ": sent to session"); send_closure(session_, &Session::send, std::move(query)); } void SessionProxy::update_main_flag(bool is_main) { if (is_main_ == is_main) { return; } LOG(INFO) << "Update " << get_name() << " is_main to " << is_main; is_main_ = is_main; close_session(); open_session(); } void SessionProxy::update_destroy(bool need_destroy) { need_destroy_ = need_destroy; close_session(); open_session(); } void SessionProxy::on_failed() { if (session_generation_ != get_link_token()) { return; } close_session(); open_session(); } void SessionProxy::update_mtproto_header() { close_session(); open_session(); } void SessionProxy::on_closed() { } void SessionProxy::close_session() { send_closure(std::move(session_), &Session::close); session_generation_++; } void SessionProxy::open_session(bool force) { if (!session_.empty()) { return; } // There are several assumption that make this code OK // 1. All unauthorized query will be sent into the same SessionProxy // 2. All authorized query are delayed before we have authorization // So only one SessionProxy will be active before we have authorization key auto should_open = [&]() { if (force) { return true; } if (need_destroy_) { return auth_key_state_ != AuthKeyState::Empty; } if (auth_key_state_ != AuthKeyState::OK) { return false; } return is_main_ || !pending_queries_.empty(); }(); if (!should_open) { return; } CHECK(session_.empty()); auto dc_id = auth_data_->dc_id(); string name = PSTRING() << "Session" << get_name().substr(Slice("SessionProxy").size()); string hash_string = PSTRING() << name << " " << dc_id.get_raw_id() << " " << allow_media_only_; auto hash = std::hash<std::string>()(hash_string); int32 int_dc_id = dc_id.get_raw_id(); if (G()->is_test_dc()) { int_dc_id += 10000; } if (allow_media_only_ && !is_cdn_) { int_dc_id = -int_dc_id; } session_ = create_actor<Session>( name, make_unique<SessionCallback>(actor_shared(this, session_generation_), dc_id, allow_media_only_, is_media_, hash), auth_data_, int_dc_id, is_main_, use_pfs_, is_cdn_, need_destroy_, tmp_auth_key_, server_salts_); } void SessionProxy::update_auth_key_state() { auto old_auth_key_state = auth_key_state_; auth_key_state_ = auth_data_->get_auth_key_state().first; if (auth_key_state_ != old_auth_key_state && old_auth_key_state == AuthKeyState::OK) { close_session(); } open_session(); if (session_.empty() || auth_key_state_ != AuthKeyState::OK) { return; } for (auto &query : pending_queries_) { query->debug(PSTRING() << get_name() << ": sent to session"); send_closure(session_, &Session::send, std::move(query)); } pending_queries_.clear(); } void SessionProxy::on_tmp_auth_key_updated(mtproto::AuthKey auth_key) { Slice state; if (auth_key.empty()) { state = Slice("Empty"); } else if (auth_key.auth_flag()) { state = Slice("OK"); } else { state = Slice("NoAuth"); } LOG(WARNING) << "Have tmp_auth_key " << auth_key.id() << ": " << state; tmp_auth_key_ = std::move(auth_key); } void SessionProxy::on_server_salt_updated(std::vector<mtproto::ServerSalt> server_salts) { server_salts_ = std::move(server_salts); } void SessionProxy::on_query_finished() { callback_->on_query_finished(); } } // namespace td
30.784553
119
0.692196
sintyaaaaa
371a7ef4925afa4dce7d6fb64afd7766d3a94857
11,455
cpp
C++
clang/test/OpenMP/target_teams_distribute_parallel_for_simd_linear_messages.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,102
2015-01-04T02:28:35.000Z
2022-03-30T12:53:41.000Z
clang/test/OpenMP/target_teams_distribute_parallel_for_simd_linear_messages.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang/test/OpenMP/target_teams_distribute_parallel_for_simd_linear_messages.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
1,868
2015-01-03T04:27:11.000Z
2022-03-25T13:37:35.000Z
// RUN: %clang_cc1 -verify -fopenmp %s -Wuninitialized // RUN: %clang_cc1 -verify -fopenmp-simd %s -Wuninitialized typedef void **omp_allocator_handle_t; extern const omp_allocator_handle_t omp_default_mem_alloc; extern const omp_allocator_handle_t omp_large_cap_mem_alloc; extern const omp_allocator_handle_t omp_const_mem_alloc; extern const omp_allocator_handle_t omp_high_bw_mem_alloc; extern const omp_allocator_handle_t omp_low_lat_mem_alloc; extern const omp_allocator_handle_t omp_cgroup_mem_alloc; extern const omp_allocator_handle_t omp_pteam_mem_alloc; extern const omp_allocator_handle_t omp_thread_mem_alloc; void xxx(int argc) { int i, step; // expected-note {{initialize the variable 'step' to silence this warning}} #pragma omp target teams distribute parallel for simd linear(i : step) // expected-warning {{variable 'step' is uninitialized when used here}} for (i = 0; i < 10; ++i) ; } namespace X { int x; }; struct B { static int ib; // expected-note {{'B::ib' declared here}} static int bfoo() { return 8; } }; int bfoo() { return 4; } int z; const int C1 = 1; const int C2 = 2; void test_linear_colons() { int B = 0; // expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear(B:bfoo()) for (int i = 0; i < 10; ++i) ; // expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear(B::ib:B:bfoo()) // expected-error {{unexpected ':' in nested name specifier; did you mean '::'}} for (int i = 0; i < 10; ++i) ; // expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear(B:ib) // expected-error {{use of undeclared identifier 'ib'; did you mean 'B::ib'}} for (int i = 0; i < 10; ++i) ; // expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear(z:B:ib) // expected-error {{unexpected ':' in nested name specifier; did you mean '::'?}} for (int i = 0; i < 10; ++i) ; // expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear(B:B::bfoo()) for (int i = 0; i < 10; ++i) ; // expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear(X::x : ::z) for (int i = 0; i < 10; ++i) ; // expected-error@+1 3 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear(B,::z, X::x) for (int i = 0; i < 10; ++i) ; // expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear(::z) for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute parallel for simd linear(B::bfoo()) // expected-error {{expected variable name}} for (int i = 0; i < 10; ++i) ; // expected-error@+1 2 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear(B::ib,B:C1+C2) for (int i = 0; i < 10; ++i) ; } template<int L, class T, class N> T test_template(T* arr, N num) { N i; T sum = (T)0; T ind2 = - num * L; // expected-note {{'ind2' defined here}} #pragma omp target teams distribute parallel for simd linear(ind2:L) // expected-error {{argument of a linear clause should be of integral or pointer type}} for (i = 0; i < num; ++i) { T cur = arr[(int)ind2]; ind2 += L; sum += cur; } return T(); } template<int LEN> int test_warn() { int ind2 = 0; // expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear(ind2:LEN) // expected-warning {{zero linear step (ind2 should probably be const)}} for (int i = 0; i < 100; i++) { ind2 += LEN; } return ind2; } struct S1; // expected-note 2 {{declared here}} expected-note 2 {{forward declaration of 'S1'}} extern S1 a; class S2 { mutable int a; public: S2():a(0) { } }; const S2 b; // expected-note 2 {{'b' defined here}} const S2 ba[5]; class S3 { int a; public: S3():a(0) { } }; const S3 ca[5]; class S4 { int a; S4(); public: S4(int v):a(v) { } }; class S5 { int a; S5():a(0) {} public: S5(int v):a(v) { } }; S3 h; #pragma omp threadprivate(h) // expected-note 2 {{defined as threadprivate or thread local}} template<class I, class C> int foomain(I argc, C **argv) { I e(4); I g(5); int i; int &j = i; #pragma omp target teams distribute parallel for simd linear // expected-error {{expected '(' after 'linear'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd linear ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd linear () // expected-error {{expected expression}} for (int k = 0; k < argc; ++k) ++k; // expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear (argc // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; // expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear (argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd linear (argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; // expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear (argc : 5) allocate , allocate(, allocate(omp_default , allocate(omp_default_mem_alloc, allocate(omp_default_mem_alloc:, allocate(omp_default_mem_alloc: argc, allocate(omp_default_mem_alloc: argv), allocate(argv) // expected-error {{expected '(' after 'allocate'}} expected-error 2 {{expected expression}} expected-error 2 {{expected ')'}} expected-error {{use of undeclared identifier 'omp_default'}} expected-note 2 {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd linear (S1) // expected-error {{'S1' does not refer to a value}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd linear (a, b:B::ib) // expected-error {{linear variable with incomplete type 'S1'}} expected-error {{argument of a linear clause should be of integral or pointer type, not 'S2'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd linear (argv[1]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; // expected-error@+1 2 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear(e, g) for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd linear(h) // expected-error {{threadprivate or thread local variable cannot be linear}} for (int k = 0; k < argc; ++k) ++k; // expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear(i) for (int k = 0; k < argc; ++k) ++k; return 0; } namespace A { double x; #pragma omp threadprivate(x) // expected-note {{defined as threadprivate or thread local}} } namespace C { using A::x; } int main(int argc, char **argv) { double darr[100]; // expected-note@+1 {{in instantiation of function template specialization 'test_template<-4, double, int>' requested here}} test_template<-4>(darr, 4); // expected-note@+1 {{in instantiation of function template specialization 'test_warn<0>' requested here}} test_warn<0>(); S4 e(4); // expected-note {{'e' defined here}} S5 g(5); // expected-note {{'g' defined here}} int i; int &j = i; #pragma omp target teams distribute parallel for simd linear // expected-error {{expected '(' after 'linear'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd linear ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd linear () // expected-error {{expected expression}} for (int k = 0; k < argc; ++k) ++k; // expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear (argc // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; // expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear (argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd linear (argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; // expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}} #pragma omp target teams distribute parallel for simd linear (argc) for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd linear (S1) // expected-error {{'S1' does not refer to a value}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd linear (a, b) // expected-error {{linear variable with incomplete type 'S1'}} expected-error {{argument of a linear clause should be of integral or pointer type, not 'S2'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd linear (argv[1]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd linear(e, g) // expected-error {{argument of a linear clause should be of integral or pointer type, not 'S4'}} expected-error {{argument of a linear clause should be of integral or pointer type, not 'S5'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd linear(h, C::x) // expected-error 2 {{threadprivate or thread local variable cannot be linear}} for (int k = 0; k < argc; ++k) ++k; foomain<int,char>(argc,argv); // expected-note {{in instantiation of function template specialization 'foomain<int, char>' requested here}} return 0; }
45.456349
500
0.6921
medismailben
371b9f40f7dbb7f926000ae17bcff9791eed1aad
4,753
cpp
C++
src/gamecredits.cpp
cpusam/dangerous_tux
e5f099f3e3665d62f1c484458125f003c1d5eece
[ "Zlib" ]
1
2020-09-18T07:43:07.000Z
2020-09-18T07:43:07.000Z
src/gamecredits.cpp
cpusam/dangerous_tux
e5f099f3e3665d62f1c484458125f003c1d5eece
[ "Zlib" ]
null
null
null
src/gamecredits.cpp
cpusam/dangerous_tux
e5f099f3e3665d62f1c484458125f003c1d5eece
[ "Zlib" ]
null
null
null
#include "gamecredits.hpp" CGameCredits::CGameCredits ( SDL_Renderer * r ) { SDL_Surface * aux; #if _WIN32 || _WIN64 char path[FILENAME_MAX], bg_path[FILENAME_MAX]; char p2[FILENAME_MAX]; _getcwd(p2, sizeof(p2)); #else char path[1024], bg_path[1024]; #endif #if _WIN32 || _WIN64 #ifndef PREFIX sprintf(path, "%s\\fonts\\inhouseedition.ttf", p2); #else sprintf(path, "%s\\dangeroustux\\fonts\\inhouseedition.ttf", PREFIX); #endif #else #ifndef PREFIX sprintf(path, "./fonts/inhouseedition.ttf"); #else sprintf(path, "%s/share/games/dangeroustux/fonts/inhouseedition.ttf", PREFIX); #endif #endif if (!Writer::instance()->load_font(path, path, 100)) throw "CGameCredits: não foi possível carregar font\n"; Writer::instance()->set_renderer(r); char s[5][32] = { {71,82,65,80,72,73,67,83}, {71,85,83,84,65,86,79,32,77,69,68,69,73,82,79,83}, {80,82,79,71,82,65,77,77,73,78,71}, {83,65,77,85,69,76,32,76,69,79,78,65,82,68,79}, {84,72,73,65,71,79,32,72,85,80,78,69,82}, }; GuiLabel * g = new GuiLabel(s[0], (SDL_Color){255,255,255,0}); widget.add_child(g); GuiLabel * gg = new GuiLabel(s[1], (SDL_Color){255,255,0,0}); widget.add_child(gg); GuiLabel * p = new GuiLabel(s[2], (SDL_Color){255,255,255,0}); widget.add_child(p); GuiLabel * ps = new GuiLabel(s[3], (SDL_Color){255,255,0,0}); widget.add_child(ps); GuiLabel * t = new GuiLabel(s[4], (SDL_Color){255,255,0,0}); widget.add_child(t); widget.set_pos(Vect(960/2,624/2)); int h = g->get_texture_height() + gg->get_texture_height() + p->get_texture_height() + ps->get_texture_height(); g->set_rel_pos(Vect(-(g->get_texture_width()/2), h)); gg->set_rel_pos(Vect(-(gg->get_texture_width()/2), g->get_texture_height() + g->get_rel_pos().y)); p->set_rel_pos(Vect(-(p->get_texture_width()/2), gg->get_texture_height() + gg->get_rel_pos().y)); ps->set_rel_pos(Vect(-(ps->get_texture_width()/2), p->get_texture_height() + p->get_rel_pos().y)); t->set_rel_pos(Vect(-(t->get_texture_width()/2), ps->get_texture_height() + ps->get_rel_pos().y)); #if _WIN32 || _WIN64 #ifndef PREFIX sprintf(path, "%s\\images\\tux_walk.png", p2); #else sprintf(path, "%s\\dangeroustux\\images\\tux_walk.png", PREFIX); #endif #else #ifndef PREFIX sprintf(path, "./images/tux_walk.png"); #else sprintf(path, "%s/share/games/dangeroustux/images/tux_walk.png", PREFIX); #endif #endif #if _WIN32 || _WIN64 #ifndef PREFIX sprintf(bg_path, "%s\\images\\credits_BG.png", p2); #else sprintf(bg_path, "%s\\dangeroustux\\images\\credits_BG.png", PREFIX); #endif #else #ifndef PREFIX sprintf(bg_path, "./images/credits_BG.png"); #else sprintf(bg_path, "%s/share/games/dangeroustux/images/credits_BG.png", PREFIX); #endif #endif anim.add_frame(NULL, (SDL_Rect){0,0,0,0}, 15000); SDL_Texture * texture = IMG_LoadTexture(r, path); if (!texture) throw "CGameCredits: não foi possivel carregar tux_walk.png\n"; tux_anim.add_frame(texture, (SDL_Rect){0, 0,214,234}, 200); tux_anim.add_frame(texture, (SDL_Rect){0, 234,214,234}, 200); // meio tux_anim.add_frame(texture, (SDL_Rect){0,2*234,214,234}, 200); tux_anim.add_frame(texture, (SDL_Rect){0, 234,214,234}, 200); // meio //tux_pos.x = widget.get_pos().x - texture_width(texture)/2; tux_pos.x = (960 - texture_width(texture))/2; if (!bg.set_texture(IMG_LoadTexture(r, bg_path))) throw "CGameCredits: não foi possível carregar credits_BG.png\n"; //widget.set_pos(Vect(960/2, 358/2)); tux_pos.y = 358; cam = new Camera((SDL_Rect){0,0,texture_width(bg.get_texture()),texture_height(bg.get_texture())}, (SDL_Rect){0,0,2000*texture_width(bg.get_texture()),texture_height(bg.get_texture())}); set_state(ACTIVE_CREDITS); } CGameCredits::~CGameCredits ( ) { Widget * w = widget.get_child(0); for (int i = 0; w; i++, w = widget.get_child(i)) delete w; delete cam; tux_anim.destroy_textures(); } void CGameCredits::draw ( SDL_Renderer * renderer ) { SDL_SetRenderDrawColor(renderer, 0x00,0xc6,0xff,0xFF); SDL_RenderFillRect(renderer, NULL); bg.draw_hor(renderer, cam); tux_anim.draw(renderer, tux_pos.x, tux_pos.y); widget.draw(renderer); } void CGameCredits::reset ( ) { bg_pos.zero(); cam->set_position(Vect()); anim.reset(); tux_anim.reset(); set_state(ACTIVE_CREDITS); } int CGameCredits::update ( ) { bg_pos.x += 5.50f; cam->set_position(bg_pos); auto children = widget.get_children(); for (auto child : children){ auto pos = child->get_pos(); if (pos.y < -1000) break; pos.y -= 2.5f; child->set_pos(pos); } widget.child_update(); widget.update(); tux_anim.update(); if (anim.update() == 3) set_state(INACTIVE_CREDITS); return get_state(); }
27.795322
187
0.673469
cpusam
371c13b60ea02cdbffa7cb54a6e594fecdd1a94c
15,321
cpp
C++
tests/test_solver.cpp
polyfem/solver-wrapper
c7f68cabc9ed93839a946d0d55d70df9b1b05f46
[ "MIT" ]
2
2020-05-30T18:23:34.000Z
2020-05-30T19:16:54.000Z
tests/test_solver.cpp
polyfem/solver-wrapper
c7f68cabc9ed93839a946d0d55d70df9b1b05f46
[ "MIT" ]
null
null
null
tests/test_solver.cpp
polyfem/solver-wrapper
c7f68cabc9ed93839a946d0d55d70df9b1b05f46
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////// #include <polysolve/FEMSolver.hpp> #include <catch2/catch.hpp> #include <iostream> #include <unsupported/Eigen/SparseExtra> #include <fstream> #include <vector> #include <ctime> #include <polysolve/LinearSolverAMGCL.hpp> ////////////////////////////////////////////////////////////////////////// using namespace polysolve; void loadSymmetric(Eigen::SparseMatrix<double> &A, std::string PATH) { std::ifstream fin(PATH); long int M, N, L; while (fin.peek() == '%') { fin.ignore(2048, '\n'); } fin >> M >> N >> L; A.resize(M, N); A.reserve(L * 2 - M); std::vector<Eigen::Triplet<double>> triple; for (size_t i = 0; i < L; i++) { int m, n; double data; fin >> m >> n >> data; triple.push_back(Eigen::Triplet<double>(m - 1, n - 1, data)); if (m != n) { triple.push_back(Eigen::Triplet<double>(n - 1, m - 1, data)); } } fin.close(); A.setFromTriplets(triple.begin(), triple.end()); }; TEST_CASE("all", "[solver]") { const std::string path = POLYSOLVE_DATA_DIR; Eigen::SparseMatrix<double> A; const bool ok = loadMarket(A, path + "/A_2.mat"); REQUIRE(ok); auto solvers = LinearSolver::availableSolvers(); for (const auto &s : solvers) { if (s == "Eigen::DGMRES") continue; #ifdef WIN32 if (s == "Eigen::ConjugateGradient" || s == "Eigen::BiCGSTAB" || s == "Eigen::GMRES" || s == "Eigen::MINRES") continue; #endif auto solver = LinearSolver::create(s, ""); solver->setParameters(R"({"conv_tol": 1e-10})"_json); Eigen::VectorXd b(A.rows()); b.setRandom(); Eigen::VectorXd x(b.size()); x.setZero(); solver->analyzePattern(A, A.rows()); solver->factorize(A); solver->solve(b, x); // solver->getInfo(solver_info); // std::cout<<"Solver error: "<<x<<std::endl; const double err = (A * x - b).norm(); INFO("solver: " + s); REQUIRE(err < 1e-8); } } TEST_CASE("pre_factor", "[solver]") { const std::string path = POLYSOLVE_DATA_DIR; Eigen::SparseMatrix<double> A; const bool ok = loadMarket(A, path + "/A_2.mat"); REQUIRE(ok); auto solvers = LinearSolver::availableSolvers(); for (const auto &s : solvers) { if (s == "Eigen::DGMRES") continue; #ifdef WIN32 if (s == "Eigen::ConjugateGradient" || s == "Eigen::BiCGSTAB" || s == "Eigen::GMRES" || s == "Eigen::MINRES") continue; #endif auto solver = LinearSolver::create(s, ""); solver->analyzePattern(A, A.rows()); std::default_random_engine eng{42}; std::uniform_real_distribution<double> urd(0.1, 5); for (int i = 0; i < 10; ++i) { std::vector<Eigen::Triplet<double>> tripletList; for (int k = 0; k < A.outerSize(); ++k) { for (Eigen::SparseMatrix<double>::InnerIterator it(A, k); it; ++it) { if (it.row() == it.col()) { tripletList.emplace_back(it.row(), it.col(), urd(eng) * 100); } else if (it.row() < it.col()) { const double val = -urd(eng); tripletList.emplace_back(it.row(), it.col(), val); tripletList.emplace_back(it.col(), it.row(), val); } } } Eigen::SparseMatrix<double> Atmp(A.rows(), A.cols()); Atmp.setFromTriplets(tripletList.begin(), tripletList.end()); Eigen::VectorXd b(Atmp.rows()); b.setRandom(); Eigen::VectorXd x(b.size()); x.setZero(); solver->factorize(Atmp); solver->solve(b, x); // solver->getInfo(solver_info); // std::cout<<"Solver error: "<<x<<std::endl; const double err = (Atmp * x - b).norm(); INFO("solver: " + s); REQUIRE(err < 1e-8); } } } #ifdef POLYSOLVE_WITH_HYPRE TEST_CASE("hypre", "[solver]") { const std::string path = POLYSOLVE_DATA_DIR; Eigen::SparseMatrix<double> A; const bool ok = loadMarket(A, path + "/A_2.mat"); REQUIRE(ok); auto solver = LinearSolver::create("Hypre", ""); // solver->setParameters(params); Eigen::VectorXd b(A.rows()); b.setRandom(); Eigen::VectorXd x(b.size()); x.setZero(); solver->analyzePattern(A, A.rows()); solver->factorize(A); solver->solve(b, x); // solver->getInfo(solver_info); // std::cout<<"Solver error: "<<x<<std::endl; const double err = (A * x - b).norm(); REQUIRE(err < 1e-8); } TEST_CASE("hypre_initial_guess", "[solver]") { const std::string path = POLYSOLVE_DATA_DIR; Eigen::SparseMatrix<double> A; const bool ok = loadMarket(A, path + "/A_2.mat"); REQUIRE(ok); // solver->setParameters(params); Eigen::VectorXd b(A.rows()); b.setRandom(); Eigen::VectorXd x(A.rows()); x.setZero(); { json solver_info; auto solver = LinearSolver::create("Hypre", ""); solver->analyzePattern(A, A.rows()); solver->factorize(A); solver->solve(b, x); solver->getInfo(solver_info); REQUIRE(solver_info["num_iterations"] > 1); } { json solver_info; auto solver = LinearSolver::create("Hypre", ""); solver->analyzePattern(A, A.rows()); solver->factorize(A); solver->solve(b, x); solver->getInfo(solver_info); REQUIRE(solver_info["num_iterations"] == 1); } // std::cout<<"Solver error: "<<x<<std::endl; const double err = (A * x - b).norm(); REQUIRE(err < 1e-8); } #endif #ifdef POLYSOLVE_WITH_AMGCL TEST_CASE("amgcl_initial_guess", "[solver]") { const std::string path = POLYSOLVE_DATA_DIR; Eigen::SparseMatrix<double> A; const bool ok = loadMarket(A, path + "/A_2.mat"); REQUIRE(ok); // solver->setParameters(params); Eigen::VectorXd b(A.rows()); b.setRandom(); Eigen::VectorXd x(A.rows()); x.setZero(); { json solver_info; auto solver = LinearSolver::create("AMGCL", ""); solver->analyzePattern(A, A.rows()); solver->factorize(A); solver->solve(b, x); solver->getInfo(solver_info); REQUIRE(solver_info["num_iterations"] > 0); } { json solver_info; auto solver = LinearSolver::create("AMGCL", ""); solver->analyzePattern(A, A.rows()); solver->factorize(A); solver->solve(b, x); solver->getInfo(solver_info); REQUIRE(solver_info["num_iterations"] == 0); } // std::cout<<"Solver error: "<<x<<std::endl; const double err = (A * x - b).norm(); REQUIRE(err < 1e-8); } #endif TEST_CASE("saddle_point_test", "[solver]") { #ifdef WIN32 #ifndef NDEBUG return; #endif #endif const std::string path = POLYSOLVE_DATA_DIR; Eigen::SparseMatrix<double> A; bool ok = loadMarket(A, path + "/A0.mat"); REQUIRE(ok); Eigen::VectorXd b; ok = loadMarketVector(b, path + "/b0.mat"); REQUIRE(ok); auto solver = LinearSolver::create("SaddlePointSolver", ""); solver->analyzePattern(A, 9934); solver->factorize(A); Eigen::VectorXd x(A.rows()); solver->solve(b, x); const double err = (A * x - b).norm(); REQUIRE(err < 1e-8); } #ifdef POLYSOLVE_WITH_AMGCL TEST_CASE("amgcl_blocksolver_small_scale", "[solver]") { #ifndef NDEBUG return; #endif const std::string path = POLYSOLVE_DATA_DIR; Eigen::SparseMatrix<double> A; const bool ok = loadMarket(A, path + "/A_2.mat"); REQUIRE(ok); // solver->setParameters(params); Eigen::VectorXd b(A.rows()); b.setRandom(); Eigen::VectorXd x(A.rows()); Eigen::VectorXd x_b(A.rows()); x.setZero(); x_b.setZero(); { json solver_info; auto solver = LinearSolver::create("AMGCL", ""); solver->setParameters(R"({"conv_tol": 1e-8})"_json); solver->analyzePattern(A, A.rows()); solver->factorize(A); solver->solve(b, x); solver->getInfo(solver_info); REQUIRE(solver_info["num_iterations"] > 0); const double err = (A * x - b).norm(); REQUIRE(err < 1e-5); } { json solver_info; auto solver = LinearSolver::create("AMGCL", ""); solver->setParameters(R"({"conv_tol": 1e-8,"block_size": 3})"_json); solver->analyzePattern(A, A.rows()); solver->factorize(A); solver->solve(b, x_b); solver->getInfo(solver_info); REQUIRE(solver_info["num_iterations"] > 0); const double err = (A * x_b - b).norm(); REQUIRE(err < 1e-5); } } #endif #ifdef POLYSOLVE_WITH_AMGCL TEST_CASE("amgcl_blocksolver_b2", "[solver]") { #ifndef NDEBUG return; #endif const std::string path = POLYSOLVE_DATA_DIR; std::string MatrixName = "gr_30_30.mtx"; Eigen::SparseMatrix<double> A; loadSymmetric(A, path + "/" + MatrixName); std::cout << "Matrix Load OK" << std::endl; Eigen::VectorXd b(A.rows()); b.setRandom(); Eigen::VectorXd x(A.rows()); Eigen::VectorXd x_b(A.rows()); x.setOnes(); x_b.setOnes(); { amgcl::profiler<> prof("gr_30_30_Scalar"); json solver_info; auto solver = LinearSolver::create("AMGCL", ""); prof.tic("setup"); solver->setParameters(R"({"conv_tol": 1e-8,"max_iter": 1000})"_json); solver->analyzePattern(A, A.rows()); solver->factorize(A); prof.toc("setup"); prof.tic("solve"); solver->solve(b, x); prof.toc("solve"); solver->getInfo(solver_info); REQUIRE(solver_info["num_iterations"] > 0); std::cout << solver_info["num_iterations"] << std::endl; std::cout << solver_info["final_res_norm"] << std::endl << prof << std::endl; } { amgcl::profiler<> prof("gr_30_30_Block"); json solver_info; auto solver = LinearSolver::create("AMGCL", ""); prof.tic("setup"); solver->setParameters(R"({"conv_tol": 1e-8,"max_iter": 1000,"block_size": 2})"_json); solver->analyzePattern(A, A.rows()); solver->factorize(A); prof.toc("setup"); prof.tic("solve"); solver->solve(b, x_b); prof.toc("solve"); solver->getInfo(solver_info); REQUIRE(solver_info["num_iterations"] >0); std::cout<<solver_info["num_iterations"]<<std::endl; std::cout << solver_info["final_res_norm"] << std::endl << prof << std::endl; } REQUIRE((A * x - b).norm() / b.norm() < 1e-7); REQUIRE((A * x_b - b).norm() / b.norm() < 1e-7); } #endif #ifdef POLYSOLVE_WITH_AMGCL TEST_CASE("amgcl_blocksolver_crystm03_CG", "[solver]") { #ifndef NDEBUG return; #endif std::cout << "Polysolve AMGCL Solver" <<std::endl; const std::string path = POLYSOLVE_DATA_DIR; std::string MatrixName = "crystm03.mtx"; Eigen::SparseMatrix<double> A; loadSymmetric(A, path + "/" + MatrixName); std::cout<<"Matrix Load OK"<<std::endl; Eigen::VectorXd b(A.rows()); b.setOnes(); Eigen::VectorXd x_b(A.rows()); x_b.setZero(); Eigen::VectorXd x(A.rows()); x.setZero(); { amgcl::profiler<> prof("crystm03_Block"); json solver_info; auto solver = LinearSolver::create("AMGCL", ""); prof.tic("setup"); solver->setParameters(R"({"conv_tol": 1e-8,"max_iter": 10000,"block_size": 3})"_json); solver->analyzePattern(A, A.rows()); solver->factorize(A); prof.toc("setup"); prof.tic("solve"); solver->solve(b, x_b); prof.toc("solve"); solver->getInfo(solver_info); REQUIRE(solver_info["num_iterations"] > 0); std::cout << solver_info["num_iterations"] << std::endl; std::cout << solver_info["final_res_norm"] << std::endl << prof << std::endl; } { amgcl::profiler<> prof("crystm03_Scalar"); json solver_info; auto solver = LinearSolver::create("AMGCL", ""); prof.tic("setup"); solver->setParameters(R"({"conv_tol": 1e-8,"max_iter": 10000})"_json); solver->analyzePattern(A, A.rows()); solver->factorize(A); prof.toc("setup"); prof.tic("solve"); solver->solve(b, x); prof.toc("solve"); solver->getInfo(solver_info); REQUIRE(solver_info["num_iterations"] > 0); std::cout<<solver_info["num_iterations"]<<std::endl; std::cout << solver_info["final_res_norm"] << std::endl << prof << std::endl; } REQUIRE((A * x - b).norm() / b.norm() < 1e-7); REQUIRE((A * x_b - b).norm() / b.norm() < 1e-7); } #endif #ifdef POLYSOLVE_WITH_AMGCL TEST_CASE("amgcl_blocksolver_crystm03_Bicgstab", "[solver]") { #ifndef NDEBUG return; #endif std::cout << "Polysolve AMGCL Solver" << std::endl; const std::string path = POLYSOLVE_DATA_DIR; std::string MatrixName = "crystm03.mtx"; Eigen::SparseMatrix<double> A; loadSymmetric(A, path + "/" + MatrixName); std::cout << "Matrix Load OK" << std::endl; Eigen::VectorXd b(A.rows()); b.setOnes(); Eigen::VectorXd x_b(A.rows()); x_b.setZero(); Eigen::VectorXd x(A.rows()); x.setZero(); { amgcl::profiler<> prof("crystm03_Block"); json solver_info; auto solver = LinearSolver::create("AMGCL", ""); prof.tic("setup"); solver->setParameters(R"({"conv_tol": 1e-8,"max_iter": 10000,"solver_type": "bicgstab","block_size": 3})"_json); solver->analyzePattern(A, A.rows()); solver->factorize(A); prof.toc("setup"); prof.tic("solve"); solver->solve(b, x_b); prof.toc("solve"); solver->getInfo(solver_info); REQUIRE(solver_info["num_iterations"] > 0); std::cout << solver_info["num_iterations"] << std::endl; std::cout << solver_info["final_res_norm"] << std::endl << prof << std::endl; } { amgcl::profiler<> prof("crystm03_Scalar"); json solver_info; auto solver = LinearSolver::create("AMGCL", ""); prof.tic("setup"); solver->setParameters(R"({"conv_tol": 1e-8,"max_iter": 10000,"solver_type":"bicgstab"})"_json); solver->analyzePattern(A, A.rows()); solver->factorize(A); prof.toc("setup"); prof.tic("solve"); solver->solve(b, x); prof.toc("solve"); solver->getInfo(solver_info); REQUIRE(solver_info["num_iterations"] > 0); std::cout << solver_info["num_iterations"] << std::endl; std::cout << solver_info["final_res_norm"] << std::endl << prof << std::endl; } REQUIRE((A * x - b).norm() / b.norm() < 1e-7); REQUIRE((A * x_b - b).norm() / b.norm() < 1e-7); } #endif
29.749515
120
0.545656
polyfem
7deab687b399e21866c78bbc3df6a2a9c3b22180
2,600
cpp
C++
src/TestPorter/main.cpp
v1otusc/wondertrader
fd65a052d26be32882f89e8e9dfcd1d7b8736a3b
[ "MIT" ]
null
null
null
src/TestPorter/main.cpp
v1otusc/wondertrader
fd65a052d26be32882f89e8e9dfcd1d7b8736a3b
[ "MIT" ]
1
2022-03-21T06:51:59.000Z
2022-03-21T06:51:59.000Z
src/TestPorter/main.cpp
v1otusc/wondertrader
fd65a052d26be32882f89e8e9dfcd1d7b8736a3b
[ "MIT" ]
null
null
null
#define _CRT_SECURE_NO_WARNINGS #include "../WtPorter/WtPorter.h" //#include "../WtExecMon/WtExecPorter.h" #include "../Includes/WTSStruct.h" #include "../Share/DLLHelper.hpp" #include "../Share/CodeHelper.hpp" void PORTER_FLAG on_init(CtxHandler ctxid) { printf("on_init\r\n"); hft_sub_ticks(ctxid, "CFFEX.IF.HOT"); } void PORTER_FLAG on_tick(CtxHandler ctxid, const char* stdCode, WTSTickStruct* newTick) { printf("on_tick\r\n"); } void PORTER_FLAG on_calc(CtxHandler ctxid, WtUInt32 uDate, WtUInt32 uTime) { printf("on_calc\r\n"); } void PORTER_FLAG on_bar(CtxHandler ctxid, const char* code, const char* period, WTSBarStruct* newBar) { printf("on_bar\r\n"); } void PORTER_FLAG on_getbar(CtxHandler ctxid, const char* code, const char* period, WTSBarStruct* bar, bool isLast) { if (bar) printf("on_getbar%I64d\r\n", bar->time); else int x = 1; } void PORTER_FLAG on_getticks(CtxHandler cHandle, const char* code, WTSTickStruct* tick, bool isLast) { printf("on_getticks\r\n"); } void PORTER_FLAG on_event(WtUInt32 evtId, WtUInt32 curDate, WtUInt32 curTime) { printf("on_event\r\n"); } void PORTER_FLAG on_channel_evt(CtxHandler cHandle, const char* trader, WtUInt32 evtid) { printf("on_channel_evt\r\n"); double undone = hft_get_undone(cHandle, "CFFEX.IF.HOT"); } void PORTER_FLAG on_order(CtxHandler cHandle, WtUInt32 localid, const char* stdCode, bool isBuy, double totalQty, double leftQty, double price, bool isCanceled, const char* userTag) { } void PORTER_FLAG on_trade(CtxHandler cHandle, WtUInt32 localid, const char* stdCode, bool isBuy, double vol, double price, const char* userTag) { } void PORTER_FLAG on_entrust(CtxHandler cHandle, WtUInt32 localid, const char* stdCode, bool bSuccess, const char* message, const char* userTag) { } void PORTER_FLAG on_order_queue(CtxHandler cHandle, const char* stdCode, WTSOrdQueStruct* ordQue) { } void PORTER_FLAG on_order_detail(CtxHandler cHandle, const char* stdCode, WTSOrdDtlStruct* ordDtl) { } void PORTER_FLAG on_transaction(CtxHandler cHandle, const char* stdCode, WTSTransStruct* trans) { } void test_porter() { #ifdef _WIN32 DLLHelper::load_library("WtPorter.dll"); #else DLLHelper::load_library("libWtPorter.so"); #endif init_porter("logcfg.json", true, "./generated"); reg_hft_factories("./hft"); config_porter("config.json", true); run_porter(true); printf("press enter key to exit\n"); getchar(); release_porter(); } int main() { test_porter(); getchar(); return 0; }
23.423423
182
0.715
v1otusc
7decb2ab6e29424bf49014c707a3ae60bf42290f
2,402
cpp
C++
arangod/RocksDBEngine/RocksDBBackgroundErrorListener.cpp
Korov/arangodb
d1f8df028f8af60d1cd5708890f0d6ae75f9dd06
[ "Apache-2.0" ]
1
2020-10-27T12:19:33.000Z
2020-10-27T12:19:33.000Z
arangod/RocksDBEngine/RocksDBBackgroundErrorListener.cpp
Korov/arangodb
d1f8df028f8af60d1cd5708890f0d6ae75f9dd06
[ "Apache-2.0" ]
null
null
null
arangod/RocksDBEngine/RocksDBBackgroundErrorListener.cpp
Korov/arangodb
d1f8df028f8af60d1cd5708890f0d6ae75f9dd06
[ "Apache-2.0" ]
1
2020-10-01T08:49:12.000Z
2020-10-01T08:49:12.000Z
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dan Larkin-York //////////////////////////////////////////////////////////////////////////////// #include "RocksDBBackgroundErrorListener.h" #include "Logger/LogMacros.h" #include "Logger/Logger.h" #include "Logger/LoggerStream.h" namespace arangodb { RocksDBBackgroundErrorListener::~RocksDBBackgroundErrorListener() = default; void RocksDBBackgroundErrorListener::OnBackgroundError(rocksdb::BackgroundErrorReason reason, rocksdb::Status* status) { if (status != nullptr && status->IsShutdownInProgress()) { // this is not a relevant error, so let's ignore it return; } if (!_called) { _called = true; std::string operation = "unknown"; switch (reason) { case rocksdb::BackgroundErrorReason::kFlush: { operation = "flush"; break; } case rocksdb::BackgroundErrorReason::kCompaction: { operation = "compaction"; break; } case rocksdb::BackgroundErrorReason::kWriteCallback: { operation = "write callback"; break; } case rocksdb::BackgroundErrorReason::kMemTable: { operation = "memtable"; break; } } LOG_TOPIC("fae2c", ERR, Logger::ROCKSDB) << "RocksDB encountered a background error during a " << operation << " operation: " << (status != nullptr ? status->ToString() : "unknown error") << "; The database will be put in read-only mode, and subsequent write errors are likely"; } } } // namespace arangodb
33.361111
98
0.616986
Korov
7ded15a6131f165f97675f07465255b4d67d5048
2,007
hpp
C++
modules/core/combinatorial/include/nt2/combinatorial/functions/lcm.hpp
feelpp/nt2
4d121e2c7450f24b735d6cff03720f07b4b2146c
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/core/combinatorial/include/nt2/combinatorial/functions/lcm.hpp
feelpp/nt2
4d121e2c7450f24b735d6cff03720f07b4b2146c
[ "BSL-1.0" ]
null
null
null
modules/core/combinatorial/include/nt2/combinatorial/functions/lcm.hpp
feelpp/nt2
4d121e2c7450f24b735d6cff03720f07b4b2146c
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_COMBINATORIAL_FUNCTIONS_LCM_HPP_INCLUDED #define NT2_COMBINATORIAL_FUNCTIONS_LCM_HPP_INCLUDED #include <nt2/include/functor.hpp> namespace nt2 { namespace tag { /*! @brief lcm generic tag Represents the lcm function in generic contexts. @par Models: Hierarchy **/ struct lcm_ : ext::elementwise_<lcm_> { /// @brief Parent hierarchy typedef ext::elementwise_<lcm_> parent; template<class... Args> static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args) BOOST_AUTO_DECLTYPE_BODY( dispatching_lcm_( ext::adl_helper(), static_cast<Args&&>(args)... ) ) }; } namespace ext { template<class Site> BOOST_FORCEINLINE generic_dispatcher<tag::lcm_, Site> dispatching_lcm_(adl_helper, boost::dispatch::meta::unknown_<Site>, ...) { return generic_dispatcher<tag::lcm_, Site>(); } template<class... Args> struct impl_lcm_; } /*! Computes the least common multiple If parameters are floating point and not flint, nan is returned. @par Semantic: For every table expressions @code auto r = lcm(a0,a1); @endcode - If any input is zero 0 is returned - If parameters are floating point and not flint, nan is returned. @see @funcref{gcd}, @funcref{is_flint} @param a0 @param a1 @return an expression which eventually will evaluate to the result **/ NT2_FUNCTION_IMPLEMENTATION(tag::lcm_, lcm, 2) } #endif
27.875
129
0.607872
feelpp
7dedaf628f5693f3e7aed18de73c8d00ddeedc27
3,190
cpp
C++
src/vulkan/vulkan_render.cpp
cmaughan/vklive
649c64335d7d77f4d3199ea8f66c04a53455b4a9
[ "MIT" ]
null
null
null
src/vulkan/vulkan_render.cpp
cmaughan/vklive
649c64335d7d77f4d3199ea8f66c04a53455b4a9
[ "MIT" ]
null
null
null
src/vulkan/vulkan_render.cpp
cmaughan/vklive
649c64335d7d77f4d3199ea8f66c04a53455b4a9
[ "MIT" ]
null
null
null
#include "vklive/vulkan/vulkan_render.h" #include "config_app.h" #include "vklive/file/file.h" #include "vklive/vulkan/vulkan_framebuffer.h" #include "vklive/vulkan/vulkan_model.h" #include "vklive/vulkan/vulkan_pipeline.h" #include "vklive/vulkan/vulkan_shader.h" #include "vklive/vulkan/vulkan_uniform.h" #include "vklive/vulkan/vulkan_utils.h" #include "vklive/vulkan/vulkan_scene.h" namespace vulkan { namespace { // Vertex layout for this example VertexLayout g_vertexLayout{ { Component::VERTEX_COMPONENT_POSITION, Component::VERTEX_COMPONENT_UV, Component::VERTEX_COMPONENT_COLOR, Component::VERTEX_COMPONENT_NORMAL, } }; } // namespace std::shared_ptr<RenderContext> render_context(VulkanContext& ctx) { return std::static_pointer_cast<RenderContext>(ctx.spRenderData); } void render_init(VulkanContext& ctx) { auto spRender = std::make_shared<RenderContext>(); ctx.spRenderData = spRender; } void render_destroy_images(VulkanContext& ctx, RenderContext& renderContext) { for (auto& buffer : renderContext.colorBuffers) { image_destroy(ctx, buffer); } renderContext.colorBuffers.clear(); if (renderContext.depthBuffer.format != vk::Format::eUndefined) { image_destroy(ctx, renderContext.depthBuffer); } } void render_destroy(VulkanContext& ctx) { auto spRender = render_context(ctx); render_destroy_images(ctx, *spRender); ctx.spRenderData = nullptr; } void render_create_images(VulkanContext& ctx, RenderContext& renderContext, const glm::uvec2& size, vk::Format colorFormat, vk::Format depthFormat) { render_destroy_images(ctx, renderContext); renderContext.colorBuffers.resize(1); image_create(ctx, renderContext.colorBuffers[0], size, colorFormat, true, "RenderDefault"); bool useDepth = depthFormat != vk::Format::eUndefined; if (useDepth) { image_create_depth(ctx, renderContext.depthBuffer, size, depthFormat, false, "RenderDefault"); } } void render_check_framebuffer(VulkanContext& ctx, const glm::uvec2& size) { auto spRender = render_context(ctx); if (spRender->frameBufferSize == size) { return; } // Might still be rendering to/with this FB, so wait for it. ctx.device.waitIdle(); // Destroy old spRender->frameBufferSize = size; render_create_images(ctx, *spRender, glm::uvec2(size), vk::Format::eR8G8B8A8Unorm, vk::Format::eD32Sfloat); image_set_sampling(ctx, spRender->colorBuffers[0]); debug_set_descriptorsetlayout_name(ctx.device, spRender->colorBuffers[0].samplerDescriptorSetLayout, "RenderColorBuffer::DescriptorSetLayout"); debug_set_descriptorset_name(ctx.device, spRender->colorBuffers[0].samplerDescriptorSet, "RenderColorBuffer::DescriptorSet"); debug_set_sampler_name(ctx.device, spRender->colorBuffers[0].sampler, "RenderColorBuffer::Sampler"); } void render(VulkanContext& ctx, const glm::vec4& rect, Scene& scene) { auto spRender = render_context(ctx); // Check the framebuffer render_check_framebuffer(ctx, glm::uvec2(rect.z, rect.w)); // Render the scene vulkan::vulkan_scene_render(ctx, *spRender, scene); } } // namespace vulkan
30.380952
147
0.739812
cmaughan
7df0b3aafe209df5e363f70d0ee3c4300b71f6c0
2,835
cc
C++
tests/unit/stall_detector_test.cc
jwnx/seastar
4207837dfbc969e46c0b581e6c3f801dbc8f3a07
[ "Apache-2.0" ]
null
null
null
tests/unit/stall_detector_test.cc
jwnx/seastar
4207837dfbc969e46c0b581e6c3f801dbc8f3a07
[ "Apache-2.0" ]
null
null
null
tests/unit/stall_detector_test.cc
jwnx/seastar
4207837dfbc969e46c0b581e6c3f801dbc8f3a07
[ "Apache-2.0" ]
1
2020-08-10T12:54:33.000Z
2020-08-10T12:54:33.000Z
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2018 ScyllaDB Ltd. */ #include <seastar/core/reactor.hh> #include <seastar/testing/test_case.hh> #include <seastar/testing/thread_test_case.hh> #include <atomic> #include <chrono> using namespace seastar; using namespace std::chrono_literals; class temporary_stall_detector_settings { std::chrono::milliseconds _old_threshold; std::function<void ()> _old_report; public: temporary_stall_detector_settings(std::chrono::duration<double> threshold, std::function<void ()> report) : _old_threshold(engine().get_blocked_reactor_notify_ms()) , _old_report(engine().get_stall_detector_report_function()) { engine().update_blocked_reactor_notify_ms(std::chrono::duration_cast<std::chrono::milliseconds>(threshold)); engine().set_stall_detector_report_function(std::move(report)); } ~temporary_stall_detector_settings() { engine().update_blocked_reactor_notify_ms(_old_threshold); engine().set_stall_detector_report_function(std::move(_old_report)); } }; void spin(std::chrono::duration<double> how_much) { auto end = std::chrono::steady_clock::now() + how_much; while (std::chrono::steady_clock::now() < end) { // spin! } } void spin_some_cooperatively(std::chrono::duration<double> how_much) { auto end = std::chrono::steady_clock::now() + how_much; while (std::chrono::steady_clock::now() < end) { spin(200us); if (need_preempt()) { thread::yield(); } } } SEASTAR_THREAD_TEST_CASE(normal_case) { std::atomic<unsigned> reports{}; temporary_stall_detector_settings tsds(10ms, [&] { ++reports; }); spin_some_cooperatively(1s); BOOST_REQUIRE_EQUAL(reports, 0); } SEASTAR_THREAD_TEST_CASE(simple_stalls) { std::atomic<unsigned> reports{}; temporary_stall_detector_settings tsds(10ms, [&] { ++reports; }); unsigned nr = 10; for (unsigned i = 0; i < nr; ++i) { spin_some_cooperatively(100ms); spin(20ms); } spin_some_cooperatively(100ms); BOOST_REQUIRE_EQUAL(reports, 10); }
33.75
116
0.703351
jwnx
7df2058ba1ee34629e396e88716ad9a0bf07a1a5
3,979
hpp
C++
include/bitpacker/bitpacker.hpp
YarikTH/bitpacker
a778a5ab5eab2cee80beb1819ee7d352775db046
[ "BSL-1.0" ]
null
null
null
include/bitpacker/bitpacker.hpp
YarikTH/bitpacker
a778a5ab5eab2cee80beb1819ee7d352775db046
[ "BSL-1.0" ]
null
null
null
include/bitpacker/bitpacker.hpp
YarikTH/bitpacker
a778a5ab5eab2cee80beb1819ee7d352775db046
[ "BSL-1.0" ]
null
null
null
#pragma once #include <array> #include <bitset> #include <cassert> #if !defined( BITPACKER_USE_STD_BIT ) # define BITPACKER_USE_STD_BIT __has_include( <bit> ) && __cplusplus >= 202002L #endif #if BITPACKER_USE_STD_BIT # include <bit> #endif #define BITPACKER_VERSION_MAJOR 0 #define BITPACKER_VERSION_MINOR 1 #define BITPACKER_VERSION_PATCH 0 #define BITPACKER_VERSION_STR "0.1.0" #define BITPACKER_VERSION \ ( BITPACKER_VERSION_MAJOR * 10000 + BITPACKER_VERSION_MINOR * 100 + BITPACKER_VERSION_PATCH ) namespace bitpacker { #if BITPACKER_USE_STD_BIT using std::bit_width; #else template <class V, std::enable_if_t<std::is_unsigned_v<V>, int> = 0> [[nodiscard]] constexpr V bit_width( const V value ) noexcept { V result = 0u; V temp = value; while( temp != 0u ) { ++result; temp >>= static_cast<V>( 1u ); } return result; } #endif template <class ContainerT> class bit_ostream { public: constexpr explicit bit_ostream( ContainerT& data ) : m_data( data ) {} constexpr bit_ostream& operator<<( const bool value ) { assert( m_offset < m_data.size() ); m_data[m_offset++] = value; return *this; } [[nodiscard]] constexpr size_t offset() const { return m_offset; } private: ContainerT& m_data; size_t m_offset = 0; }; template <class ContainerT> class bit_istream { public: constexpr explicit bit_istream( ContainerT& data ) : m_data( data ) {} constexpr bit_istream& operator>>( bool& value ) { assert( m_offset < m_data.size() ); value = m_data[m_offset++]; return *this; } [[nodiscard]] constexpr size_t offset() const { return m_offset; } private: ContainerT& m_data; size_t m_offset = 0; }; /// Return unsigned difference between two integers /// Left hand side value should be greater or equal than right hand side value template <typename V, class UnsignedV = typename std::make_unsigned<V>::type> [[nodiscard]] constexpr UnsignedV integral_unsigned_difference( const V lhs, const V rhs ) { return static_cast<UnsignedV>( lhs ) - static_cast<UnsignedV>( rhs ); } /// Calculate delta for integral values with given range template <typename V, class UnsignedV = typename std::make_unsigned<V>::type> [[nodiscard]] constexpr UnsignedV integral_delta( const V min_value, const V max_value ) { return integral_unsigned_difference( max_value, min_value ); } /// Calculate delta for integral values without limits template <typename V, class UnsignedV = typename std::make_unsigned<V>::type> [[nodiscard]] constexpr UnsignedV integral_delta() { const auto min_value = std::numeric_limits<V>::min(); const auto max_value = std::numeric_limits<V>::max(); return integral_delta( min_value, max_value ); } // Pack normalized value in range from 0 to delta template <typename V, typename OutputBitStreamT> constexpr void pack_normalized_value( OutputBitStreamT& obstream, const V value, const V delta ) { static_assert( std::is_unsigned_v<V> ); auto temp = value; constexpr auto ONE = static_cast<V>( 1 ); for( size_t i = 0, ie = bit_width( delta ); i < ie; ++i ) { const bool bit = temp & ONE; obstream << bit; temp >>= ONE; } } template <typename V, typename InputBitStreamT> constexpr V unpack_normalized_value( InputBitStreamT& ibstream, const V delta ) { V value{}; constexpr auto ONE = static_cast<V>( 1 ); for( size_t i = 0, ie = bit_width( delta ); i < ie; ++i ) { bool bit{}; ibstream >> bit; if( bit ) { value |= ( ONE << i ); } } return value; } } // namespace bitpacker
25.837662
101
0.627042
YarikTH
7df26e063b76c4063de18842b4922826bd4706a0
14,125
cpp
C++
src/mme-app/utils/mmeCommonUtils.cpp
dksan23/Nucleus
0377bee9cacebe352caba9d9cf76dcc9af9e69bf
[ "Apache-2.0" ]
null
null
null
src/mme-app/utils/mmeCommonUtils.cpp
dksan23/Nucleus
0377bee9cacebe352caba9d9cf76dcc9af9e69bf
[ "Apache-2.0" ]
1
2021-05-12T09:17:31.000Z
2021-05-12T09:17:31.000Z
src/mme-app/utils/mmeCommonUtils.cpp
dksan23/Nucleus
0377bee9cacebe352caba9d9cf76dcc9af9e69bf
[ "Apache-2.0" ]
6
2021-05-06T11:18:55.000Z
2021-05-12T13:13:21.000Z
/* * Copyright (c) 2019, Infosys Ltd. * * SPDX-License-Identifier: Apache-2.0 */ #include <utils/mmeCommonUtils.h> #include <cmath> #include <controlBlock.h> #include <contextManager/dataBlocks.h> #include <contextManager/subsDataGroupManager.h> #include <log.h> #include <mme_app.h> #include <msgBuffer.h> #include <s1ap_structs.h> #include <utils/defaultMmeProcedureCtxt.h> #include <random> using namespace mme; extern mme_config_t *mme_cfg; bool MmeCommonUtils::isLocalGuti(const guti &guti_r) { bool rc = false; if (guti_r.mme_grp_id == mme_cfg->mme_group_id && guti_r.mme_code == mme_cfg->mme_code) { rc = true; } return rc; } #ifdef S10_FEATURE bool MmeCommonUtils::compare_plmn_id(const struct PLMN *plmn) { bool rc = false; //need to check whether this comparison will work or not, else need to decode idx to mcc and mnc int config_plmn; for(config_plmn = 0; config_plmn < mme_cfg->num_plmns; config_plmn++) { if((mme_cfg->plmns[config_plmn].idx[0] == plmn->idx[0]) && (mme_cfg->plmns[config_plmn].idx[1] == plmn->idx[1]) && (mme_cfg->plmns[config_plmn].idx[2] == plmn->idx[2]) && (mme_cfg->plmns[config_plmn].mnc_digits == plmn->mnc_digits)) rc = true; } return rc; } bool MmeCommonUtils::compare_tac(const uint16_t tac) { bool rc = false; int i = 0; /*for(i = 0; i < mme_cfg->num_tai; i++) { if(mme_cfg->served_tai.tac[i] == tac) rc = true; }*/ return rc; } bool MmeCommonUtils::isLocalTAI(const struct PLMN *plmn, const short target_tac) { bool rc = false; if(true == compare_plmn_id(plmn)) { if(true == compare_tac(target_tac)) { log_msg(LOG_DEBUG, "TAC and PLMN are matching"); rc = true; } } log_msg(LOG_DEBUG, "TAC and PLMN are not matching"); return rc; } void MmeCommonUtils::select_neighboring_mme(const struct TAI *tai, int *service_ip_addr) { //*service_ip_addr = mme_cfg->target_mme_ip; return; } #endif uint8_t MmeCommonUtils::select_preferred_int_algo(uint8_t &val) { uint8_t result = 0; for(int i = 0; i < MAX_ALGO_COUNT; i++) { if (val & (0x80 >> mme_cfg->integrity_alg_order[i])) { result = mme_cfg->integrity_alg_order[i]; break; } } return result; } uint8_t MmeCommonUtils::select_preferred_sec_algo(uint8_t &val) { uint8_t result = 0; for(int i = 0; i < MAX_ALGO_COUNT; i++) { if (val & (0x80 >> mme_cfg->ciphering_alg_order[i])) { result = mme_cfg->ciphering_alg_order[i]; break; } } return result; } uint32_t MmeCommonUtils::allocateMtmsi() { uint32_t tmsi = 0; std::default_random_engine generator(time(NULL)); std::uniform_int_distribution<int> temp_fun(0, 1000000); while(1) { tmsi = temp_fun(generator); if (SubsDataGroupManager::Instance()->findCBWithmTmsi(tmsi) == -1) break; } log_msg(LOG_INFO, "MTMSI allocated is %u", tmsi); return tmsi; } void MmeCommonUtils::formatS1apPlmnId(struct PLMN* plmn_p) { /* Lets update plmnId .... What we received from s1ap is : 214365 and what we need on * s6a/s11/nas interfaces is - 216354*/ unsigned char plmn_byte2 = plmn_p->idx[1]; unsigned char plmn_byte3 = plmn_p->idx[2]; unsigned char mnc3 = plmn_byte3 >> 4; // mnc3 unsigned char mnc2 = plmn_byte3 & 0xf; // mnc2 unsigned char mnc1 = plmn_byte2 >> 4; // mnc1 unsigned char mcc3 = plmn_byte2 & 0xf; //mcc3 // First byte we are not changing mcc2 mcc1 if(mnc1 != 0x0F) { plmn_byte2 = (mnc3 << 4) | mcc3; // 2nd byte on NAS - mnc3 mcc3 plmn_byte3 = (mnc2 << 4) | mnc1; // 3rd byte on NAS - <mnc2 mnc1> plmn_p->idx[1] = plmn_byte2; plmn_p->idx[2] = plmn_byte3; } } void MmeCommonUtils::getS1apPlmnIdFroms11(struct PLMN* plmn_p) { /* we have on s11/nas/s6a - 216354 */ /* s1ap need : 214365 */ unsigned char plmn_byte2 = plmn_p->idx[1]; unsigned char plmn_byte3 = plmn_p->idx[2]; unsigned char mnc3 = plmn_byte2 >> 4; // mnc3 unsigned char mnc2 = plmn_byte3 >> 4; // mnc2 unsigned char mnc1 = plmn_byte3 & 0xf; // mnc1 unsigned char mcc3 = plmn_byte2 & 0xf; //mcc3 // First byte we are not changing mcc2 mcc1 if(mnc1 != 0x0F) { plmn_byte2 = (mnc1 << 4) | mcc3; plmn_byte3 = (mnc3 << 4) | mnc2; plmn_p->idx[1] = plmn_byte2; plmn_p->idx[2] = plmn_byte3; } } AttachType MmeCommonUtils::getAttachType(UEContext* ueContext_p, const struct ue_attach_info& ue_info) { log_msg(LOG_INFO, "deriveAttachType"); AttachType attachType = maxAttachType_c; if(UE_ID_IMSI(ue_info.flags)) { log_msg(LOG_INFO, "IMSI attach received."); attachType = imsiAttach_c; } else if (UE_ID_GUTI(ue_info.flags)) { log_msg(LOG_INFO, "GUTI attach received. mTMSI is %u ", ue_info.mi_guti.m_TMSI); attachType = unknownGutiAttach_c; if (isLocalGuti(ue_info.mi_guti)) { // The guti is allocated by this MME, check if a context exists. // If the context does not exist, treat as unknown GUTI attach? log_msg(LOG_INFO, "GUTI is local.."); if (ueContext_p != NULL) { if (ueContext_p->getMTmsi() == ue_info.mi_guti.m_TMSI) { log_msg(LOG_INFO, "and known"); attachType = knownGutiAttach_c; } else { log_msg(LOG_INFO, "mTMSI mismatches with UE context. " "Treat as unknown GUTI attach"); } } else { log_msg(LOG_INFO, "UE context is null. Unknown GUTI attach triggered"); } } else { log_msg(LOG_INFO, "GUTI is not local.."); } } return attachType; } SM::ControlBlock* MmeCommonUtils::findControlBlock(cmn::utils::MsgBuffer* buf) { SM::ControlBlock *cb = NULL; const s1_incoming_msg_header_t* msgData_p = (s1_incoming_msg_header_t*)(buf->getDataPointer()); if(msgData_p == NULL) { log_msg(LOG_INFO, "MsgData is NULL ."); return cb; } switch (msgData_p->msg_type) { case attach_request: { const ue_attach_info_t *ue_info = (ue_attach_info_t *)(msgData_p); if(UE_ID_IMSI(ue_info->flags)) { log_msg(LOG_INFO, "IMSI attach received."); uint8_t imsi[BINARY_IMSI_LEN] = {0}; memcpy( imsi, ue_info->IMSI, BINARY_IMSI_LEN ); uint8_t first = imsi[0] >> 4; imsi[0] = (uint8_t)(( first << 4 ) | 0x0f ); DigitRegister15 IMSIInfo; IMSIInfo.convertFromBcdArray(imsi); int cbIndex = SubsDataGroupManager::Instance()->findCBWithimsi(IMSIInfo); if (cbIndex > 0) { log_msg(LOG_DEBUG, "existing cb for IMSI. %s ",IMSIInfo.getDigitsArray()); cb = SubsDataGroupManager::Instance()->findControlBlock(cbIndex); } if (cb == NULL) { log_msg(LOG_INFO, "create new cb for IMSI %s.", IMSIInfo.getDigitsArray()); cb = SubsDataGroupManager::Instance()->allocateCB(); if(cb == NULL) { log_msg(LOG_DEBUG, "create new cb for IMSI failed. %s ",IMSIInfo.getDigitsArray()); return nullptr; } cb->addTempDataBlock(DefaultMmeProcedureCtxt::Instance()); } } else if (UE_ID_GUTI(ue_info->flags)) { log_msg(LOG_INFO, "GUTI attach received."); if (isLocalGuti(ue_info->mi_guti)) { log_msg(LOG_INFO, "GUTI is local."); int cbIndex = SubsDataGroupManager::Instance()->findCBWithmTmsi(ue_info->mi_guti.m_TMSI); if (cbIndex > 0) { cb = SubsDataGroupManager::Instance()->findControlBlock(cbIndex); } else { log_msg(LOG_ERROR, "Failed to find control block with mTmsi."); // allocate new cb and proceed? cb = SubsDataGroupManager::Instance()->allocateCB(); cb->addTempDataBlock(DefaultMmeProcedureCtxt::Instance()); } } else { cb = SubsDataGroupManager::Instance()->allocateCB(); cb->addTempDataBlock(DefaultMmeProcedureCtxt::Instance()); } } break; } case service_request: { int cbIndex = SubsDataGroupManager::Instance()->findCBWithmTmsi(msgData_p->ue_idx); if (cbIndex > 0) { cb = SubsDataGroupManager::Instance()->findControlBlock(cbIndex); } else { log_msg(LOG_INFO, "Failed to find control block with mTmsi."); } if (cb == NULL) { log_msg(LOG_INFO, "Failed to find control block using mtmsi %d." " Allocate a temporary control block", msgData_p->ue_idx); // Respond with Service Reject from default Service Request event handler cb = SubsDataGroupManager::Instance()->allocateCB(); cb->addTempDataBlock(DefaultMmeProcedureCtxt::Instance()); } break; } case detach_request: { const detach_req_Q_msg_t *detach_Req = (const detach_req_Q_msg_t *)(msgData_p); int cbIndex = SubsDataGroupManager::Instance()->findCBWithmTmsi(detach_Req->ue_m_tmsi); if (cbIndex > 0) { cb = SubsDataGroupManager::Instance()->findControlBlock(cbIndex); } else { log_msg(LOG_INFO, "Failed to find control block with mTmsi. %d", detach_Req->ue_m_tmsi); } break; } case tau_request: { const tauReq_Q_msg_t *tau_Req = (const tauReq_Q_msg_t *)(msgData_p); int cbIndex = SubsDataGroupManager::Instance()->findCBWithmTmsi(tau_Req->ue_m_tmsi); if (cbIndex > 0) { cb = SubsDataGroupManager::Instance()->findControlBlock(cbIndex); } else { log_msg(LOG_INFO, "Failed to find control block using mTmsi %d." " Allocate a temporary control block", tau_Req->ue_m_tmsi); // Respond with TAU Reject from default TAU event handler cb = SubsDataGroupManager::Instance()->allocateCB(); cb->addTempDataBlock(DefaultMmeProcedureCtxt::Instance()); } break; } default: { log_msg(LOG_INFO, "Unhandled message type %d ", msgData_p->msg_type); } } return cb; } ControlBlock* MmeCommonUtils::findControlBlockForS11Msg(cmn::utils::MsgBuffer* msg_p) { ControlBlock* cb_p = NULL; const gtp_incoming_msg_data_t* msgData_p = (gtp_incoming_msg_data_t*)(msg_p->getDataPointer()); if(msgData_p == NULL) { log_msg(LOG_INFO, "GTP message data is NULL ."); return cb_p; } switch (msgData_p->msg_type) { case downlink_data_notification: { const struct ddn_Q_msg* ddn = (const struct ddn_Q_msg*) (msg_p->getDataPointer()); if (ddn->s11_mme_cp_teid == 0) { log_msg(LOG_INFO, "UE Index in DDN message data is 0."); return cb_p; } cb_p = SubsDataGroupManager::Instance()->findControlBlock(ddn->s11_mme_cp_teid); if (cb_p == NULL) { log_msg(LOG_INFO, "Failed to find control block using index %d." " Allocate a temporary control block", ddn->s11_mme_cp_teid); // Respond with DDN failure from default DDN event handler cb_p = SubsDataGroupManager::Instance()->allocateCB(); cb_p->addTempDataBlock(DefaultMmeProcedureCtxt::Instance()); } }break; case create_bearer_request: { const struct cb_req_Q_msg * cbr = (const struct cb_req_Q_msg *) (msg_p->getDataPointer()); if (cbr->s11_mme_cp_teid == 0) { log_msg(LOG_INFO, "UE Index in CB Req message data is 0."); return cb_p; } cb_p = SubsDataGroupManager::Instance()->findControlBlock(cbr->s11_mme_cp_teid); if (cb_p == NULL) { log_msg(LOG_INFO, "Failed to find control block using index %d." " Allocate a temporary control block", cbr->s11_mme_cp_teid); // Respond with CB Resp from default CB Req event handler cb_p = SubsDataGroupManager::Instance()->allocateCB(); cb_p->addTempDataBlock(DefaultMmeProcedureCtxt::Instance()); } }break; case delete_bearer_request: { const struct db_req_Q_msg * dbr = (const struct db_req_Q_msg *) (msg_p->getDataPointer()); if (dbr->s11_mme_cp_teid == 0) { log_msg(LOG_INFO, "UE Index in DB Req message data is 0."); return cb_p; } cb_p = SubsDataGroupManager::Instance()->findControlBlock(dbr->s11_mme_cp_teid); if (cb_p == NULL) { log_msg(LOG_INFO, "Failed to find control block using index %d." " Allocate a temporary control block", dbr->s11_mme_cp_teid); // Respond with DB Resp from default DB Req event handler cb_p = SubsDataGroupManager::Instance()->allocateCB(); cb_p->addTempDataBlock(DefaultMmeProcedureCtxt::Instance()); } }break; default: { log_msg(LOG_INFO, "Unhandled message type"); } } return cb_p; } bool MmeCommonUtils::isEmmInfoRequired(ControlBlock& cb, UEContext& ueCtxt, MmeProcedureCtxt& procCtxt) { bool rc = false; if (procCtxt.getCtxtType() == attach_c) { MmeAttachProcedureCtxt& attachCtxt = dynamic_cast<MmeAttachProcedureCtxt &>(procCtxt); if (attachCtxt.getAttachType() == imsiAttach_c) { rc = true; } } return rc; } bool MmeCommonUtils::isUeNRCapable(UEContext &ueCtxt) { bool rc; if (!ueCtxt.getUeNetCapab().ue_net_capab_m.u.bits.dcnr) { log_msg(LOG_DEBUG, "UE does not support dual connectivity"); rc = false; } else if (!mme_cfg->feature_list.dcnr_support) { log_msg(LOG_DEBUG,"MME local config does not allow dual connectivity"); rc = false; } else if (!(ueCtxt.getHssFeatList2().feature_list & nrAsSecRatBitMask_c)) { log_msg(LOG_DEBUG,"HSS does not support dual connectivity feature"); rc = false; } else if (ueCtxt.getAccessRestrictionData() & nrAsSecRatInEutranNotAllowedBitMask_c) { log_msg(LOG_DEBUG,"hss informed about access restriction for this UE"); rc = false; } else { log_msg(LOG_DEBUG,"All well, this UE can use DCNR"); rc = true; } return rc; }
28.193613
105
0.632212
dksan23
7df37ff7b62b2e446ee6b4b53d8b3d57b05d880c
695
cpp
C++
112-path-sum/112-path-sum.cpp
SouvikChan/-Leetcode_Souvik
cc4b72cb4a14a1c6b8be8bd8390de047443fe008
[ "MIT" ]
null
null
null
112-path-sum/112-path-sum.cpp
SouvikChan/-Leetcode_Souvik
cc4b72cb4a14a1c6b8be8bd8390de047443fe008
[ "MIT" ]
null
null
null
112-path-sum/112-path-sum.cpp
SouvikChan/-Leetcode_Souvik
cc4b72cb4a14a1c6b8be8bd8390de047443fe008
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool hasPathSum(TreeNode* root, int targetSum) { if(root==NULL) return false; if(root->left==NULL and root->right==NULL) return (targetSum-root->val)==0; return hasPathSum(root->left, targetSum-root->val) || hasPathSum(root->right,targetSum-root->val); } };
33.095238
106
0.592806
SouvikChan
7df3ff31a0f12af5f99989e23e969a1563996568
2,319
cpp
C++
FW/SC/scene.cpp
JAntn/wblocks
e8aa383882b4726f6f7cca7213fa49e9e80d990f
[ "MIT" ]
null
null
null
FW/SC/scene.cpp
JAntn/wblocks
e8aa383882b4726f6f7cca7213fa49e9e80d990f
[ "MIT" ]
null
null
null
FW/SC/scene.cpp
JAntn/wblocks
e8aa383882b4726f6f7cca7213fa49e9e80d990f
[ "MIT" ]
null
null
null
#include "FW/SC/scene.h" #include "FW/tools.h" #include "FW/ST/state_writer.h" #include "FW/RC/record.h" #include "FW/SC/scene_line.h" //////////////////////////////////////////////////////////////////////// /// Static long TypeScene::m_IdCount = 0; QString TypeScene::GenerateId() { return QString().setNum( m_IdCount++ ); } QString TypeScene::IdCount() { return QString().setNum( m_IdCount ); } //////////////////////////////////////////////////////////////////////// TypeScene::TypeScene( TypeController& controller, TypeVariant* parent ) : TypeVariant( parent ), m_Controller( &controller ), m_TopZ( 0 ) { m_Graphics = new QGraphicsScene(); } TypeScene::~TypeScene() { delete m_Graphics; } TypeSceneItem* TypeScene::NewItem( TypeStateWriter& state ) { return new TypeSceneItem( *this, state ); } TypeSceneItem* TypeScene::NewItem( TypeRecord& record ) { return new TypeSceneItem( *this, record, 100 + ( qrand() % 40 - 80 ), 100 + ( qrand() % 40 - 80 ) ); } TypeSceneItem* TypeScene::NewItem( TypeRecord& record, qreal x, qreal y, qreal z ) { return new TypeSceneItem( *this, record, x, y, z ); } QList<TypeSceneItem*> TypeScene::FromRecord( TypeRecord& record ) const { QList<TypeSceneItem*> result; for( TypeSceneItem* item : Items() ) { if( & item->Record() == & record ) result.append( item ); } return result; } void TypeScene::Clear() { Graphics().clear(); } int TypeScene::Size() { return Items().size(); } void TypeScene::BringFront( TypeSceneItem& item ) { m_TopZ += 0.01; item.setZValue( m_TopZ ); } void TypeScene::UpdateView() { // Update lines ClearLines(); for( TypeSceneItem* from : Items() ) { if( from->Record().Struct() != 0 ) { for( TypeVariantPtr<TypeRecord> record : *from->Record().Struct() ) { for( TypeSceneItem* target : Items() ) { TypeRecord* record_target = &target->Record(); if( record == record_target ) m_Lines.append( new TypeSceneLine( *from, *target, Qt::blue ) ); } } } } } void TypeScene::ClearLines() { for( TypeSceneLine* line : Lines() ) delete line; }
20.705357
104
0.552393
JAntn
7df5be715159b1976cc0082ac8515bb247bfee33
1,766
cpp
C++
ngraph/frontend/onnx_import/src/utils/provenance_tag.cpp
NikDemoShow/openvino
31907e51e96f1603753dc69811bdf738374ca5e6
[ "Apache-2.0" ]
1
2022-02-10T08:05:09.000Z
2022-02-10T08:05:09.000Z
ngraph/frontend/onnx_import/src/utils/provenance_tag.cpp
NikDemoShow/openvino
31907e51e96f1603753dc69811bdf738374ca5e6
[ "Apache-2.0" ]
105
2020-06-04T00:23:29.000Z
2022-02-21T13:04:33.000Z
ngraph/frontend/onnx/frontend/src/utils/provenance_tag.cpp
v-Golubev/openvino
26936d1fbb025c503ee43fe74593ee9d7862ab15
[ "Apache-2.0" ]
3
2021-04-25T06:52:41.000Z
2021-05-07T02:01:44.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <functional> #include <numeric> #include <sstream> #include "utils/provenance_tag.hpp" namespace ngraph { namespace onnx_import { namespace detail { std::string concat_strings( const std::vector<std::reference_wrapper<const std::string>>& strings) { const auto concat_with_comma = [](const std::string& accumulator, std::reference_wrapper<const std::string> next_string) { return accumulator + ", " + next_string.get(); }; return std::accumulate( strings.begin() + 1, strings.end(), strings.begin()->get(), concat_with_comma); } std::string build_input_provenance_tag(const std::string& input_name, const PartialShape& shape) { std::stringstream tag_builder; tag_builder << "<ONNX Input (" << input_name << ") Shape:" << shape << ">"; return tag_builder.str(); } std::string build_op_provenance_tag(const Node& onnx_node) { const auto output_names = concat_strings(onnx_node.get_output_names()); const auto node_name = onnx_node.get_name().empty() ? "" : onnx_node.get_name() + " "; return std::string{"<ONNX " + onnx_node.op_type() + " (" + node_name + "-> " + output_names + ")>"}; } } // namespace detail } // namespace onnx_import } // namespace ngraph
34.627451
99
0.513024
NikDemoShow
7df68ea30a4435e95cf9e77cff8e5af224d508e6
619
cpp
C++
AlgorithmsLibrary/ Non-modifying sequence operations/find_if_find_if_not_find/find_if_find_if_not_if.cpp
paulkokos/CppReference
dd62c7f34bae129930b61b636e60863b946aa4dc
[ "MIT" ]
1
2020-07-07T08:14:46.000Z
2020-07-07T08:14:46.000Z
AlgorithmsLibrary/ Non-modifying sequence operations/find_if_find_if_not_find/find_if_find_if_not_if.cpp
paulkokos/CppReference
dd62c7f34bae129930b61b636e60863b946aa4dc
[ "MIT" ]
null
null
null
AlgorithmsLibrary/ Non-modifying sequence operations/find_if_find_if_not_find/find_if_find_if_not_if.cpp
paulkokos/CppReference
dd62c7f34bae129930b61b636e60863b946aa4dc
[ "MIT" ]
1
2019-01-17T14:32:46.000Z
2019-01-17T14:32:46.000Z
#include <iostream> #include <algorithm> #include <vector> #include <iterator> int main() { int n1 = 3; int n2 = 5; std::vector<int> v{0, 1, 2, 3, 4}; auto result1 = std::find(std::begin(v), std::end(v), n1); auto result2 = std::find(std::begin(v), std::end(v), n2); if (result1 != std::end(v)) { std::cout << "v contains: " << n1 << '\n'; } else { std::cout << "v does not contain: " << n1 << '\n'; } if (result2 != std::end(v)) { std::cout << "v contains: " << n2 << '\n'; } else { std::cout << "v does not contain: " << n2 << '\n'; } }
22.925926
61
0.478191
paulkokos
7df766eedc0152e169e8416896437132f2ae0bdc
16,057
cpp
C++
hphp/runtime/vm/unwind.cpp
Atry/hhvm
f195d3d81b52586d9b9fa2f17c05fe1bb68bcc3e
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/runtime/vm/unwind.cpp
Atry/hhvm
f195d3d81b52586d9b9fa2f17c05fe1bb68bcc3e
[ "PHP-3.01", "Zend-2.0" ]
3
2022-02-17T04:00:03.000Z
2022-03-24T03:45:33.000Z
hphp/runtime/vm/unwind.cpp
Atry/hhvm
f195d3d81b52586d9b9fa2f17c05fe1bb68bcc3e
[ "PHP-3.01", "Zend-2.0" ]
1
2022-02-19T09:29:50.000Z
2022-02-19T09:29:50.000Z
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/vm/unwind.h" #include <boost/implicit_cast.hpp> #include <folly/ScopeGuard.h> #include "hphp/util/trace.h" #include "hphp/runtime/base/tv-refcount.h" #include "hphp/runtime/ext/asio/ext_async-function-wait-handle.h" #include "hphp/runtime/ext/asio/ext_async-generator-wait-handle.h" #include "hphp/runtime/ext/asio/ext_async-generator.h" #include "hphp/runtime/ext/asio/ext_static-wait-handle.h" #include "hphp/runtime/ext/generator/ext_generator.h" #include "hphp/runtime/vm/bytecode.h" #include "hphp/runtime/vm/debugger-hook.h" #include "hphp/runtime/vm/func.h" #include "hphp/runtime/vm/hhbc.h" #include "hphp/runtime/vm/hhbc-codec.h" #include "hphp/runtime/vm/resumable.h" #include "hphp/runtime/vm/runtime.h" #include "hphp/runtime/vm/unit.h" #include "hphp/runtime/vm/vm-regs.h" #include "hphp/runtime/vm/jit/unwind-itanium.h" namespace HPHP { TRACE_SET_MOD(unwind); using boost::implicit_cast; namespace { ////////////////////////////////////////////////////////////////////// #if (!defined(NDEBUG) || defined(USE_TRACE)) std::string describeEx(Either<ObjectData*, Exception*> exception) { if (exception.left()) { return folly::format("[user exception] {}", implicit_cast<void*>(exception.left())).str(); } return folly::format("[C++ exception] {}", implicit_cast<void*>(exception.right())).str(); } #endif void discardStackTemps(const ActRec* const fp, Stack& stack) { ITRACE(2, "discardStackTemps with fp {} sp {}\n", implicit_cast<const void*>(fp), implicit_cast<void*>(stack.top())); visitStackElems( fp, stack.top(), [&] (TypedValue* tv) { assertx(tv == stack.top()); ITRACE(2, " unwind pop TV : {}\n", implicit_cast<void*>(stack.top())); stack.popTV(); } ); ITRACE(2, "discardStackTemps ends with sp = {}\n", implicit_cast<void*>(stack.top())); } /** * Discard the current frame, assuming that a PHP exception given in * phpException argument, or C++ exception (phpException == nullptr) * is being thrown. Returns an exception to propagate, or nulltpr * if the VM execution should be resumed. */ ObjectData* tearDownFrame(ActRec*& fp, Stack& stack, PC& pc, ObjectData* phpException, bool jit, bool teardownStack) { auto const func = fp->func(); auto const prevFp = fp->sfp(); auto const callOff = fp->callOffset(); ITRACE(1, "tearDownFrame: {} ({})\n", func->fullName()->data(), func->unit()->filepath()->data()); ITRACE(1, " fp {}, prevFp {}, jit {}\n", implicit_cast<void*>(fp), implicit_cast<void*>(prevFp), jit); auto const decRefLocals = [&] { /* * It is possible that locals have already been decref'd. * * Here's why: * * - If a destructor for any of these things throws a php * exception, it's swallowed at the dtor boundary and we keep * running php. * * - If the destructor for any of these things throws a fatal, * it's swallowed, and we set surprise flags to throw a fatal * from now on. * * - If the second case happened and we have to run another * destructor, its enter hook will throw, but it will be * swallowed again. * * - Finally, the exit hook for the returning function can * throw, but this happens last so everything is destructed. * * - When that happens, exit hook sets localsDecRefd flag. */ if (fp->localsDecRefd()) return false; fp->setLocalsDecRefd(); try { if (teardownStack) { frame_free_locals_helper_inl(fp, func->numLocals()); if (fp->func()->cls() && fp->hasThis()) decRefObj(fp->getThis()); fp->trashThis(); } EventHook::FunctionUnwind(fp, phpException); } catch (...) {} return true; }; if (LIKELY(!isResumed(fp))) { auto const decRefd = decRefLocals(); if (UNLIKELY(func->isAsyncFunction()) && decRefd && phpException && (!fp->isAsyncEagerReturn() || func->isMemoizeImpl())) { // If in an eagerly executed async function without request for async // eager return, wrap the user exception into a failed StaticWaitHandle // and return it to the caller. auto const waitHandle = c_StaticWaitHandle::CreateFailed(phpException); phpException = nullptr; stack.ndiscard(func->numSlotsInFrame()); if (jit) { jit::g_unwind_rds->fswh = waitHandle; // Don't trash the ActRec since service-request-handlers might not need // to read the call offset and func pointer stack.retNoTrash(); } else { stack.ret(); assertx(stack.topTV() == fp->retSlot()); tvCopy(make_tv<KindOfObject>(waitHandle), *fp->retSlot()); fp->retSlot()->m_aux.u_asyncEagerReturnFlag = 0; } } else { // Free ActRec. stack.ndiscard(func->numSlotsInFrame()); stack.discardAR(); // JIT may have optimized away NullUninit writes over the space reserved // for inout outputs, so we need to discard them. stack.ndiscard(func->numInOutParams()); } } else if (func->isAsyncFunction()) { auto const waitHandle = frame_afwh(fp); if (phpException) { // Handle exception thrown by async function. decRefLocals(); waitHandle->fail(phpException); decRefObj(waitHandle); phpException = nullptr; if (jit) jit::g_unwind_rds->fswh = nullptr; } else if (waitHandle->isRunning()) { // Let the C++ exception propagate. If the current frame represents async // function that is running, mark it as abruptly interrupted. Some opcodes // like Await may change state of the async function just before exit hook // decides to throw C++ exception. decRefLocals(); waitHandle->failCpp(); decRefObj(waitHandle); } } else if (func->isAsyncGenerator()) { auto const gen = frame_async_generator(fp); if (phpException) { // Handle exception thrown by async generator. decRefLocals(); auto eagerResult = gen->fail(phpException); phpException = nullptr; if (eagerResult) { if (jit) { jit::g_unwind_rds->fswh = eagerResult; // Allocate space on the stack for the eagerResult to be written later // SP needs to be consistent between interp and jit stack.top()--; } else { stack.pushObjectNoRc(eagerResult); } } else { if (jit) jit::g_unwind_rds->fswh = nullptr; } } else if (gen->isEagerlyExecuted() || gen->getWaitHandle()->isRunning()) { // Fail the async generator and let the C++ exception propagate. decRefLocals(); gen->failCpp(); } } else if (func->isNonAsyncGenerator()) { // Mark the generator as finished. decRefLocals(); frame_generator(fp)->fail(); } else { not_reached(); } /* * At the final ActRec in this nesting level. */ if (UNLIKELY(!prevFp)) { pc = nullptr; fp = nullptr; return phpException; } assertx(stack.isValidAddress(reinterpret_cast<uintptr_t>(prevFp)) || isResumed(prevFp)); pc = prevFp->func()->at(callOff); assertx(prevFp->func()->contains(pc)); fp = prevFp; return phpException; } const StaticString s_previous("previous"); const Slot s_previousIdx{6}; DEBUG_ONLY bool is_throwable(ObjectData* throwable) { auto const erCls = SystemLib::s_ErrorClass; auto const exCls = SystemLib::s_ExceptionClass; return throwable->instanceof(erCls) || throwable->instanceof(exCls); } DEBUG_ONLY bool throwable_has_expected_props() { auto const erCls = SystemLib::s_ErrorClass; auto const exCls = SystemLib::s_ExceptionClass; if (erCls->lookupDeclProp(s_previous.get()) != s_previousIdx || exCls->lookupDeclProp(s_previous.get()) != s_previousIdx) { return false; } // Check that we have the expected type-hints on these props so we don't need // to verify anything when setting. If someone changes the type-hint we want // to know. auto const isException = [&](const TypeConstraint& tc) { if (!tc.isUnresolved() && !tc.isObject()) return false; auto const cls = Class::lookup(tc.anyNamedEntity()); return cls && cls == SystemLib::s_ExceptionClass; }; return isException(erCls->declPropTypeConstraint(s_previousIdx)) && isException(exCls->declPropTypeConstraint(s_previousIdx)); } const StaticString s_hphpd_break("hphpd_break"); ////////////////////////////////////////////////////////////////////// } Offset findCatchHandler(const Func* func, Offset raiseOffset) { auto const eh = func->findEH(raiseOffset); if (eh == nullptr) return kInvalidOffset; return eh->m_handler; } void chainFaultObjects(ObjectData* top, ObjectData* prev) { assertx(throwable_has_expected_props()); // We don't chain the fault objects if there is a cycle in top, prev, or the // resulting chained fault object. std::unordered_set<uintptr_t> seen; // Walk head's previous pointers untill we find an unset one, or determine // they form a cycle. auto findAcyclicPrev = [&](ObjectData* head) { tv_lval foundLval; do { assertx(is_throwable(head)); if (!seen.emplace((uintptr_t)head).second) return tv_lval(); foundLval = head->propLvalAtOffset(s_previousIdx); assertx(foundLval.type() != KindOfUninit); head = foundLval.val().pobj; } while (foundLval.type() == KindOfObject && foundLval.val().pobj->instanceof(SystemLib::s_ThrowableClass)); return foundLval; }; auto const prevLval = findAcyclicPrev(top); if (!prevLval || !findAcyclicPrev(prev)) { decRefObj(prev); return; } // Found an unset previous pointer, and result will not have a cycle so chain // the fault objects. tvMove(make_tv<KindOfObject>(prev), prevLval); } void lockObjectWhileUnwinding(PC pc, Stack& stack) { auto const op = decode_op(pc); if (LIKELY(op != OpFCallCtor)) return; auto fca = decodeFCallArgs(op, pc, nullptr /* StringDecoder */); if (!fca.lockWhileUnwinding()) return; // We just unwound from a constructor that was called from a new expression // (as opposed to via e.g. parent::__construct()). The object being // constructed is on the top of the stack, and needs to be locked. auto const obj = stack.top(); assertx(tvIsObject(obj)); ITRACE(2, "Locking object {}\n", obj); obj->m_data.pobj->lockObject(); } /* * Unwinding proceeds as follows: * * - Discard all evaluation stack temporaries. * * - Check if we are handling user exception in an eagerly executed * async function. If so, pop its frame, wrap the exception into * failed StaticWaitHandle object, leave it on the stack as * a return value from the async function and resume VM. * * - Failing any of the above, pop the frame for the current * function. If the current function was the last frame in the * current VM nesting level, rethrow the exception, otherwise go * to the first step and repeat this process in the caller's * frame. * * If a non nullptr fpToUnwind is given, the unwinder will not unwind past * fpToUnwind, instead return when vmfp() is equal to fpToUnwind. * * The return value UnwinderResult indicates whether we ended unwinding due to * reaching fpToUnwind as well as whether we ended with putting a failed * static wait handle on the stack. */ UnwinderResult unwindVM(Either<ObjectData*, Exception*> exception, const ActRec* fpToUnwind /* = nullptr */, bool teardown /* = true */) { assertx(!exception.isNull()); auto phpException = exception.left(); if (phpException) phpException->incRefCount(); auto& fp = vmfp(); auto& stack = vmStack(); auto& pc = vmpc(); ITRACE(1, "entering unwinder for exception: {}\n", describeEx(exception)); SCOPE_EXIT { ITRACE(1, "leaving unwinder for exception: {}\n", describeEx(exception)); }; while (true) { auto const func = fp->func(); ITRACE(1, "unwind: func {}, raiseOffset {}, fp {}, sp {}, teardown {}\n", func->name()->data(), func->offsetOf(pc), implicit_cast<void*>(fp), implicit_cast<void*>(stack.top()), teardown); ITRACE(3, "Stack top: {}, stack base: {}\n", stack.top(), Stack::anyFrameStackBase(fp)); if (teardown) discardStackTemps(fp, stack); // Jitted teardown should have decreffed all the stack elements in the // middle assertx(stack.top() == Stack::anyFrameStackBase(fp)); // Note: we skip catch/finally clauses if we have a pending C++ // exception as part of our efforts to avoid running more PHP // code in the face of such exceptions. Similarly, if the frame // has already been torn down (eg an exception thrown by a user // profiler on function exit), we can't execute any handlers in // *this* frame. if (RequestInfo::s_requestInfo->m_pendingException == nullptr && phpException && !UNLIKELY(fp->localsDecRefd())) { const EHEnt* eh = func->findEH(func->offsetOf(pc)); if (eh != nullptr) { // Found exception handler. Push the exception on top of the // stack and resume VM. ITRACE(1, "unwind: entering catch at {} func {} ({})\n", eh->m_handler, func->fullName()->data(), func->unit()->filepath()->data()); vmStack().pushObjectNoRc(phpException); pc = func->at(eh->m_handler); DEBUGGER_ATTACHED_ONLY(phpDebuggerExceptionHandlerHook()); return UnwindNone; } } // We found no more handlers in this frame. auto const jit = fpToUnwind != nullptr && fpToUnwind == fp->m_sfp; phpException = tearDownFrame(fp, stack, pc, phpException, jit, teardown); // If we entered from the JIT and this is the last iteration, we can't // trust the PC since catch traces for inlined frames may add more // frames on vmfp()'s rbp chain which might have resulted in us incorrectly // calculating the PC. if (exception.left() != phpException) { assertx(phpException == nullptr); if (fp && !jit) pc = skipCall(pc); ITRACE(1, "Returning with exception == null\n"); return UnwindFSWH; } if (!fp || (fpToUnwind && fp == fpToUnwind)) break; lockObjectWhileUnwinding(pc, stack); } if (fp || fpToUnwind) { assertx(fpToUnwind && (phpException || exception.right())); ITRACE(1, "Reached {}\n", fpToUnwind); if (phpException) phpException->decRefCount(); return UnwindReachedGoal; } ITRACE(1, "unwind: reached the end of this nesting's ActRec chain\n"); if (exception.right()) { exception.right()->throwException(); not_reached(); } assertx(phpException); throw_object(Object::attach(phpException)); } ////////////////////////////////////////////////////////////////////// }
35.603104
80
0.622595
Atry
7df94dbfe2eb1d337d19f03c8b460ab9640c7087
1,360
cc
C++
cc/output/copy_output_result.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
cc/output/copy_output_result.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
cc/output/copy_output_result.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/output/copy_output_result.h" #include "base/logging.h" #include "components/viz/common/quads/texture_mailbox.h" namespace cc { CopyOutputResult::CopyOutputResult() {} CopyOutputResult::CopyOutputResult(std::unique_ptr<SkBitmap> bitmap) : size_(bitmap->width(), bitmap->height()), bitmap_(std::move(bitmap)) { DCHECK(bitmap_); } CopyOutputResult::CopyOutputResult( const gfx::Size& size, const viz::TextureMailbox& texture_mailbox, std::unique_ptr<SingleReleaseCallback> release_callback) : size_(size), texture_mailbox_(texture_mailbox), release_callback_(std::move(release_callback)) { DCHECK(texture_mailbox_.IsTexture()); } CopyOutputResult::~CopyOutputResult() { if (release_callback_) release_callback_->Run(gpu::SyncToken(), false); } std::unique_ptr<SkBitmap> CopyOutputResult::TakeBitmap() { return std::move(bitmap_); } void CopyOutputResult::TakeTexture( viz::TextureMailbox* texture_mailbox, std::unique_ptr<SingleReleaseCallback>* release_callback) { *texture_mailbox = texture_mailbox_; *release_callback = std::move(release_callback_); texture_mailbox_ = viz::TextureMailbox(); } } // namespace cc
28.333333
76
0.747794
metux
7dfa357ea81a103eef3e76c1f4dc78093c7e9783
468
hpp
C++
lib/cml/hal/peripherals/RS485.hpp
msemegen/CML
f37e20f0add711c743b69607d39aa5ab0680cf7e
[ "MIT" ]
23
2020-07-16T21:52:38.000Z
2022-03-13T18:24:16.000Z
lib/cml/hal/peripherals/RS485.hpp
msemegen/CML
f37e20f0add711c743b69607d39aa5ab0680cf7e
[ "MIT" ]
16
2019-12-28T01:14:44.000Z
2021-04-15T14:40:07.000Z
lib/cml/hal/peripherals/RS485.hpp
msemegen/CML
f37e20f0add711c743b69607d39aa5ab0680cf7e
[ "MIT" ]
5
2020-07-17T17:48:50.000Z
2022-03-25T16:06:52.000Z
#pragma once /* * Name: RS485.hpp * * Copyright (c) Mateusz Semegen and contributors. All rights reserved. * Licensed under the MIT license. See LICENSE file in the project root for details. */ #ifdef STM32L4 #include <soc/m4/stm32l4/peripherals/RS485.hpp> #endif // STM32L4 namespace cml { namespace hal { #ifdef STM32L4 using RS485 = soc::m4::stm32l4::peripherals::RS485; #endif // STM32L4 } // namespace hal } // namespace cml
20.347826
87
0.675214
msemegen
7dfdfa0938d87d3c746a60cd2566d0ba6e14b113
173
cpp
C++
RemoteServer/EchoCommand.cpp
tdm1223/RemoteExplorer
b3ad193426f88c7d66cd1f23bf1fb4d4bde66bc4
[ "MIT" ]
2
2020-06-26T08:42:04.000Z
2021-10-30T07:47:30.000Z
RemoteServer/EchoCommand.cpp
tdm1223/RemoteExplorer
b3ad193426f88c7d66cd1f23bf1fb4d4bde66bc4
[ "MIT" ]
null
null
null
RemoteServer/EchoCommand.cpp
tdm1223/RemoteExplorer
b3ad193426f88c7d66cd1f23bf1fb4d4bde66bc4
[ "MIT" ]
null
null
null
#include"EchoCommand.h" bool EchoCommand::Execute(SOCKET sock, char* buf) { Sleep(2000); if (!Send(sock, buf)) { return false; } return true; }
15.727273
49
0.583815
tdm1223
7dfee15069cb1c0af2454d5d8d30cd03e401d9c8
1,864
cpp
C++
cpp-leetcode/lcci17.17-multi-search-lcci_trie.cpp
yanglr/LeetCodeOJ
27dd1e4a2442b707deae7921e0118752248bef5e
[ "MIT" ]
45
2021-07-25T00:45:43.000Z
2022-03-24T05:10:43.000Z
cpp-leetcode/lcci17.17-multi-search-lcci_trie.cpp
yanglr/LeetCodeOJ
27dd1e4a2442b707deae7921e0118752248bef5e
[ "MIT" ]
null
null
null
cpp-leetcode/lcci17.17-multi-search-lcci_trie.cpp
yanglr/LeetCodeOJ
27dd1e4a2442b707deae7921e0118752248bef5e
[ "MIT" ]
15
2021-07-25T00:40:52.000Z
2021-12-27T06:25:31.000Z
#include<vector> #include<algorithm> #include<iostream> #include<unordered_map> using namespace std; class Solution { private: struct Node { int idx; vector<Node*> children; Node() : idx(-1), children(26, nullptr) {} }; struct Trie { Node* root; Trie() : root(new Node()) {} void insert(string& word, int idx) { Node* p = root; for (char& c : word) { c -= 'a'; if (p->children[c] == nullptr) { p->children[c] = new Node(); } p = p->children[c]; } p->idx = idx; } }; public: vector<vector<int>> multiSearch(string big, vector<string>& smalls) { unordered_map<string, vector<int>> cache; const int n = big.size(); const int m = smalls.size(); vector<vector<int>> res(m); Trie trie = Trie(); // 构造前缀树 for (int i = 0; i < m; i++) { trie.insert(smalls[i], i); } for (int i = 0; i < n; i++) { int j = i; Node* node = trie.root; while (j < n && node->children[big[j] - 'a']) { node = node->children[big[j] - 'a']; if (node->idx != -1) { res[node->idx].push_back(i); } j++; } } return res; } }; // Test int main() { Solution sol; string big = "mississippi"; vector<string> smalls = {"is", "ppi", "hi", "sis", "i", "ssippi"}; auto res = sol.multiSearch(big, smalls); for (auto& row : res) // 遍历每一行 { for (auto& elem : row) // 输出每一个元素 cout << elem << " "; cout << "\n"; } return 0; }
24.207792
73
0.413627
yanglr
b40120c3a5e2bb8e6ba692b2cd8c782c7b787e59
26,057
cpp
C++
aten/src/ATen/native/LinearAlgebra.cpp
wxwoods/mctorch
7cd6eb51fdd01fa75ed9245039a4f145ba342de2
[ "BSD-3-Clause" ]
1
2019-07-23T11:20:58.000Z
2019-07-23T11:20:58.000Z
aten/src/ATen/native/LinearAlgebra.cpp
wxwoods/mctorch
7cd6eb51fdd01fa75ed9245039a4f145ba342de2
[ "BSD-3-Clause" ]
null
null
null
aten/src/ATen/native/LinearAlgebra.cpp
wxwoods/mctorch
7cd6eb51fdd01fa75ed9245039a4f145ba342de2
[ "BSD-3-Clause" ]
null
null
null
#include <ATen/ATen.h> #include <ATen/ExpandUtils.h> #include <ATen/Dispatch.h> #include <ATen/NativeFunctions.h> #include <ATen/LegacyTHFunctions.h> #include <ATen/native/LinearAlgebraUtils.h> #include <ATen/TensorUtils.h> #include <ATen/Parallel.h> #include <functional> #include <numeric> #include <vector> #include <limits> namespace at { namespace native { // Helper function for det methods. // For pivoted LU factorization A = P * L * U. Since we always have det(L) = 1, // det(P) = \pm 1, this method returns a 3-tuple: // (det(P), diag(U), info), // where info helps us identify singular matrices. static inline std::tuple<double, Tensor, int> _lu_det_P_diag_U_info(const Tensor& self) { Tensor p, lu, info; std::tie(lu, p, info) = at::_lu_with_info(self, /*pivot=*/true, /*check_errors=*/false); int int_info = info.item<int32_t>(); AT_CHECK(int_info >= 0, "LU factorization (getrf) failed with info = ", int_info); auto n = self.size(0); auto num_exchanges = (at::arange(1, n + 1, p.options()) != p).nonzero().size(0); if (num_exchanges % 2 == 1) { return std::make_tuple(-1., lu.diag(), int_info); } else { return std::make_tuple(1., lu.diag(), int_info); } } Tensor det(const Tensor& self) { AT_CHECK(at::isFloatingType(self.scalar_type()) && self.dim() == 2 && self.size(0) == self.size(1), "det(", self.type(), "{", self.sizes(), "}): expected a 2D square tensor " "of floating types"); double det_P; Tensor diag_U; int info; std::tie(det_P, diag_U, info) = _lu_det_P_diag_U_info(self); if (info > 0) { return at::zeros({}, self.options()); } else { return diag_U.prod().mul_(det_P); } } Tensor logdet(const Tensor& self) { AT_CHECK(at::isFloatingType(self.scalar_type()) && self.dim() == 2 && self.size(0) == self.size(1), "logdet(", self.type(), "{", self.sizes(), "}): expected a 2D square tensor " "of floating types"); double det_P; Tensor diag_U; int info; std::tie(det_P, diag_U, info) = _lu_det_P_diag_U_info(self); if (info > 0) { return at::full({}, -std::numeric_limits<double>::infinity(), self.options()); } // `det_sign` is the sign of the determinant. We work on `diag_U.sign()` for // numerical stability when diag_U has a lot small values. auto det_sign = diag_U.sign().prod().mul_(det_P); // This synchronizes on GPU, but `_lu_det_P_diag_U_info` above already synchronizes if (det_sign.item<double>() <= 0) { return det_sign.log_(); // get proper nan (det<0) or -inf (det=0) } else { return diag_U.abs_().log_().sum(); } } std::tuple<Tensor, Tensor> slogdet(const Tensor& self) { AT_CHECK(at::isFloatingType(self.scalar_type()) && self.dim() == 2 && self.size(0) == self.size(1), "slogdet(", self.type(), "{", self.sizes(), "}): expected a 2D square tensor " "of floating types"); double det_P; Tensor diag_U; int info; std::tie(det_P, diag_U, info) = _lu_det_P_diag_U_info(self); if (info > 0) { return std::make_tuple(at::zeros({}, self.options()), at::full({}, -std::numeric_limits<double>::infinity(), self.options())); } else { // `det_sign` is the sign of the determinant. We work on `diag_U.sign()` for // numerical stability when diag_U has a lot small values. auto det_sign = diag_U.sign().prod().mul_(det_P); return std::make_tuple(det_sign, diag_U.abs_().log_().sum()); } } Tensor pinverse(const Tensor& self, double rcond) { AT_CHECK(at::isFloatingType(self.scalar_type()) && self.dim() == 2, "pinverse(", self.type(), "{", self.sizes(), "}): expected a 2D tensor " "of floating types"); if (self.numel() == 0) { // Match NumPy return at::empty({self.size(1), self.size(0)}, self.options()); } Tensor U, S, V; std::tie(U, S, V) = self.svd(); Tensor max_val = S[0]; Tensor S_pseudoinv = at::where(S > rcond * max_val, S.reciprocal(), at::zeros({}, self.options())); return V.mm(S_pseudoinv.diag().mm(U.t())); } static inline Tensor _matrix_rank_helper(const Tensor& self, bool symmetric) { Tensor S; if (!symmetric) { Tensor U, V; std::tie(U, S, V) = self.svd(/*some=*/true, /*compute_uv=*/false); } else { Tensor eigvecs; std::tie(S, eigvecs) = self.symeig(/*eigenvectors=*/false); S = S.abs(); } return S; } Tensor matrix_rank(const Tensor& self, double tol, bool symmetric) { AT_CHECK(at::isFloatingType(self.scalar_type()) && self.dim() == 2, "matrix_rank(", self.type(), "{", self.sizes(), "}): expected a 2D tensor " "of floating types"); Tensor S = _matrix_rank_helper(self, symmetric); return (S > tol).sum(); } Tensor matrix_rank(const Tensor& self, bool symmetric) { AT_CHECK(at::isFloatingType(self.scalar_type()) && self.dim() == 2, "matrix_rank(", self.type(), "{", self.sizes(), "}): expected a 2D tensor " "of floating types"); Tensor S = _matrix_rank_helper(self, symmetric); double tol = _get_epsilon(self.scalar_type()) * std::max(self.size(0), self.size(1)); return (S > S.max().mul_(tol)).sum(); } static void check_1d(const Tensor& t, const char* arg, const char* fn) { AT_CHECK(t.dim() == 1, fn, ": Expected 1-D argument ", arg, ", but got ", t.dim(), "-D"); } Tensor ger(const Tensor& self, const Tensor& vec2) { check_1d(self, "self", "ger"); check_1d(vec2, "vec2", "ger"); return at::legacy::th::_th_ger(self, vec2); } Tensor& ger_out(Tensor& result, const Tensor& self, const Tensor& vec2) { check_1d(self, "self", "ger"); check_1d(vec2, "vec2", "ger"); return at::legacy::th::_th_ger_out(result, self, vec2); } Tensor mm(const Tensor& self, const Tensor& mat2) { if (self.is_sparse()) { return at::zeros({}, mat2.options()).addmm(self, mat2, 0, 1); } return at::legacy::th::_th_mm(self, mat2); } Tensor& mm_out(Tensor& result, const Tensor& self, const Tensor& mat2) { if (self.is_sparse()) { return at::addmm_out(result, at::zeros({}, mat2.options()), self, mat2, 0, 1); } return at::legacy::th::_th_mm_out(result, self, mat2); } Tensor mv(const Tensor& self, const Tensor& vec) { check_1d(vec, "vec", "mv"); return at::legacy::th::_th_mv(self, vec); } Tensor& mv_out(Tensor& result, const Tensor& self, const Tensor& vec) { check_1d(vec, "vec", "mv"); return at::legacy::th::_th_mv_out(result, self, vec); } Tensor addmv(const Tensor& self, const Tensor& mat, const Tensor& vec, Scalar beta, Scalar alpha) { check_1d(vec, "vec", "addmv"); return at::legacy::th::_th_addmv(self, mat, vec, beta, alpha); } Tensor& addmv_(Tensor& self, const Tensor& mat, const Tensor& vec, Scalar beta, Scalar alpha) { check_1d(vec, "vec", "addmv"); return at::legacy::th::_th_addmv_(self, mat, vec, beta, alpha); } Tensor& addmv_out(Tensor &result, const Tensor& self, const Tensor& mat, const Tensor& vec, Scalar beta, Scalar alpha) { check_1d(vec, "vec", "addmv"); return at::legacy::th::_th_addmv_out(result, self, mat, vec, beta, alpha); } Tensor addr(const Tensor& self, const Tensor& vec1, const Tensor& vec2, Scalar beta, Scalar alpha) { check_1d(vec1, "vec1", "addr"); check_1d(vec2, "vec2", "addr"); return at::legacy::th::_th_addr(self, vec1, vec2, beta, alpha); } Tensor& addr_(Tensor& self, const Tensor& vec1, const Tensor& vec2, Scalar beta, Scalar alpha) { check_1d(vec1, "vec1", "addr"); check_1d(vec2, "vec2", "addr"); return at::legacy::th::_th_addr_(self, vec1, vec2, beta, alpha); } Tensor& addr_out(Tensor &result, const Tensor& self, const Tensor& vec1, const Tensor& vec2, Scalar beta, Scalar alpha) { check_1d(vec1, "vec1", "addr"); check_1d(vec2, "vec2", "addr"); return at::legacy::th::_th_addr_out(result, self, vec1, vec2, beta, alpha); } template <typename scalar_t, bool is_bmm> inline void baddbmm_cpu_kernel(const Tensor& result, const Tensor& self, const Tensor& mat2, Scalar beta_, Scalar alpha_) { int64_t bs = result.size(0); int64_t is = result.size(1); int64_t js = result.size(2); int64_t ks = self.size(2); scalar_t alpha = alpha_.to<scalar_t>(); scalar_t beta = beta_.to<scalar_t>(); auto r0 = result.accessor<scalar_t, 3>(); auto s0 = self.accessor<scalar_t, 3>(); auto m0 = mat2.accessor<scalar_t, 3>(); int64_t grain_size = std::min(internal::GRAIN_SIZE / (is * js * ks), (int64_t)1); parallel_for(0, bs, grain_size, [&](int64_t b_begin, int64_t b_end) { for (int64_t b = b_begin; b < b_end; b++) { auto r1 = r0[b]; auto s1 = s0[b]; auto m1 = m0[b]; for (int64_t i = 0; i < is; i++) { auto r2 = r1[i]; auto s2 = s1[i]; for (int64_t j = 0; j < js; j++) { scalar_t &r = r2[j]; if (is_bmm) { r = 0; for (int64_t k = 0; k < ks; k++) { r += s2[k] * m1[k][j]; } } else { r *= beta; for (int64_t k = 0; k < ks; k++) { r += alpha * s2[k] * m1[k][j]; } } } } } }); } // This tries to apply some optimizations to bmm/baddbmm: // - When the operand size is small, computation are parallelized over the batch // dimension using OMP and naive matrix multiplication is applied. // - When the operand size is larger than the threshold, if compiled with MKL, MKL's batch gemm is used. // - Otherwise, we use a series of matrix multiplications. // The threshold of 400 for the first has not been thoroughly benchmarked yet and may have room for further // optimization, it likely depends on the characteristics of the CPU, MKL will be different from non-MKL etc., // but this seems to be a first starting point. static inline Tensor& bmm_out_or_baddbmm_(Tensor& self_or_result, const Tensor& batch1, const Tensor& batch2, Scalar beta, Scalar alpha, bool is_bmm_out) { // is_bmm_out: true for bmm_out, false for baddbmm_ // self_or_result is "self" for baddbmm_ and "result" for bmm_out CheckedFrom c = (is_bmm_out ? "bmm" : "baddbmm"); TensorArg self_arg(self_or_result, is_bmm_out ? "self" : "result", 0); TensorArg b1_arg(batch1, "batch1", 1); TensorArg b2_arg(batch2, "batch2", 2); checkBackend(c, {self_or_result, batch1, batch2}, Backend::CPU); checkDim(c, b1_arg, 3); checkDim(c, b2_arg, 3); int64_t bs = batch1.size(0); checkSize(c, b2_arg, 0, bs); int64_t contraction_size = batch1.size(2); int64_t res_rows = batch1.size(1); int64_t res_cols = batch2.size(2); checkSize(c, b2_arg, 1, contraction_size); if (is_bmm_out) { self_or_result.resize_({bs, res_rows, res_cols}); } else { checkSize(c, self_arg, 0, bs); checkSize(c, self_arg, 1, res_rows); checkSize(c, self_arg, 2, res_cols); } // handle pathological cases that blas may not like if (self_or_result.numel() == 0) { return self_or_result; } else if (contraction_size == 0) { return self_or_result.zero_(); } auto batch_items_contiguous_or_transposed = [&](const Tensor& t) { return (t.stride(2) == 1 && t.stride(1) >= t.size(2)) || (t.stride(1) == 1 && t.stride(2) >= t.size(1)); }; if (contraction_size * res_rows * res_cols < 400) { if (is_bmm_out) { AT_DISPATCH_ALL_TYPES(batch1.scalar_type(), "bmm", [&] { baddbmm_cpu_kernel<scalar_t, true>(self_or_result, batch1, batch2, beta, alpha); }); } else { AT_DISPATCH_ALL_TYPES(batch1.scalar_type(), "baddbmm", [&] { baddbmm_cpu_kernel<scalar_t, false>(self_or_result, batch1, batch2, beta, alpha); }); } } else if (at::hasMKL() && at::native::is_floating_point(self_or_result) && batch_items_contiguous_or_transposed(batch1) && batch_items_contiguous_or_transposed(batch2) && self_or_result.is_contiguous()) { at::native::_baddbmm_mkl_(self_or_result, batch1, batch2, beta, alpha); } else { // split along batch dimension if (is_bmm_out) { for (int64_t b = 0; b < bs; b++) { auto r = self_or_result.select(0, b); at::native::mm_out(r, batch1.select(0, b), batch2.select(0, b)); } } else { for (int64_t b = 0; b < bs; b++) { self_or_result.select(0, b).addmm_(batch1.select(0, b), batch2.select(0, b), beta, alpha); } } } return self_or_result; } Tensor baddbmm_cpu(const Tensor& self, const Tensor& batch1, const Tensor& batch2, Scalar beta, Scalar alpha) { Tensor result = at::empty({0}, self.options()); return at::native::baddbmm_out_cpu(result, self, batch1, batch2, beta, alpha); } Tensor& baddbmm_out_cpu(Tensor &result, const Tensor& self_, const Tensor& batch1, const Tensor& batch2, Scalar beta, Scalar alpha) { Tensor self; std::tie(self) = expand_size(self_, {batch1.size(0), batch1.size(1), batch2.size(2)}, "baddbmm"); result.resize_(self.sizes()); result.copy_(self); return at::native::baddbmm__cpu(result, batch1, batch2, beta, alpha); } Tensor& baddbmm__cpu(Tensor& self, const Tensor& batch1, const Tensor& batch2, Scalar beta, Scalar alpha) { return bmm_out_or_baddbmm_(self, batch1, batch2, beta, alpha, false); } Tensor bmm_cpu(const Tensor& self, const Tensor& mat2) { Tensor result = at::empty({0}, self.options()); return at::native::bmm_out_cpu(result, self, mat2); } Tensor& bmm_out_cpu(Tensor &result, const Tensor& batch1, const Tensor& batch2) { Scalar beta(0.0); Scalar alpha(1.0); return bmm_out_or_baddbmm_(result, batch1, batch2, beta, alpha, true); } Tensor dot(const Tensor& self, const Tensor& tensor) { check_1d(self, "self", "dot"); check_1d(tensor, "tensor", "dot"); return at::legacy::th::_th_dot(self, tensor); } Tensor& dot_out(Tensor& result, const Tensor& self, const Tensor& tensor) { result.resize_({}); AT_CHECK(result.scalar_type() == self.scalar_type(), "result dtype ", result.scalar_type(), " does not match self dtype ", self.scalar_type()); return result.fill_(self.dot(tensor)); } /* Matrix product of two Tensors. The behavior depends on the dimensionality of the Tensors as follows: - If both Tensors are 1-dimensional, the dot product (scalar) is returned. - If both arguments are 2-dimensional, the matrix-matrix product is returned. - If the first argument is 1-dimensional and the second argument is 2-dimensional, a 1 is prepended to its dimension for the purpose of the matrix multiply. After the matrix multiply, the prepended dimension is removed. - If the first argument is 2-dimensional and the second argument is 1-dimensional, the matrix-vector product is returned. - If both arguments are at least 1-dimensional and at least one argument is N-dimensional (where N > 2), then a batched matrix multiply is returned. If the first argument is 1-dimensional, a 1 is prepended to its dimension for the purpose of the batched matrix multiply and removed after. If the second argument is 1-dimensional, a 1 is appended to its dimension for the purpose of the batched matrix multiple and removed after. The non-matrix (i.e. batch) dimensions are broadcasted (and thus must be broadcastable). For example, if tensor1 is a (j x 1 x n x m) Tensor and tensor2 is a (k x m x p) Tensor, the returned tensor will be an (j x k x n x p) Tensor. */ Tensor matmul( c10::optional<Tensor> out_opt, const Tensor& tensor1, const Tensor& tensor2) { auto dim_tensor1 = tensor1.dim(); auto dim_tensor2 = tensor2.dim(); auto has_out = out_opt.has_value(); Tensor out = out_opt.value_or(Tensor()); if (dim_tensor1 == 1 && dim_tensor2 == 1) { return has_out ? at::native::dot_out(out, tensor1, tensor2) : tensor1.dot(tensor2); } else if (dim_tensor1 == 2 && dim_tensor2 == 1) { return has_out ? at::native::mv_out(out, tensor1, tensor2) : tensor1.mv(tensor2); } else if (dim_tensor1 == 1 && dim_tensor2 == 2) { return has_out ? at::native::mm_out(out, tensor1.unsqueeze(0), tensor2).squeeze_(0) : tensor1.unsqueeze(0).mm(tensor2).squeeze_(0); } else if (dim_tensor1 == 2 && dim_tensor2 == 2) { return has_out ? at::native::mm_out(out, tensor1, tensor2) : tensor1.mm(tensor2); } else if (dim_tensor1 >= 3 && (dim_tensor2 == 1 || dim_tensor2 == 2)) { // optimization: use mm instead of bmm by folding tensor1's batch into // its leading matrix dimension. Tensor t2 = dim_tensor2 == 1 ? tensor2.unsqueeze(-1) : tensor2; auto size1 = tensor1.sizes(); auto size2 = t2.sizes(); std::vector<int64_t> output_size; output_size.insert(output_size.end(), size1.begin(), size1.end() - 1); if (dim_tensor2 > 1) { output_size.push_back(size2[dim_tensor2 - 1]); } // fold the batch into the first dimension Tensor t1 = tensor1.contiguous().view({-1, size1[size1.size() - 1]}); Tensor output = has_out ? at::_unsafe_view(at::mm_out(out, t1, t2), output_size) : at::_unsafe_view(t1.mm(t2), output_size); return has_out ? out.set_(output) : output; } else if ((dim_tensor1 >= 1 && dim_tensor2 >= 1) && (dim_tensor1 >= 3 || dim_tensor2 >= 3)) { // We are multiplying b1 x n x m1 by x2 x m2 x p (where b1 can be a list); // we track m1 vs m2 separately even though they must match for nicer error messages int64_t n = dim_tensor1 > 1 ? tensor1.size(-2) : 1; int64_t m1 = tensor1.size(-1); IntArrayRef batch_tensor1(tensor1.sizes().data(), std::max<int64_t>(dim_tensor1 - 2, 0)); int64_t m2 = dim_tensor2 > 1 ? tensor2.size(-2) : 1; int64_t p = tensor2.size(-1); IntArrayRef batch_tensor2(tensor2.sizes().data(), std::max<int64_t>(dim_tensor2 - 2, 0)); // expand the batch portion (i.e. cut off matrix dimensions and expand rest) std::vector<int64_t> expand_batch_portion = infer_size(batch_tensor1, batch_tensor2); std::vector<int64_t> tensor1_expand_size(expand_batch_portion); tensor1_expand_size.insert(tensor1_expand_size.end(), {n, m1}); std::vector<int64_t> tensor2_expand_size(expand_batch_portion); tensor2_expand_size.insert(tensor2_expand_size.end(), {m2, p}); int expand_batch_product = std::accumulate(expand_batch_portion.begin(), expand_batch_portion.end(), 1, std::multiplies<int64_t>()); std::vector<int64_t> tensor1_bmm_view({expand_batch_product}); tensor1_bmm_view.insert(tensor1_bmm_view.end(), {n, m1}); std::vector<int64_t> tensor2_bmm_view({expand_batch_product}); tensor2_bmm_view.insert(tensor2_bmm_view.end(), {m2, p}); // flatten expanded batches Tensor tensor1_expanded = tensor1.expand(tensor1_expand_size).contiguous().view(tensor1_bmm_view); Tensor tensor2_expanded = tensor2.expand(tensor2_expand_size).contiguous().view(tensor2_bmm_view); // reshape batches back into result std::vector<int64_t> output_shape(expand_batch_portion); if (dim_tensor1 > 1) { output_shape.push_back(n); } if (dim_tensor2 > 1) { output_shape.push_back(p); } Tensor output = has_out ? at::_unsafe_view(at::bmm_out(out, tensor1_expanded, tensor2_expanded), output_shape) : at::_unsafe_view(tensor1_expanded.bmm(tensor2_expanded), output_shape); return has_out ? out.set_(output) : output; } AT_ERROR("both arguments to matmul need to be at least 1D, but they are ", dim_tensor1, "D and ", dim_tensor2, "D"); } Tensor matmul(const Tensor & tensor1, const Tensor & tensor2) { return at::native::matmul(c10::nullopt, tensor1, tensor2); } Tensor& matmul_out(Tensor &result, const Tensor & tensor1, const Tensor & tensor2) { at::native::matmul(c10::optional<Tensor>(result), tensor1, tensor2); return result; } Tensor matrix_power(const Tensor& a, int64_t n) { AT_CHECK(a.dim() >= 2 && at::isFloatingType(a.scalar_type()), "matrix_power(", a.type(), "{", a.sizes(), "}): expected a tensor " "of floating types with dim at least 2"); if (n == 0) { return a.clone().copy_(at::eye(a.size(-2), a.options()).expand_as(a)); } else if (n < 0) { Tensor a_ = at::inverse(a); n *= -1; return at::native::matrix_power(a_, n); } else if (n == 1) { return a.clone(); } else if (n == 2) { return at::native::matmul(a, a); } else if (n == 3) { return at::native::matmul(at::native::matmul(a, a), a); } // This is a binary decomposition of n. // Moving from the least significant bit to the most significant bit // This is done to reduce the number of matrix multiplications // by raising the input matrix in powers of 2 // The total number of matrix multiplications are // number of bits + number of bits that equal 1 ~ O(log n) // instead of O(n) Tensor result, z; int64_t r; while (n > 0) { z = (!z.defined()) ? a.clone() : at::native::matmul(z, z); r = n % 2; n = n / 2; if (r == 1) { result = (!result.defined()) ? z.clone() : at::native::matmul(result, z); } } return result; } Tensor frobenius_norm(const Tensor& self) { return at::norm(self); } Tensor frobenius_norm(const Tensor& self, IntArrayRef dim, bool keepdim) { AT_CHECK( dim.size() <= 2, "Expected at most 2 dimensions, but got ", dim.size(), " dimensions instead."); if (dim.size() == 1) { return at::norm(self, 2, dim, keepdim, self.scalar_type()); } return at::sqrt(at::sum(self * self, dim, keepdim)); } Tensor &frobenius_norm_out( Tensor& result, const Tensor& self, IntArrayRef dim, bool keepdim) { AT_CHECK( dim.size() <= 2, "Expected at most 2 dimensions, but got ", dim.size(), " dimensions instead."); if (dim.size() == 1) { return at::norm_out(result, self, 2, dim, keepdim, self.scalar_type()); } return at::sqrt_out(result, at::sum(self * self, dim, keepdim)); } Tensor nuclear_norm(const Tensor& self, bool keepdim) { AT_CHECK( self.dim() == 2, "Expected a tensor with 2 dimensions, but got a ", self.dim(), " dimensions tensor instead."); return at::sum(std::get<1>(at::svd(self)), 0, keepdim); } Tensor &nuclear_norm_out(Tensor& result, const Tensor& self, bool keepdim) { AT_CHECK( self.dim() == 2, "Expected a tensor with 2 dimensions, but got a ", self.dim(), " dimensions tensor instead."); return at::sum_out(result, std::get<1>(at::svd(self)), 0, keepdim); } static inline Tensor _chain_matmul_general(TensorList matrices, std::vector<std::vector<int64_t>>& order, int64_t i, int64_t j) { if (i == j) return matrices[i]; else return at::mm(_chain_matmul_general(matrices, order, i, order[i][j]), _chain_matmul_general(matrices, order, order[i][j] + 1, j)); } // Why the separate implementation for 3 matrices? // The logic for three matrices is much faster when done directly // Requires 1 comparison to 4 comparisons and lesser arithmetic operations static inline Tensor _chain_matmul_three_matrices(TensorList matrices) { int64_t a = matrices[0].size(0); // This is the first dimension int64_t b = matrices[1].size(0); // This is the common dimension between the first two matrices int64_t c = matrices[2].size(0); // This is the common dimension between the last two matrices int64_t d = matrices[2].size(1); // This is the last dimension // The matrices are of size (a x b), (b x c), (c x d) // cost_1 is the cost of parenthesizing (a x b) and (b x c) and then combining (c x d) // cost_2 is the cost of parenthesizing (b x c) and (c x d) and then combining (a x b) int64_t cost_1 = (a * c) * (b + d); int64_t cost_2 = (b * d) * (a + c); if (cost_1 > cost_2) { return at::mm(matrices[0], at::mm(matrices[1], matrices[2])); } else { return at::mm(at::mm(matrices[0], matrices[1]), matrices[2]); } } Tensor chain_matmul(TensorList matrices) { checkAllSameDim(matrices, 2); if (matrices.size() == 1) { return matrices[0]; } else if (matrices.size() == 2) { return at::mm(matrices[0], matrices[1]); } else if (matrices.size() == 3) { return _chain_matmul_three_matrices(matrices); } else { // Following the algorithm in Chapter 15.2 : Introduction to Algorithms, Cormen et al. // Minor modifications have been made to accommodate zero-indexing auto n = matrices.size(); // Dim vector - the length of which is n + 1. Note that for matrix multiplication, there // needs to a common dimension between the multiplicands, hence for n matrices, there are // n + 1 values. The values p_{i} and p_{i + 1} correspond to the dimensions of matrix i in // the chain (zero-indexed) std::vector<int64_t> p; p.push_back(matrices[0].size(0)); for (int64_t i = 0; i < n; i++) { p.push_back(matrices[i].size(1)); } // Cost matrix - an element m[i, j] of this matrix corresponds to the minimum cost of // parenthesizing matrices A_{i} to A_{j}. By this definition m[i, i] = 0 for all i // m[i, j] is filled using the substructure property of the algorithm, meaning: // m[i, j] = min_{i <= k < j} m[i, k] + m[k, j] + p_{i-1}p_{k}p_{j} std::vector<std::vector<int64_t>> m(n, std::vector<int64_t>(n, 0)); // Auxiliary table for constructing the order // s[i, j] stores the index k at which the optimal split is obtained std::vector<std::vector<int64_t>> s(n, std::vector<int64_t>(n)); // j and q are used repetitively in the algorithm below int64_t j, q; for (int64_t l = 1; l < n; l++) { for (int64_t i = 0; i < n - l; i++) { j = i + l; m[i][j] = std::numeric_limits<int64_t>::max(); for (int64_t k = i; k < j; k++) { q = m[i][k] + m[k + 1][j] + p[i] * p[k + 1] * p[j + 1]; if (q < m[i][j]) { m[i][j] = q; s[i][j] = k; } } } } // We use the result from the algorithm to compute the matrix chain product via recursion return _chain_matmul_general(matrices, s, 0, n - 1); } } } // namespace native } // namespace at
39.065967
155
0.644856
wxwoods
b4017fd6a90ad0f9f060e68d9500d2c4da784f73
40,053
cpp
C++
be/src/olap/reader.cpp
spaces-X/doris-vectorized
73ff3f3c0786c79a154e714fde56c812ac3f4f8f
[ "Apache-2.0" ]
null
null
null
be/src/olap/reader.cpp
spaces-X/doris-vectorized
73ff3f3c0786c79a154e714fde56c812ac3f4f8f
[ "Apache-2.0" ]
null
null
null
be/src/olap/reader.cpp
spaces-X/doris-vectorized
73ff3f3c0786c79a154e714fde56c812ac3f4f8f
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "olap/reader.h" #include <parallel_hashmap/phmap.h> #include <boost/algorithm/string/case_conv.hpp> #include <charconv> #include <unordered_set> #include "olap/bloom_filter_predicate.h" #include "olap/collect_iterator.h" #include "vec/olap/vcollect_iterator.h" #include "olap/comparison_predicate.h" #include "olap/in_list_predicate.h" #include "olap/null_predicate.h" #include "olap/row.h" #include "olap/row_block.h" #include "olap/row_cursor.h" #include "olap/rowset/beta_rowset_reader.h" #include "olap/rowset/column_data.h" #include "olap/schema.h" #include "olap/storage_engine.h" #include "olap/tablet.h" #include "runtime/mem_pool.h" #include "runtime/mem_tracker.h" #include "runtime/string_value.hpp" #include "util/date_func.h" #include "util/mem_util.hpp" using std::nothrow; using std::set; using std::vector; namespace doris { void ReaderParams::check_validation() const { if (UNLIKELY(version.first == -1)) { LOG(FATAL) << "version is not set. tablet=" << tablet->full_name(); } } std::string ReaderParams::to_string() const { std::stringstream ss; ss << "tablet=" << tablet->full_name() << " reader_type=" << reader_type << " aggregation=" << aggregation << " version=" << version << " start_key_include=" << start_key_include << " end_key_include=" << end_key_include; for (const auto& key : start_key) { ss << " keys=" << key; } for (const auto& key : end_key) { ss << " end_keys=" << key; } for (auto& condition : conditions) { ss << " conditions=" << apache::thrift::ThriftDebugString(condition); } return ss.str(); } KeysParam::~KeysParam() { for (auto start_key : start_keys) { SAFE_DELETE(start_key); } for (auto end_key : end_keys) { SAFE_DELETE(end_key); } } std::string KeysParam::to_string() const { std::stringstream ss; ss << "start_key_include=" << start_key_include << " end_key_include=" << end_key_include; for (auto start_key : start_keys) { ss << " keys=" << start_key->to_string(); } for (auto end_key : end_keys) { ss << " end_keys=" << end_key->to_string(); } return ss.str(); } Reader::Reader() : _collect_iter(new CollectIterator()) {} Reader::~Reader() { VLOG_NOTICE << "merged rows:" << _merged_rows; _conditions.finalize(); if (!_all_conditions.empty()) { _all_conditions.finalize(); } _delete_handler.finalize(); for (auto pred : _col_predicates) { delete pred; } for (auto pred : _value_col_predicates) { delete pred; } } OLAPStatus Reader::init(const ReaderParams& read_params) { // TODO(yingchun): monitor _tracker.reset(new MemTracker(-1, read_params.tablet->full_name())); _predicate_mem_pool.reset(new MemPool(_tracker.get())); OLAPStatus res = _init_params(read_params); if (res != OLAP_SUCCESS) { LOG(WARNING) << "fail to init reader when init params. res:" << res << ", tablet_id:" << read_params.tablet->tablet_id() << ", schema_hash:" << read_params.tablet->schema_hash() << ", reader type:" << read_params.reader_type << ", version:" << read_params.version; return res; } std::vector<RowsetReaderSharedPtr> rs_readers; res = _capture_rs_readers(read_params, &rs_readers); if (res != OLAP_SUCCESS) { LOG(WARNING) << "fail to init reader when _capture_rs_readers. res:" << res << ", tablet_id:" << read_params.tablet->tablet_id() << ", schema_hash:" << read_params.tablet->schema_hash() << ", reader_type:" << read_params.reader_type << ", version:" << read_params.version; return res; } return OLAP_SUCCESS; } // When only one rowset has data, and this rowset is nonoverlapping, we can read directly without aggregation bool Reader::_optimize_for_single_rowset(const std::vector<RowsetReaderSharedPtr>& rs_readers) { bool has_delete_rowset = false; bool has_overlapping = false; int nonoverlapping_count = 0; for (const auto& rs_reader : rs_readers) { if (rs_reader->rowset()->rowset_meta()->delete_flag()) { has_delete_rowset = true; break; } if (rs_reader->rowset()->rowset_meta()->num_rows() > 0) { if (rs_reader->rowset()->rowset_meta()->is_segments_overlapping()) { // when there are overlapping segments, can not do directly read has_overlapping = true; break; } else if (++nonoverlapping_count > 1) { break; } } } return !has_overlapping && nonoverlapping_count == 1 && !has_delete_rowset; } OLAPStatus Reader::_capture_rs_readers(const ReaderParams& read_params, std::vector<RowsetReaderSharedPtr>* valid_rs_readers) { const std::vector<RowsetReaderSharedPtr>* rs_readers = &read_params.rs_readers; if (rs_readers->empty()) { LOG(WARNING) << "fail to acquire data sources. tablet=" << _tablet->full_name(); return OLAP_ERR_VERSION_NOT_EXIST; } bool eof = false; bool is_lower_key_included = _keys_param.start_key_include; bool is_upper_key_included = _keys_param.end_key_include; for (int i = 0; i < _keys_param.start_keys.size(); ++i) { // lower bound RowCursor* start_key = _keys_param.start_keys[i]; RowCursor* end_key = _keys_param.end_keys[i]; if (!is_lower_key_included) { if (end_key != nullptr && compare_row_key(*start_key, *end_key) >= 0) { VLOG_NOTICE << "return EOF when lower key not include" << ", start_key=" << start_key->to_string() << ", end_key=" << end_key->to_string(); eof = true; break; } } else { if (end_key != nullptr && compare_row_key(*start_key, *end_key) > 0) { VLOG_NOTICE << "return EOF when lower key include=" << ", start_key=" << start_key->to_string() << ", end_key=" << end_key->to_string(); eof = true; break; } } _is_lower_keys_included.push_back(is_lower_key_included); _is_upper_keys_included.push_back(is_upper_key_included); } if (eof) { return OLAP_SUCCESS; } bool need_ordered_result = true; if (read_params.reader_type == READER_QUERY) { if (_tablet->tablet_schema().keys_type() == DUP_KEYS) { // duplicated keys are allowed, no need to merge sort keys in rowset need_ordered_result = false; } if (_aggregation) { // compute engine will aggregate rows with the same key, // it's ok for rowset to return unordered result need_ordered_result = false; } } _reader_context.reader_type = read_params.reader_type; _reader_context.tablet_schema = &_tablet->tablet_schema(); _reader_context.need_ordered_result = need_ordered_result; _reader_context.return_columns = &_return_columns; _reader_context.seek_columns = &_seek_columns; _reader_context.load_bf_columns = &_load_bf_columns; _reader_context.load_bf_all_columns = &_load_bf_all_columns; _reader_context.conditions = &_conditions; _reader_context.all_conditions = &_all_conditions; _reader_context.predicates = &_col_predicates; _reader_context.value_predicates = &_value_col_predicates; _reader_context.lower_bound_keys = &_keys_param.start_keys; _reader_context.is_lower_keys_included = &_is_lower_keys_included; _reader_context.upper_bound_keys = &_keys_param.end_keys; _reader_context.is_upper_keys_included = &_is_upper_keys_included; _reader_context.delete_handler = &_delete_handler; _reader_context.stats = &_stats; _reader_context.runtime_state = read_params.runtime_state; _reader_context.use_page_cache = read_params.use_page_cache; _reader_context.sequence_id_idx = _sequence_col_idx; *valid_rs_readers = *rs_readers; return OLAP_SUCCESS; } OLAPStatus Reader::_init_params(const ReaderParams& read_params) { read_params.check_validation(); _aggregation = read_params.aggregation; _need_agg_finalize = read_params.need_agg_finalize; _reader_type = read_params.reader_type; _tablet = read_params.tablet; _init_conditions_param(read_params); _init_load_bf_columns(read_params); OLAPStatus res = _init_delete_condition(read_params); if (res != OLAP_SUCCESS) { OLAP_LOG_WARNING("fail to init delete param. [res=%d]", res); return res; } res = _init_return_columns(read_params); if (res != OLAP_SUCCESS) { OLAP_LOG_WARNING("fail to init return columns. [res=%d]", res); return res; } res = _init_keys_param(read_params); if (res != OLAP_SUCCESS) { LOG(WARNING) << "fail to init keys param. res=" << res; return res; } _init_seek_columns(); _collect_iter->init(this); if (_tablet->tablet_schema().has_sequence_col()) { auto sequence_col_idx = _tablet->tablet_schema().sequence_col_idx(); DCHECK_NE(sequence_col_idx, -1); for (auto col : _return_columns) { // query has sequence col if (col == sequence_col_idx) { _sequence_col_idx = sequence_col_idx; break; } } } return res; } OLAPStatus Reader::_init_return_columns(const ReaderParams& read_params) { if (read_params.reader_type == READER_QUERY) { _return_columns = read_params.return_columns; if (!_delete_handler.empty()) { // We need to fetch columns which there are deletion conditions on them. set<uint32_t> column_set(_return_columns.begin(), _return_columns.end()); for (const auto& conds : _delete_handler.get_delete_conditions()) { for (const auto& cond_column : conds.del_cond->columns()) { if (column_set.find(cond_column.first) == column_set.end()) { column_set.insert(cond_column.first); _return_columns.push_back(cond_column.first); } } } } for (auto id : read_params.return_columns) { if (_tablet->tablet_schema().column(id).is_key()) { _key_cids.push_back(id); } else { _value_cids.push_back(id); } } } else if (read_params.return_columns.empty()) { for (size_t i = 0; i < _tablet->tablet_schema().num_columns(); ++i) { _return_columns.push_back(i); if (_tablet->tablet_schema().column(i).is_key()) { _key_cids.push_back(i); } else { _value_cids.push_back(i); } } VLOG_NOTICE << "return column is empty, using full column as default."; } else if (read_params.reader_type == READER_CHECKSUM) { _return_columns = read_params.return_columns; for (auto id : read_params.return_columns) { if (_tablet->tablet_schema().column(id).is_key()) { _key_cids.push_back(id); } else { _value_cids.push_back(id); } } } else { OLAP_LOG_WARNING("fail to init return columns. [reader_type=%d return_columns_size=%u]", read_params.reader_type, read_params.return_columns.size()); return OLAP_ERR_INPUT_PARAMETER_ERROR; } std::sort(_key_cids.begin(), _key_cids.end(), std::greater<uint32_t>()); return OLAP_SUCCESS; } void Reader::_init_seek_columns() { std::unordered_set<uint32_t> column_set(_return_columns.begin(), _return_columns.end()); for (auto& it : _conditions.columns()) { column_set.insert(it.first); } size_t max_key_column_count = 0; for (const auto& key : _keys_param.start_keys) { max_key_column_count = std::max(max_key_column_count, key->field_count()); } for (const auto& key : _keys_param.end_keys) { max_key_column_count = std::max(max_key_column_count, key->field_count()); } for (size_t i = 0; i < _tablet->tablet_schema().num_columns(); i++) { if (i < max_key_column_count || column_set.find(i) != column_set.end()) { _seek_columns.push_back(i); } } } OLAPStatus Reader::_init_keys_param(const ReaderParams& read_params) { if (read_params.start_key.empty()) { return OLAP_SUCCESS; } _keys_param.start_key_include = read_params.start_key_include; _keys_param.end_key_include = read_params.end_key_include; size_t start_key_size = read_params.start_key.size(); _keys_param.start_keys.resize(start_key_size, nullptr); size_t scan_key_size = read_params.start_key.front().size(); if (scan_key_size > _tablet->tablet_schema().num_columns()) { LOG(WARNING) << "Input param are invalid. Column count is bigger than num_columns of schema. " << "column_count=" << scan_key_size << ", schema.num_columns=" << _tablet->tablet_schema().num_columns(); return OLAP_ERR_INPUT_PARAMETER_ERROR; } std::vector<uint32_t> columns(scan_key_size); std::iota(columns.begin(), columns.end(), 0); std::shared_ptr<Schema> schema = std::make_shared<Schema>(_tablet->tablet_schema().columns(), columns); for (size_t i = 0; i < start_key_size; ++i) { if (read_params.start_key[i].size() != scan_key_size) { OLAP_LOG_WARNING("The start_key.at(%ld).size == %ld, not equals the %ld", i, read_params.start_key[i].size(), scan_key_size); return OLAP_ERR_INPUT_PARAMETER_ERROR; } if ((_keys_param.start_keys[i] = new (nothrow) RowCursor()) == nullptr) { OLAP_LOG_WARNING("fail to new RowCursor!"); return OLAP_ERR_MALLOC_ERROR; } OLAPStatus res = _keys_param.start_keys[i]->init_scan_key( _tablet->tablet_schema(), read_params.start_key[i].values(), schema); if (res != OLAP_SUCCESS) { OLAP_LOG_WARNING("fail to init row cursor. [res=%d]", res); return res; } res = _keys_param.start_keys[i]->from_tuple(read_params.start_key[i]); if (res != OLAP_SUCCESS) { OLAP_LOG_WARNING("fail to init row cursor from Keys. [res=%d key_index=%ld]", res, i); return res; } } size_t end_key_size = read_params.end_key.size(); _keys_param.end_keys.resize(end_key_size, nullptr); for (size_t i = 0; i < end_key_size; ++i) { if (read_params.end_key[i].size() != scan_key_size) { OLAP_LOG_WARNING("The end_key.at(%ld).size == %ld, not equals the %ld", i, read_params.end_key[i].size(), scan_key_size); return OLAP_ERR_INPUT_PARAMETER_ERROR; } if ((_keys_param.end_keys[i] = new (nothrow) RowCursor()) == nullptr) { OLAP_LOG_WARNING("fail to new RowCursor!"); return OLAP_ERR_MALLOC_ERROR; } OLAPStatus res = _keys_param.end_keys[i]->init_scan_key( _tablet->tablet_schema(), read_params.end_key[i].values(), schema); if (res != OLAP_SUCCESS) { OLAP_LOG_WARNING("fail to init row cursor. [res=%d]", res); return res; } res = _keys_param.end_keys[i]->from_tuple(read_params.end_key[i]); if (res != OLAP_SUCCESS) { OLAP_LOG_WARNING("fail to init row cursor from Keys. [res=%d key_index=%ld]", res, i); return res; } } //TODO:check the valid of start_key and end_key.(eg. start_key <= end_key) return OLAP_SUCCESS; } void Reader::_init_conditions_param(const ReaderParams& read_params) { _conditions.set_tablet_schema(&_tablet->tablet_schema()); _all_conditions.set_tablet_schema(&_tablet->tablet_schema()); for (const auto& condition : read_params.conditions) { ColumnPredicate* predicate = _parse_to_predicate(condition); if (predicate != nullptr) { if (_tablet->tablet_schema() .column(_tablet->field_index(condition.column_name)) .aggregation() != FieldAggregationMethod::OLAP_FIELD_AGGREGATION_NONE) { _value_col_predicates.push_back(predicate); } else { _col_predicates.push_back(predicate); OLAPStatus status = _conditions.append_condition(condition); DCHECK_EQ(OLAP_SUCCESS, status); } OLAPStatus status = _all_conditions.append_condition(condition); DCHECK_EQ(OLAP_SUCCESS, status); } } // Only key column bloom filter will push down to storage engine for (const auto& filter : read_params.bloom_filters) { _col_predicates.emplace_back(_parse_to_predicate(filter)); } } #define COMPARISON_PREDICATE_CONDITION_VALUE(NAME, PREDICATE) \ ColumnPredicate* Reader::_new_##NAME##_pred(const TabletColumn& column, int index, \ const std::string& cond, bool opposite) const { \ ColumnPredicate* predicate = nullptr; \ switch (column.type()) { \ case OLAP_FIELD_TYPE_TINYINT: { \ int8_t value = 0; \ std::from_chars(cond.data(), cond.data() + cond.size(), value); \ predicate = new PREDICATE<int8_t>(index, value, opposite); \ break; \ } \ case OLAP_FIELD_TYPE_SMALLINT: { \ int16_t value = 0; \ std::from_chars(cond.data(), cond.data() + cond.size(), value); \ predicate = new PREDICATE<int16_t>(index, value, opposite); \ break; \ } \ case OLAP_FIELD_TYPE_INT: { \ int32_t value = 0; \ std::from_chars(cond.data(), cond.data() + cond.size(), value); \ predicate = new PREDICATE<int32_t>(index, value, opposite); \ break; \ } \ case OLAP_FIELD_TYPE_BIGINT: { \ int64_t value = 0; \ std::from_chars(cond.data(), cond.data() + cond.size(), value); \ predicate = new PREDICATE<int64_t>(index, value, opposite); \ break; \ } \ case OLAP_FIELD_TYPE_LARGEINT: { \ int128_t value = 0; \ StringParser::ParseResult result; \ value = StringParser::string_to_int<__int128>(cond.data(), cond.size(), &result); \ predicate = new PREDICATE<int128_t>(index, value, opposite); \ break; \ } \ case OLAP_FIELD_TYPE_DECIMAL: { \ decimal12_t value = {0, 0}; \ value.from_string(cond); \ predicate = new PREDICATE<decimal12_t>(index, value, opposite); \ break; \ } \ case OLAP_FIELD_TYPE_CHAR: { \ StringValue value; \ size_t length = std::max(static_cast<size_t>(column.length()), cond.length()); \ char* buffer = reinterpret_cast<char*>(_predicate_mem_pool->allocate(length)); \ memset(buffer, 0, length); \ memory_copy(buffer, cond.c_str(), cond.length()); \ value.len = length; \ value.ptr = buffer; \ predicate = new PREDICATE<StringValue>(index, value, opposite); \ break; \ } \ case OLAP_FIELD_TYPE_VARCHAR: \ case OLAP_FIELD_TYPE_STRING: { \ StringValue value; \ int32_t length = cond.length(); \ char* buffer = reinterpret_cast<char*>(_predicate_mem_pool->allocate(length)); \ memory_copy(buffer, cond.c_str(), length); \ value.len = length; \ value.ptr = buffer; \ predicate = new PREDICATE<StringValue>(index, value, opposite); \ break; \ } \ case OLAP_FIELD_TYPE_DATE: { \ uint24_t value = timestamp_from_date(cond); \ predicate = new PREDICATE<uint24_t>(index, value, opposite); \ break; \ } \ case OLAP_FIELD_TYPE_DATETIME: { \ uint64_t value = timestamp_from_datetime(cond); \ predicate = new PREDICATE<uint64_t>(index, value, opposite); \ break; \ } \ case OLAP_FIELD_TYPE_BOOL: { \ int32_t ivalue = 0; \ auto result = std::from_chars(cond.data(), cond.data() + cond.size(), ivalue); \ bool value = false; \ if (result.ec == std::errc()) { \ if (ivalue == 0) { \ value = false; \ } else { \ value = true; \ } \ } else { \ StringParser::ParseResult parse_result; \ value = StringParser::string_to_bool(cond.data(), cond.size(), &parse_result); \ } \ predicate = new PREDICATE<bool>(index, value, opposite); \ break; \ } \ default: \ break; \ } \ \ return predicate; \ } COMPARISON_PREDICATE_CONDITION_VALUE(eq, EqualPredicate) COMPARISON_PREDICATE_CONDITION_VALUE(ne, NotEqualPredicate) COMPARISON_PREDICATE_CONDITION_VALUE(lt, LessPredicate) COMPARISON_PREDICATE_CONDITION_VALUE(le, LessEqualPredicate) COMPARISON_PREDICATE_CONDITION_VALUE(gt, GreaterPredicate) COMPARISON_PREDICATE_CONDITION_VALUE(ge, GreaterEqualPredicate) ColumnPredicate* Reader::_parse_to_predicate( const std::pair<std::string, std::shared_ptr<IBloomFilterFuncBase>>& bloom_filter) { int32_t index = _tablet->field_index(bloom_filter.first); if (index < 0) { return nullptr; } const TabletColumn& column = _tablet->tablet_schema().column(index); return BloomFilterColumnPredicateFactory::create_column_predicate(index, bloom_filter.second, column.type()); } ColumnPredicate* Reader::_parse_to_predicate(const TCondition& condition, bool opposite) const { // TODO: not equal and not in predicate is not pushed down int32_t index = _tablet->field_index(condition.column_name); if (index < 0) { return nullptr; } const TabletColumn& column = _tablet->tablet_schema().column(index); ColumnPredicate* predicate = nullptr; if ((condition.condition_op == "*=" || condition.condition_op == "!*=" || condition.condition_op == "=" || condition.condition_op == "!=") && condition.condition_values.size() == 1) { predicate = condition.condition_op == "*=" || condition.condition_op == "=" ? _new_eq_pred(column, index, condition.condition_values[0], opposite) : _new_ne_pred(column, index, condition.condition_values[0], opposite); } else if (condition.condition_op == "<<") { predicate = _new_lt_pred(column, index, condition.condition_values[0], opposite); } else if (condition.condition_op == "<=") { predicate = _new_le_pred(column, index, condition.condition_values[0], opposite); } else if (condition.condition_op == ">>") { predicate = _new_gt_pred(column, index, condition.condition_values[0], opposite); } else if (condition.condition_op == ">=") { predicate = _new_ge_pred(column, index, condition.condition_values[0], opposite); } else if ((condition.condition_op == "*=" || condition.condition_op == "!*=") && condition.condition_values.size() > 1) { switch (column.type()) { case OLAP_FIELD_TYPE_TINYINT: { phmap::flat_hash_set<int8_t> values; int8_t value = 0; for (auto& cond_val : condition.condition_values) { std::from_chars(cond_val.data(), cond_val.data() + cond_val.size(), value); values.insert(value); } if (condition.condition_op == "*=") { predicate = new InListPredicate<int8_t>(index, std::move(values), opposite); } else { predicate = new NotInListPredicate<int8_t>(index, std::move(values), opposite); } break; } case OLAP_FIELD_TYPE_SMALLINT: { phmap::flat_hash_set<int16_t> values; int16_t value = 0; for (auto& cond_val : condition.condition_values) { std::from_chars(cond_val.data(), cond_val.data() + cond_val.size(), value); values.insert(value); } if (condition.condition_op == "*=") { predicate = new InListPredicate<int16_t>(index, std::move(values), opposite); } else { predicate = new NotInListPredicate<int16_t>(index, std::move(values), opposite); } break; } case OLAP_FIELD_TYPE_INT: { phmap::flat_hash_set<int32_t> values; int32_t value = 0; for (auto& cond_val : condition.condition_values) { std::from_chars(cond_val.data(), cond_val.data() + cond_val.size(), value); values.insert(value); } if (condition.condition_op == "*=") { predicate = new InListPredicate<int32_t>(index, std::move(values), opposite); } else { predicate = new NotInListPredicate<int32_t>(index, std::move(values), opposite); } break; } case OLAP_FIELD_TYPE_BIGINT: { phmap::flat_hash_set<int64_t> values; int64_t value = 0; for (auto& cond_val : condition.condition_values) { std::from_chars(cond_val.data(), cond_val.data() + cond_val.size(), value); values.insert(value); } if (condition.condition_op == "*=") { predicate = new InListPredicate<int64_t>(index, std::move(values), opposite); } else { predicate = new NotInListPredicate<int64_t>(index, std::move(values), opposite); } break; } case OLAP_FIELD_TYPE_LARGEINT: { phmap::flat_hash_set<int128_t> values; int128_t value = 0; StringParser::ParseResult result; for (auto& cond_val : condition.condition_values) { value = StringParser::string_to_int<__int128>(cond_val.c_str(), cond_val.size(), &result); values.insert(value); } if (condition.condition_op == "*=") { predicate = new InListPredicate<int128_t>(index, std::move(values), opposite); } else { predicate = new NotInListPredicate<int128_t>(index, std::move(values), opposite); } break; } case OLAP_FIELD_TYPE_DECIMAL: { phmap::flat_hash_set<decimal12_t> values; for (auto& cond_val : condition.condition_values) { decimal12_t value = {0, 0}; value.from_string(cond_val); values.insert(value); } if (condition.condition_op == "*=") { predicate = new InListPredicate<decimal12_t>(index, std::move(values), opposite); } else { predicate = new NotInListPredicate<decimal12_t>(index, std::move(values), opposite); } break; } case OLAP_FIELD_TYPE_CHAR: { phmap::flat_hash_set<StringValue> values; for (auto& cond_val : condition.condition_values) { StringValue value; size_t length = std::max(static_cast<size_t>(column.length()), cond_val.length()); char* buffer = reinterpret_cast<char*>(_predicate_mem_pool->allocate(length)); memset(buffer, 0, length); memory_copy(buffer, cond_val.c_str(), cond_val.length()); value.len = length; value.ptr = buffer; values.insert(value); } if (condition.condition_op == "*=") { predicate = new InListPredicate<StringValue>(index, std::move(values), opposite); } else { predicate = new NotInListPredicate<StringValue>(index, std::move(values), opposite); } break; } case OLAP_FIELD_TYPE_VARCHAR: case OLAP_FIELD_TYPE_STRING:{ phmap::flat_hash_set<StringValue> values; for (auto& cond_val : condition.condition_values) { StringValue value; int32_t length = cond_val.length(); char* buffer = reinterpret_cast<char*>(_predicate_mem_pool->allocate(length)); memory_copy(buffer, cond_val.c_str(), length); value.len = length; value.ptr = buffer; values.insert(value); } if (condition.condition_op == "*=") { predicate = new InListPredicate<StringValue>(index, std::move(values), opposite); } else { predicate = new NotInListPredicate<StringValue>(index, std::move(values), opposite); } break; } case OLAP_FIELD_TYPE_DATE: { phmap::flat_hash_set<uint24_t> values; for (auto& cond_val : condition.condition_values) { uint24_t value = timestamp_from_date(cond_val); values.insert(value); } if (condition.condition_op == "*=") { predicate = new InListPredicate<uint24_t>(index, std::move(values), opposite); } else { predicate = new NotInListPredicate<uint24_t>(index, std::move(values), opposite); } break; } case OLAP_FIELD_TYPE_DATETIME: { phmap::flat_hash_set<uint64_t> values; for (auto& cond_val : condition.condition_values) { uint64_t value = timestamp_from_datetime(cond_val); values.insert(value); } if (condition.condition_op == "*=") { predicate = new InListPredicate<uint64_t>(index, std::move(values), opposite); } else { predicate = new NotInListPredicate<uint64_t>(index, std::move(values), opposite); } break; } // OLAP_FIELD_TYPE_BOOL is not valid in this case. default: break; } } else if (boost::to_lower_copy(condition.condition_op) == "is") { predicate = new NullPredicate( index, boost::to_lower_copy(condition.condition_values[0]) == "null", opposite); } return predicate; } void Reader::_init_load_bf_columns(const ReaderParams& read_params) { _init_load_bf_columns(read_params, &_conditions, &_load_bf_columns); _init_load_bf_columns(read_params, &_all_conditions, &_load_bf_all_columns); } void Reader::_init_load_bf_columns(const ReaderParams& read_params, Conditions* conditions, std::set<uint32_t>* load_bf_columns) { // add all columns with condition to load_bf_columns for (const auto& cond_column : conditions->columns()) { if (!_tablet->tablet_schema().column(cond_column.first).is_bf_column()) { continue; } for (const auto& cond : cond_column.second->conds()) { if (cond->op == OP_EQ || (cond->op == OP_IN && cond->operand_set.size() < MAX_OP_IN_FIELD_NUM)) { load_bf_columns->insert(cond_column.first); } } } // remove columns which have same value between start_key and end_key int min_scan_key_len = _tablet->tablet_schema().num_columns(); for (const auto& start_key : read_params.start_key) { min_scan_key_len = std::min(min_scan_key_len, static_cast<int>(start_key.size())); } for (const auto& end_key : read_params.end_key) { min_scan_key_len = std::min(min_scan_key_len, static_cast<int>(end_key.size())); } int max_equal_index = -1; for (int i = 0; i < read_params.start_key.size(); ++i) { int j = 0; for (; j < min_scan_key_len; ++j) { if (read_params.start_key[i].get_value(j) != read_params.end_key[i].get_value(j)) { break; } } if (max_equal_index < j - 1) { max_equal_index = j - 1; } } for (int i = 0; i < max_equal_index; ++i) { load_bf_columns->erase(i); } // remove the max_equal_index column when it's not varchar // or longer than number of short key fields if (max_equal_index == -1) { return; } FieldType type = _tablet->tablet_schema().column(max_equal_index).type(); if ((type != OLAP_FIELD_TYPE_VARCHAR && type != OLAP_FIELD_TYPE_STRING)|| max_equal_index + 1 > _tablet->num_short_key_columns()) { load_bf_columns->erase(max_equal_index); } } OLAPStatus Reader::_init_delete_condition(const ReaderParams& read_params) { if (read_params.reader_type == READER_CUMULATIVE_COMPACTION) { return OLAP_SUCCESS; } _tablet->obtain_header_rdlock(); OLAPStatus ret = _delete_handler.init(_tablet->tablet_schema(), _tablet->delete_predicates(), read_params.version.second, this); _tablet->release_header_lock(); if (read_params.reader_type == READER_BASE_COMPACTION) { _filter_delete = true; } return ret; } } // namespace doris
46.304046
135
0.521684
spaces-X
b4059cf3bbff0376086ece948f66bdf87f3b2a6e
5,542
hpp
C++
DFNs/StereoReconstruction/ScanlineOptimization.hpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
7
2019-02-26T15:09:50.000Z
2021-09-30T07:39:01.000Z
DFNs/StereoReconstruction/ScanlineOptimization.hpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
null
null
null
DFNs/StereoReconstruction/ScanlineOptimization.hpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
1
2020-12-06T12:09:05.000Z
2020-12-06T12:09:05.000Z
/** * @author Alessandro Bianco */ /** * @addtogroup DFNs * @{ */ #ifndef STEREORECONSTRUCTION_SCANLINEOPTIMIZATION_HPP #define STEREORECONSTRUCTION_SCANLINEOPTIMIZATION_HPP #include "StereoReconstructionInterface.hpp" #include <Types/CPP/PointCloud.hpp> #include <Types/CPP/Frame.hpp> #include <Helpers/ParametersListHelper.hpp> #include <opencv2/core/core.hpp> #include <pcl/point_cloud.h> #include <pcl/point_types.h> namespace CDFF { namespace DFN { namespace StereoReconstruction { /** * Scene reconstruction (as a 3D pointcloud) from 2D stereo images, using * the Adaptive-Cost 2-Pass Scanline Optimization disparity mapping * algorithm (by Tombari). * * Processing steps: (i) conversion of the images to PCL representation, * (ii) computation of a disparity map using Tombari's algorithm, (iii) * scene reconstruction based on the disparity map using a reprojection * algorithm, (iv) downsampling of the generated pointcloud. * * @param costAggregationRadius * @param spatialBandwidth * @param colorBandwidth * @param weakSmoothnessPenalty * @param strongSmoothnessPenalty * * @param matchingOptionsSet.numberOfDisparities * number of detected disparity intervals * @param matchingOptionsSet.horizontalOffset * @param matchingOptionsSet.ratioFilter * @param matchingOptionsSet.peakFilter * @param matchingOptionsSet.usePreprocessing * @param matchingOptionsSet.useLeftRightConsistencyCheck * @param matchingOptionsSet.leftRightConsistencyThreshold * * @param pointCloudSamplingDensity * downsampling ratio: a number between 0 and 1 that describes how * much downsampling of the generated pointcloud is desired. The * pointcloud is subsampled at positions that are multiples of n, * where n = 1/pointCloudSamplingDensity. * * @param stereoCameraParameters * camera parameters in the form of the focal length and principal * point of the left camera and the distance between the two cameras: * the parameters to use to provide this information are called * LeftFocalLength, LeftPrinciplePointX, LeftPrinciplePointY, and * Baseline, respectively * * @param reconstructionSpace * a bounding box for the reconstructed scene, provided via * parameters called LimitX, LimitY, LimitZ. A reconstructed point * of coordinates (x,y,z) is accepted into the pointcloud if * -LimitX <= x <= LimitX, -LimitY <= y <= LimitY, 0 < z <= LimitZ. * * @reference The algorithm is adapted from Liang Wang, Miao Liao, Minglun * Gong, Ruigang Yang, and David Nister (2006), "High Quality * Real-Time Stereo using Adaptive Cost Aggregation and Dynamic * Programming", Third IEEE International Symposium on 3D Data * Processing, Visualization, and Transmission, 798-805. */ class ScanlineOptimization : public StereoReconstructionInterface { public: ScanlineOptimization(); virtual ~ScanlineOptimization(); virtual void configure() override; virtual void process() override; private: static const float EPSILON; //DFN Parameters typedef pcl::PointCloud<pcl::RGB> PclImage; typedef pcl::PointCloud<pcl::RGB>::Ptr PclImagePtr; typedef pcl::PointCloud<pcl::RGB>::ConstPtr PclImageConstPtr; typedef pcl::PointCloud<pcl::PointXYZ> PclPointCloud; typedef pcl::PointCloud<pcl::PointXYZ>::Ptr PclPointCloudPtr; typedef pcl::PointCloud<pcl::PointXYZ>::ConstPtr PclPointCloudConstPtr; struct ReconstructionSpace { float limitX; float limitY; float limitZ; }; struct CameraParameters { float leftPrinciplePointX; float leftPrinciplePointY; float leftFocalLength; float baseline; }; struct MatchingOptionsSet { int numberOfDisparities; int horizontalOffset; int ratioFilter; int peakFilter; bool usePreprocessing; bool useLeftRightConsistencyCheck; int leftRightConsistencyThreshold; }; struct ScanlineOptimizationOptionsSet { int costAggregationRadius; int spatialBandwidth; int colorBandwidth; int strongSmoothnessPenalty; int weakSmoothnessPenalty; float pointCloudSamplingDensity; float voxelGridLeafSize; MatchingOptionsSet matchingOptionsSet; CameraParameters cameraParameters; ReconstructionSpace reconstructionSpace; }; Helpers::ParametersListHelper parametersHelper; ScanlineOptimizationOptionsSet parameters; static const ScanlineOptimizationOptionsSet DEFAULT_PARAMETERS; //Type conversion methods PclImagePtr Convert(FrameWrapper::FrameConstPtr frame); PointCloudWrapper::PointCloudConstPtr SampleCloud(PclPointCloudConstPtr pointCloud); PointCloudWrapper::PointCloudConstPtr SampleCloudWithPeriodicSampling(PclPointCloudConstPtr pointCloud); PointCloudWrapper::PointCloudConstPtr SampleCloudWithVoxelGrid(PclPointCloudConstPtr pointCloud); cv::Mat PclImageToCvMatrix(PclImagePtr pclImage); //Core computation methods PclPointCloudPtr ComputePointCloud(PclImagePtr leftImage, PclImagePtr rightImage); //Input Validation methods void ValidateParameters(); //Testing methods for visualizing intermediate disparity map output. #ifdef TESTING #define SAVE_DISPARITY_MATRIX(visualMap) disparityMatrix = PclImageToCvMatrix(visualMap); #else #define SAVE_DISPARITY_MATRIX(visualMap) #endif }; } } } #endif // STEREORECONSTRUCTION_SCANLINEOPTIMIZATION_HPP /** @} */
32.034682
107
0.746481
H2020-InFuse
b4063a6084a2e2804dc5a3f28c50332ac508920c
1,229
cpp
C++
QmlStream/AvLib/Common/AvCommon.cpp
milclo39/QtTools
41463299799fc74d2691939e85b52c02a30ad9e6
[ "Apache-2.0" ]
null
null
null
QmlStream/AvLib/Common/AvCommon.cpp
milclo39/QtTools
41463299799fc74d2691939e85b52c02a30ad9e6
[ "Apache-2.0" ]
null
null
null
QmlStream/AvLib/Common/AvCommon.cpp
milclo39/QtTools
41463299799fc74d2691939e85b52c02a30ad9e6
[ "Apache-2.0" ]
null
null
null
//--------------------------------------------------------------------------------// /*! @file AvCommon.cpp @brief libAvライブラリ共通クラス @author 大橋 */ //--------------------------------------------------------------------------------// #include "../AvCommon.h" #define __STDC_CONSTANT_MACROS #ifdef _STDINT_H #undef _STDINT_H #endif extern "C"{ #include <libavcodec/avcodec.h> } //--------------------------------------------------------------------------------// /*! @brief コンストラクタ */ //--------------------------------------------------------------------------------// ClAvImage::ClAvImage() { m_dDuration = 0; } //--------------------------------------------------------------------------------// //--------------------------------------------------------------------------------// /*! @brief コンストラクタ @param[in] pFrame : フレームデータ @param[in] dDuration : 画像表示時間(msec) */ //--------------------------------------------------------------------------------// ClAvImage::ClAvImage(AVFrame *pFrame, qreal dDuration) { m_img = QImage(pFrame->data[0], pFrame->width, pFrame->height, QImage::Format_RGB888).copy(); m_dDuration = dDuration; } //--------------------------------------------------------------------------------//
28.581395
94
0.313263
milclo39
b40aa8ff2d0280f6a0f3c399759b76a8e06f84e2
460
hpp
C++
MainBrain/test/ModelTest/ButtonTest/ButtonTest.hpp
smit-happens/YCP_EVOS
cecfa8aaa3c73945106786c44aa78d4fe872e3c3
[ "MIT" ]
10
2017-07-30T21:26:32.000Z
2021-05-04T14:33:29.000Z
MainBrain/test/ModelTest/ButtonTest/ButtonTest.hpp
smit-happens/YCP_EVOS
cecfa8aaa3c73945106786c44aa78d4fe872e3c3
[ "MIT" ]
122
2017-07-30T15:55:55.000Z
2019-05-19T20:29:13.000Z
MainBrain/test/ModelTest/ButtonTest/ButtonTest.hpp
smit-happens/YCP_EVOS
cecfa8aaa3c73945106786c44aa78d4fe872e3c3
[ "MIT" ]
3
2018-03-10T20:01:10.000Z
2019-06-07T18:02:38.000Z
/** A one line description of the class. * * #include "ButtonTest.hpp" * Created 3-12-18 By: Smitty * * A longer description. */ #ifndef BUTTONTEST_HPP #define BUTTONTEST_HPP #include "../BaseModelTest/BaseModelTest.hpp" class ButtonTest : public BaseModelTest { public: ButtonTest(void); ~ButtonTest(void); void update(void); String getName(void); int getState(void); void setState(void); }; #endif //BUTTONTEST_HPP
14.375
45
0.678261
smit-happens
b40afe568a853447158e863d9ea060df8fe564e8
4,076
cpp
C++
cdn/src/v20180606/model/QnPrivateAccess.cpp
TencentCloud/tencentcloud-sdk-cpp-intl-en
752c031f5ad2c96868183c5931eae3a42dd5ae6c
[ "Apache-2.0" ]
1
2022-01-27T09:27:34.000Z
2022-01-27T09:27:34.000Z
cdn/src/v20180606/model/QnPrivateAccess.cpp
TencentCloud/tencentcloud-sdk-cpp-intl-en
752c031f5ad2c96868183c5931eae3a42dd5ae6c
[ "Apache-2.0" ]
null
null
null
cdn/src/v20180606/model/QnPrivateAccess.cpp
TencentCloud/tencentcloud-sdk-cpp-intl-en
752c031f5ad2c96868183c5931eae3a42dd5ae6c
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/cdn/v20180606/model/QnPrivateAccess.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cdn::V20180606::Model; using namespace std; QnPrivateAccess::QnPrivateAccess() : m_switchHasBeenSet(false), m_accessKeyHasBeenSet(false), m_secretKeyHasBeenSet(false) { } CoreInternalOutcome QnPrivateAccess::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Switch") && !value["Switch"].IsNull()) { if (!value["Switch"].IsString()) { return CoreInternalOutcome(Core::Error("response `QnPrivateAccess.Switch` IsString=false incorrectly").SetRequestId(requestId)); } m_switch = string(value["Switch"].GetString()); m_switchHasBeenSet = true; } if (value.HasMember("AccessKey") && !value["AccessKey"].IsNull()) { if (!value["AccessKey"].IsString()) { return CoreInternalOutcome(Core::Error("response `QnPrivateAccess.AccessKey` IsString=false incorrectly").SetRequestId(requestId)); } m_accessKey = string(value["AccessKey"].GetString()); m_accessKeyHasBeenSet = true; } if (value.HasMember("SecretKey") && !value["SecretKey"].IsNull()) { if (!value["SecretKey"].IsString()) { return CoreInternalOutcome(Core::Error("response `QnPrivateAccess.SecretKey` IsString=false incorrectly").SetRequestId(requestId)); } m_secretKey = string(value["SecretKey"].GetString()); m_secretKeyHasBeenSet = true; } return CoreInternalOutcome(true); } void QnPrivateAccess::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_switchHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Switch"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_switch.c_str(), allocator).Move(), allocator); } if (m_accessKeyHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AccessKey"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_accessKey.c_str(), allocator).Move(), allocator); } if (m_secretKeyHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SecretKey"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_secretKey.c_str(), allocator).Move(), allocator); } } string QnPrivateAccess::GetSwitch() const { return m_switch; } void QnPrivateAccess::SetSwitch(const string& _switch) { m_switch = _switch; m_switchHasBeenSet = true; } bool QnPrivateAccess::SwitchHasBeenSet() const { return m_switchHasBeenSet; } string QnPrivateAccess::GetAccessKey() const { return m_accessKey; } void QnPrivateAccess::SetAccessKey(const string& _accessKey) { m_accessKey = _accessKey; m_accessKeyHasBeenSet = true; } bool QnPrivateAccess::AccessKeyHasBeenSet() const { return m_accessKeyHasBeenSet; } string QnPrivateAccess::GetSecretKey() const { return m_secretKey; } void QnPrivateAccess::SetSecretKey(const string& _secretKey) { m_secretKey = _secretKey; m_secretKeyHasBeenSet = true; } bool QnPrivateAccess::SecretKeyHasBeenSet() const { return m_secretKeyHasBeenSet; }
27.727891
143
0.692591
TencentCloud
b40ce6f2a657d35e764164dc09ccee362752e54d
1,263
hpp
C++
sim_algorithm/b_tree.hpp
pachicobue/CacheObliviousAlgorithms
db6e5f19c708d83208206091ae44cd6d7c71c4e0
[ "Unlicense" ]
null
null
null
sim_algorithm/b_tree.hpp
pachicobue/CacheObliviousAlgorithms
db6e5f19c708d83208206091ae44cd6d7c71c4e0
[ "Unlicense" ]
null
null
null
sim_algorithm/b_tree.hpp
pachicobue/CacheObliviousAlgorithms
db6e5f19c708d83208206091ae44cd6d7c71c4e0
[ "Unlicense" ]
null
null
null
#pragma once /** * @file b_tree.hpp * @brief B-木 */ #include <memory> #include "config.hpp" #include "simulator/disk_variable.hpp" /** * @brief B-木 * @details Cache Awareなデータ構造 * @note * 中間ノードは以下のデータを持つ (根のキー数はK-1未満でもOK + 葉のsonsは空) * - keys:k個のキー (キー数kは K-1 <= k <= 2K-1) * - sons:k+1個の子ノード * * さらに探索木としての性質として以下が成立している * - keysは昇順 * - sons[i]に含まれるキーは、keys[i-1]以上&keys[i]未満 */ class b_tree { struct node_t { node_t() = default; std::vector<disk_var<data_t>> keys{}; std::vector<disk_var<std::shared_ptr<node_t>>> sons{}; disk_var<bool> leaf{false}; }; public: /** * @brief コンストラクタ * @param K[in] キー数に関する定数 */ b_tree(const std::size_t K_); /** * @brief コンストラクタ * @param K[in] キー数に関する定数 * @param datas[in] 初期データ */ b_tree(const std::vector<data_t>& datas, const std::size_t K_); /** * @brief 挿入 * @param key[in] キー */ void insert(const data_t key); /** * @brief LowerBound * @param key[in] キー */ data_t lower_bound(const data_t key) const; using node_t = node_t; using ptr_t = std::shared_ptr<node_t>; std::size_t K; private: void illegal_insert(const data_t key); ptr_t m_root; };
19.136364
67
0.585115
pachicobue
b40dcafc5aed4211d2d4a3cd395cb8b1b74a10b6
2,057
cpp
C++
modules/segmentation/src/segmenter_organized_connected_component.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
2
2021-02-22T11:36:33.000Z
2021-07-20T11:31:08.000Z
modules/segmentation/src/segmenter_organized_connected_component.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
null
null
null
modules/segmentation/src/segmenter_organized_connected_component.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
3
2018-10-19T10:39:23.000Z
2021-04-07T13:39:03.000Z
#include <v4r/segmentation/plane_utils.h> #include <v4r/segmentation/segmenter_organized_connected_component.h> #include <pcl/common/angles.h> #include <pcl/pcl_config.h> #include <pcl/segmentation/euclidean_cluster_comparator.h> #include <pcl/segmentation/organized_connected_component_segmentation.h> #include <pcl/impl/instantiate.hpp> namespace v4r { template <typename PointT> void OrganizedConnectedComponentSegmenter<PointT>::segment() { clusters_.clear(); pcl::PointCloud<pcl::Label>::Ptr labels(new pcl::PointCloud<pcl::Label>); labels->points.resize(scene_->points.size()); for (pcl::Label &p : labels->points) p.label = 1; #if PCL_VERSION_COMPARE(<=, 1, 8, 1) auto euclidean_cluster_comp = boost::make_shared<pcl::EuclideanClusterComparator<PointT, pcl::Normal, pcl::Label>>(); euclidean_cluster_comp->setAngularThreshold(pcl::deg2rad(param_.angular_threshold_deg_)); std::vector<bool> exclude_labels(scene_->points.size(), false); euclidean_cluster_comp->setExcludeLabels(exclude_labels); #else auto euclidean_cluster_comp = boost::make_shared<pcl::EuclideanClusterComparator<PointT, pcl::Label>>(); #endif euclidean_cluster_comp->setInputCloud(scene_); euclidean_cluster_comp->setLabels(labels); euclidean_cluster_comp->setDistanceThreshold(param_.distance_threshold_, true); pcl::PointCloud<pcl::Label> euclidean_labels; std::vector<pcl::PointIndices> euclidean_label_indices; pcl::OrganizedConnectedComponentSegmentation<PointT, pcl::Label> seg(euclidean_cluster_comp); seg.setInputCloud(scene_); seg.segment(euclidean_labels, euclidean_label_indices); for (size_t i = 0; i < euclidean_label_indices.size(); i++) { if (euclidean_label_indices[i].indices.size() >= param_.min_cluster_size_) clusters_.push_back(euclidean_label_indices[i].indices); } } #define PCL_INSTANTIATE_OrganizedConnectedComponentSegmenter(T) \ template class V4R_EXPORTS OrganizedConnectedComponentSegmenter<T>; PCL_INSTANTIATE(OrganizedConnectedComponentSegmenter, PCL_XYZ_POINT_TYPES) } // namespace v4r
41.979592
119
0.792902
v4r-tuwien
b40df7bdec0f3905c976fa4bf85430ae073ddb6c
116
cpp
C++
cmake_tutorials/01-basic/C-static-library/src/main.cpp
walkacross/cpp_tutorials
184dd674a4861b8f69eb795c59012d4d2a97eedc
[ "Apache-2.0" ]
1
2019-03-14T18:43:51.000Z
2019-03-14T18:43:51.000Z
cmake_tutorials/01-basic/C-static-library/src/main.cpp
walkacross/cpp_tutorials
184dd674a4861b8f69eb795c59012d4d2a97eedc
[ "Apache-2.0" ]
null
null
null
cmake_tutorials/01-basic/C-static-library/src/main.cpp
walkacross/cpp_tutorials
184dd674a4861b8f69eb795c59012d4d2a97eedc
[ "Apache-2.0" ]
null
null
null
#include "static/Hello.h" int main(int argc, char* argv[]) { Hello hi_obj; hi_obj.print(); return 0; }
12.888889
32
0.603448
walkacross
b40e7f9938f691f32bb44b53e04392a9a9ef413f
6,967
cpp
C++
samples/game/Engine.cpp
Admer456/FoxGLBox
6717902d102c929e565b3237753d4f918cf83ab7
[ "MIT" ]
null
null
null
samples/game/Engine.cpp
Admer456/FoxGLBox
6717902d102c929e565b3237753d4f918cf83ab7
[ "MIT" ]
null
null
null
samples/game/Engine.cpp
Admer456/FoxGLBox
6717902d102c929e565b3237753d4f918cf83ab7
[ "MIT" ]
null
null
null
#include "IEngine.hpp" #include "Vector.hpp" #include "IRenderWorld.hpp" #include "GameEntity.hpp" #include <iostream> #include <chrono> #include "SDL.h" #include "SDL_opengl.h" #include "glm/gtc/matrix_transform.hpp" #include "Engine.hpp" namespace chrono = std::chrono; IEngine* IEngine::AllocateInstance() { return new Engine(); } void Engine::Init( const char* title, int width, int height ) { gEngine = this; // Init SDL and create a window SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS ); // Set the OpenGL context version SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 4 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 5 ); // Create the window and context window = SDL_CreateWindow( title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL ); SDL_GLContext glContext = SDL_GL_CreateContext( window ); // Initialise the render system with render init params renderSystem = foxglbox::GetRenderSystem(); RenderInitParams rip { width, height, // Resolution RenderInitParams::Renderer_OpenGL45,// OpenGL 4.5 render backend RenderInitParams::Windowing_SDL2, // SDL2 windowing glContext // OpenGL 4.5 context }; renderWorld = renderSystem->InitRenderer( rip ); windowWidth = width; windowHeight = height; // Turning on VSync here so my GPU (and yours) doesn't crash'n'burn SDL_GL_SetSwapInterval( 0 ); // Set relative mouse mode SDL_SetRelativeMouseMode( SDL_TRUE ); // Populate the world with entities CreateGameEntities(); } bool Engine::RunFrame() { auto startPoint = chrono::system_clock::now(); { SDL_Event event; while ( SDL_PollEvent( &event ) ) { if ( event.type == SDL_QUIT ) { return false; } if ( event.type == SDL_KEYDOWN ) { if ( event.key.keysym.sym == SDLK_ESCAPE ) { return false; } } } // Update all updateable entities for ( auto& ent : gameEntities ) { if ( nullptr != ent ) { if ( ent->entityFlags.canThink ) { ent->Update( frameTime ); } } } // Present the entities to the user (i.e. just update render entities) for ( auto& ent : gameEntities ) { if ( nullptr != ent ) { if ( ent->entityFlags.visible ) { ent->Present(); } } } // Render the frame! renderWorld->RenderFrame( mainView ); SDL_GL_SwapWindow( window ); } auto endPoint = chrono::system_clock::now(); auto microSeconds = chrono::duration_cast<chrono::microseconds>(endPoint - startPoint); frameTime = (microSeconds.count() / (1000.0f * 1000.0f)) * timeScale; float frameRate = 1.0f / frameTime; printf( "## Frame time: %3.2f ms\n## Frame rate: %4.1f fps\n\n", (frameTime * 1000.0f), frameRate ); return true; } void Engine::Shutdown() { for ( auto& ent : gameEntities ) { if ( nullptr != ent ) { delete ent; ent = nullptr; } } if ( nullptr != renderWorld ) { renderWorld->Shutdown(); delete renderWorld; renderWorld = nullptr; } } void Engine::Print( const char* string ) { std::cout << string; } RenderModelHandle Engine::GetModel( const char* modelPath ) { if ( nullptr == modelPath ) { return RenderHandleInvalid; } RenderModelParams modelParams{ modelPath }; return renderWorld->CreateModel( modelParams ); } void Engine::SubmitRenderView( const RenderView& view, bool isMain ) { if ( isMain ) { mainView = view; return; } } void Engine::CreateGameEntities() { using namespace Entities; for ( auto& ent : gameEntities ) { ent = nullptr; } RenderModelHandle terrainHandle = GetModel( "terrain.obj" ); RenderModelHandle amanHandle = GetModel( "aman.obj" ); // The A-Man RenderModelHandle testCoverHandle = GetModel( "test_cover.obj" ); RenderModelHandle testRockHandle = GetModel( "testrock.obj" ); // Ideally, you'd wanna load some sorta level/scene file, but I decided to keep the sample very simple CreateEntity<Prop>( fglVector::Zero, fglVector( 90.0f, 0.0f, 0.0f ), terrainHandle ); CreateEntity<Prop>( fglVector( 2.0f, 1.0f, 6.0f ), fglVector( 90.0f, 0.0f, 0.0f ), testCoverHandle ); CreateEntity<Prop>( fglVector( 2.0f, 1.0f, 2.3f ), fglVector( 90.0f, 0.0f, 0.0f ), testRockHandle ); CreateEntity<PropRotating>( fglVector( 2.0f, 0.0f, 3.0f ), fglVector::Zero, amanHandle ); CreateEntity<PropInstanced>( fglVector( 4.0f, -2.0f, 5.0f ), fglVector::Zero, testRockHandle ); CreateEntity<Player>( fglVector( -8.0f, 0.0f, 0.0f ), fglVector::Zero, 0 ); for ( auto& ent : gameEntities ) { if ( nullptr != ent ) { ent->Spawn(); } } } template<typename EntityClass> EntityClass* Engine::CreateEntity( fglVector position, fglVector angles, RenderModelHandle modelHandle ) { for ( auto& ent : gameEntities ) { if ( nullptr == ent ) { EntityClass* entity = Entities::GameEntity::Instance<EntityClass>( position, angles, modelHandle ); ent = entity; return entity; } } return nullptr; } /* Copyright (c) 2021 Admer456 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. */
31.102679
119
0.602268
Admer456
b40eec3ec4fc17178ae487d540648a9c18cd0d1b
949
hpp
C++
pogre/CameraStrategy.hpp
ValtoLibraries/PUtils
f30ebf21416654743ad2a05b14974acd27257da8
[ "MIT" ]
null
null
null
pogre/CameraStrategy.hpp
ValtoLibraries/PUtils
f30ebf21416654743ad2a05b14974acd27257da8
[ "MIT" ]
null
null
null
pogre/CameraStrategy.hpp
ValtoLibraries/PUtils
f30ebf21416654743ad2a05b14974acd27257da8
[ "MIT" ]
null
null
null
#pragma once #include <OgreInput.h> #include <OgreSceneNode.h> namespace pogre { class CameraStrategy { public: CameraStrategy(Ogre::SceneNode *camNode = nullptr) : _camNode(camNode) {} virtual ~CameraStrategy() = default; public: virtual void keyPressed(const OgreBites::KeyboardEvent &event) {} virtual void keyReleased(const OgreBites::KeyboardEvent &event) {} public: virtual void mouseMoved(const OgreBites::MouseMotionEvent &event) {} virtual void mousePressed(const OgreBites::MouseButtonEvent &event) {} virtual void mouseReleased(const OgreBites::MouseButtonEvent &event) {} public: virtual void frameRendered(const Ogre::FrameEvent &event) {} public: void setCamNode(Ogre::SceneNode *node) { _camNode = node; } Ogre::SceneNode *getCamNode() const { return _camNode; } private: Ogre::SceneNode *_camNode; }; }
28.757576
81
0.670179
ValtoLibraries
b41019ad77fa92c7d7746c17dd0c79736e53cae0
5,170
cc
C++
zircon/system/utest/debugger/crash-and-recover.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
5
2022-01-10T20:22:17.000Z
2022-01-21T20:14:17.000Z
zircon/system/utest/debugger/crash-and-recover.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
2
2021-09-19T21:55:09.000Z
2021-12-19T03:34:53.000Z
zircon/system/utest/debugger/crash-and-recover.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
1
2021-08-23T11:33:57.000Z
2021-08-23T11:33:57.000Z
// Copyright 2016 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file contains basic "crash-and-recover" test support where the inferior // crashes and then the cause of the crash is fixed in the debugger and then // the inferior is resumed. The pieces of the test are abstracted out info // this file as the test is done in a couple of places. // // The test consists of two parts: // 1) Debugger side: // Send RQST_CRASH_AND_RECOVER. // In the exception handler: // - call TestSegvPc() // - call TestMemoryOps() // - call FixInferiorSegv() // - resume the inferior // 2) Inferior side: // On receipt of RQST_CRASH_AND_RECOVER: // - call TestPrepAndSegv() // - send RESP_RECOVERED_FROM_CRASH #include "crash-and-recover.h" #include <assert.h> #include <inttypes.h> #include <lib/backtrace-request/backtrace-request.h> #include <lib/zx/thread.h> #include <link.h> #include <stdlib.h> #include <string.h> #include <zircon/process.h> #include <zircon/processargs.h> #include <zircon/syscalls.h> #include <zircon/syscalls/debug.h> #include <zircon/syscalls/exception.h> #include <zircon/syscalls/object.h> #include <zircon/syscalls/port.h> #include <zircon/threads.h> #include <atomic> #include <test-utils/test-utils.h> #include <zxtest/zxtest.h> #include "debugger.h" #include "inferior-control.h" #include "inferior.h" #include "utils.h" namespace { constexpr size_t kTestMemorySize = 8; constexpr uint8_t kTestDataAdjust = 0x10; } // namespace bool test_prep_and_segv() { uint8_t test_data[kTestMemorySize]; for (unsigned i = 0; i < sizeof(test_data); ++i) test_data[i] = static_cast<uint8_t>(i); #ifdef __x86_64__ void* segv_pc; // Note: Fuchsia is always PIC. __asm__("leaq .Lsegv_here(%%rip),%0" : "=r"(segv_pc)); printf("About to segv, pc %p\n", segv_pc); // Set r9 to point to test_data so we can easily access it // from the parent process. Likewise set r10 to segv_pc // so the parent process can verify it matches the fault PC. __asm__( "\ movq %[zero],%%r8\n\ movq %[test_data],%%r9\n\ movq %[pc],%%r10\n\ .Lsegv_here:\n\ movq (%%r8),%%rax\ " : : [zero] "g"(0), [test_data] "g"(test_data), [pc] "g"(segv_pc) : "rax", "r8", "r9", "r10"); #endif #ifdef __aarch64__ void* segv_pc; // Note: Fuchsia is always PIC. __asm__( "adrp %0, .Lsegv_here\n" "add %0, %0, :lo12:.Lsegv_here" : "=r"(segv_pc)); printf("About to segv, pc %p\n", segv_pc); // Set r9 to point to test_data so we can easily access it // from the parent process. Likewise set r10 to segv_pc // so the parent process can verify it matches the fault PC. __asm__( "\ mov x8,xzr\n\ mov x9,%[test_data]\n\ mov x10,%[pc]\n\ .Lsegv_here:\n\ ldr x0,[x8]\ " : : [test_data] "r"(test_data), [pc] "r"(segv_pc) : "x0", "x8", "x9", "x10"); #endif // On resumption test_data should have had kTestDataAdjust added to each element. // Note: This is the inferior process, it's not running under the test harness. for (unsigned i = 0; i < sizeof(test_data); ++i) { if (test_data[i] != i + kTestDataAdjust) { printf("TestPrepAndSegv: bad data on resumption, test_data[%u] = 0x%x\n", i, test_data[i]); return false; } } printf("Inferior successfully resumed!\n"); return true; } void test_segv_pc(zx_handle_t thread) { zx_thread_state_general_regs_t regs; read_inferior_gregs(thread, &regs); #if defined(__x86_64__) ASSERT_EQ(regs.rip, regs.r10, "fault PC does not match r10"); #elif defined(__aarch64__) ASSERT_EQ(regs.pc, regs.r[10], "fault PC does not match x10"); #endif } void test_memory_ops(zx_handle_t inferior, zx_handle_t thread) { uint64_t test_data_addr = 0; uint8_t test_data[kTestMemorySize]; zx_thread_state_general_regs_t regs; read_inferior_gregs(thread, &regs); #if defined(__x86_64__) test_data_addr = regs.r9; #elif defined(__aarch64__) test_data_addr = regs.r[9]; #endif size_t size = read_inferior_memory(inferior, test_data_addr, test_data, sizeof(test_data)); EXPECT_EQ(size, sizeof(test_data), "read_inferior_memory: short read"); for (unsigned i = 0; i < sizeof(test_data); ++i) { EXPECT_EQ(test_data[i], i, "test_memory_ops"); } for (unsigned i = 0; i < sizeof(test_data); ++i) { test_data[i] = static_cast<uint8_t>(test_data[i] + kTestDataAdjust); } size = write_inferior_memory(inferior, test_data_addr, test_data, sizeof(test_data)); EXPECT_EQ(size, sizeof(test_data), "write_inferior_memory: short write"); // Note: Verification of the write is done in the inferior. } void fix_inferior_segv(zx_handle_t thread) { printf("Fixing inferior segv\n"); // The segv was because r8 == 0, change it to a usable value. See TestPrepAndSegv. zx_thread_state_general_regs_t regs; read_inferior_gregs(thread, &regs); #if defined(__x86_64__) regs.r8 = regs.rsp; #elif defined(__aarch64__) regs.r[8] = regs.sp; #endif write_inferior_gregs(thread, &regs); }
29.044944
97
0.681431
allansrc
b4128eded06ac8e8acf2d51e8653792f3e99b3dc
3,093
cpp
C++
ace/tao/tao_idl/be/be_visitor_operation/base_proxy_impl_ch.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
ace/tao/tao_idl/be/be_visitor_operation/base_proxy_impl_ch.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
ace/tao/tao_idl/be/be_visitor_operation/base_proxy_impl_ch.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
// base_proxy_impl_ch.cpp,v 1.2 2001/05/15 15:48:35 parsons Exp #include "idl.h" #include "idl_extern.h" #include "be.h" #include "be_visitor_operation.h" ACE_RCSID(be_visitor_operation, x_proxy_impl_xh, "base_proxy_impl_ch.cpp,v 1.2 2001/05/15 15:48:35 parsons Exp") be_visitor_operation_base_proxy_impl_ch::be_visitor_operation_base_proxy_impl_ch (be_visitor_context *ctx) : be_visitor_scope (ctx) { } be_visitor_operation_base_proxy_impl_ch::~be_visitor_operation_base_proxy_impl_ch (void) { } int be_visitor_operation_base_proxy_impl_ch::visit_operation (be_operation *node) { TAO_OutStream *os; // output stream be_type *bt; // type node representing the return type os = this->ctx_->stream (); this->ctx_->node (node); // save the node // os->indent (); // start with the current indentation level // every operation is declared virtual in the client code *os << "virtual "; // STEP I: generate the return type bt = be_type::narrow_from_decl (node->return_type ()); if (!bt) { ACE_ERROR_RETURN ((LM_ERROR, "(%N:%l) be_visitor_operation_sh::" "visit_operation - " "Bad return type\n"), -1); } // grab the right visitor to generate the return type be_visitor_context ctx (*this->ctx_); ctx.state (TAO_CodeGen::TAO_OPERATION_RETTYPE_OTHERS); be_visitor *visitor = tao_cg->make_visitor (&ctx); if (!visitor) { ACE_ERROR_RETURN ((LM_ERROR, "be_visitor_operation_sh::" "visit_operation - " "Bad visitor to return type\n"), -1); } if (bt->accept (visitor) == -1) { delete visitor; ACE_ERROR_RETURN ((LM_ERROR, "(%N:%l) be_visitor_operation_sh::" "visit_operation - " "codegen for return type failed\n"), -1); } delete visitor; // STEP 2: generate the operation name *os << " " << node->local_name (); // STEP 3: generate the argument list with the appropriate mapping. For these // we grab a visitor that generates the parameter listing ctx = *this->ctx_; ctx.state (TAO_CodeGen::TAO_OPERATION_ARGLIST_BASE_PROXY_IMPL_CH); visitor = tao_cg->make_visitor (&ctx); if (!visitor) { ACE_ERROR_RETURN ((LM_ERROR, "be_visitor_operation_sh::" "visit_operation - " "Bad visitor to return type\n"), -1); } if (node->accept (visitor) == -1) { delete visitor; ACE_ERROR_RETURN ((LM_ERROR, "(%N:%l) be_visitor_operation_sh::" "visit_operation - " "codegen for argument list failed\n"), -1); } delete visitor; return 0; }
29.740385
113
0.555448
tharindusathis
b4131c729c07e9fb420407b622a64a563ab1fec8
19,019
cpp
C++
aslam_optimizer/aslam_backend_expressions/src/EuclideanExpressionNode.cpp
chengfzy/kalibr
fe9705b380b160dc939607135f7d30efa64ea2e9
[ "BSD-4-Clause" ]
null
null
null
aslam_optimizer/aslam_backend_expressions/src/EuclideanExpressionNode.cpp
chengfzy/kalibr
fe9705b380b160dc939607135f7d30efa64ea2e9
[ "BSD-4-Clause" ]
null
null
null
aslam_optimizer/aslam_backend_expressions/src/EuclideanExpressionNode.cpp
chengfzy/kalibr
fe9705b380b160dc939607135f7d30efa64ea2e9
[ "BSD-4-Clause" ]
null
null
null
#include <aslam/backend/EuclideanExpressionNode.hpp> #include <aslam/backend/HomogeneousExpressionNode.hpp> #include <aslam/backend/VectorExpressionNode.hpp> #include <sm/kinematics/homogeneous_coordinates.hpp> #include <sm/kinematics/rotations.hpp> namespace aslam { namespace backend { EuclideanExpressionNode::EuclideanExpressionNode() {} EuclideanExpressionNode::~EuclideanExpressionNode() {} /// \brief Evaluate the euclidean matrix. Eigen::Vector3d EuclideanExpressionNode::toEuclidean() const { return toEuclideanImplementation(); } /// \brief Evaluate the Jacobians void EuclideanExpressionNode::evaluateJacobians(JacobianContainer& outJacobians) const { evaluateJacobiansImplementation(outJacobians); } /// \brief Evaluate the Jacobians and apply the chain rule. void EuclideanExpressionNode::evaluateJacobians(JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const { SM_ASSERT_EQ_DBG(Exception, applyChainRule.cols(), 3, "The chain rule matrix must have three columns"); evaluateJacobiansImplementation(outJacobians, applyChainRule); } void EuclideanExpressionNode::getDesignVariables(DesignVariable::set_t& designVariables) const { getDesignVariablesImplementation(designVariables); } EuclideanExpressionNodeMultiply::EuclideanExpressionNodeMultiply(boost::shared_ptr<RotationExpressionNode> lhs, boost::shared_ptr<EuclideanExpressionNode> rhs) : _lhs(lhs), _rhs(rhs) { _C_lhs = _lhs->toRotationMatrix(); _p_rhs = _rhs->toEuclidean(); } EuclideanExpressionNodeMultiply::~EuclideanExpressionNodeMultiply() {} void EuclideanExpressionNodeMultiply::getDesignVariablesImplementation(DesignVariable::set_t& designVariables) const { _lhs->getDesignVariables(designVariables); _rhs->getDesignVariables(designVariables); } Eigen::Vector3d EuclideanExpressionNodeMultiply::toEuclideanImplementation() const { _C_lhs = _lhs->toRotationMatrix(); _p_rhs = _rhs->toEuclidean(); return _C_lhs * _p_rhs; } void EuclideanExpressionNodeMultiply::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const { _lhs->evaluateJacobians(outJacobians, sm::kinematics::crossMx(_C_lhs * _p_rhs)); _rhs->evaluateJacobians(outJacobians, _C_lhs); } void EuclideanExpressionNodeMultiply::evaluateJacobiansImplementation(JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const { _lhs->evaluateJacobians(outJacobians, applyChainRule * sm::kinematics::crossMx(_C_lhs * _p_rhs)); _rhs->evaluateJacobians(outJacobians, applyChainRule * _C_lhs); } // ------------------------------------------------------- // ## New Class for rotations with MatrixExpressions EuclideanExpressionNodeMatrixMultiply::EuclideanExpressionNodeMatrixMultiply( boost::shared_ptr<MatrixExpressionNode> lhs, boost::shared_ptr<EuclideanExpressionNode> rhs) : _lhs(lhs), _rhs(rhs) { _A_lhs = _lhs->toMatrix3x3(); _p_rhs = _rhs->toEuclidean(); } EuclideanExpressionNodeMatrixMultiply::~EuclideanExpressionNodeMatrixMultiply() {} void EuclideanExpressionNodeMatrixMultiply::getDesignVariablesImplementation( DesignVariable::set_t& designVariables) const { _lhs->getDesignVariables(designVariables); _rhs->getDesignVariables(designVariables); } Eigen::Vector3d EuclideanExpressionNodeMatrixMultiply::toEuclideanImplementation() const { _A_lhs = _lhs->toMatrix3x3(); _p_rhs = _rhs->toEuclidean(); return _A_lhs * _p_rhs; } void EuclideanExpressionNodeMatrixMultiply::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const { Eigen::Matrix<double, 3, 9> J_full; J_full << _p_rhs(0) * Eigen::Matrix3d::Identity(), _p_rhs(1) * Eigen::Matrix3d::Identity(), _p_rhs(2) * Eigen::Matrix3d::Identity(); _lhs->evaluateJacobians(outJacobians, J_full); _rhs->evaluateJacobians(outJacobians, _A_lhs); } void EuclideanExpressionNodeMatrixMultiply::evaluateJacobiansImplementation( JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const { Eigen::Matrix<double, 3, 9> J_full; J_full << _p_rhs(0) * Eigen::Matrix3d::Identity(), _p_rhs(1) * Eigen::Matrix3d::Identity(), _p_rhs(2) * Eigen::Matrix3d::Identity(); _lhs->evaluateJacobians(outJacobians, applyChainRule * J_full); _rhs->evaluateJacobians(outJacobians, applyChainRule * _A_lhs); } // ---------------------------- EuclideanExpressionNodeCrossEuclidean::EuclideanExpressionNodeCrossEuclidean( boost::shared_ptr<EuclideanExpressionNode> lhs, boost::shared_ptr<EuclideanExpressionNode> rhs) : _lhs(lhs), _rhs(rhs) {} EuclideanExpressionNodeCrossEuclidean::~EuclideanExpressionNodeCrossEuclidean() {} void EuclideanExpressionNodeCrossEuclidean::getDesignVariablesImplementation( DesignVariable::set_t& designVariables) const { _lhs->getDesignVariables(designVariables); _rhs->getDesignVariables(designVariables); } Eigen::Vector3d EuclideanExpressionNodeCrossEuclidean::toEuclideanImplementation() const { return sm::kinematics::crossMx(_lhs->toEuclidean()) * _rhs->toEuclidean(); ; } void EuclideanExpressionNodeCrossEuclidean::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const { _lhs->evaluateJacobians(outJacobians, -sm::kinematics::crossMx(_rhs->toEuclidean())); _rhs->evaluateJacobians(outJacobians, sm::kinematics::crossMx(_lhs->toEuclidean())); } void EuclideanExpressionNodeCrossEuclidean::evaluateJacobiansImplementation( JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const { _lhs->evaluateJacobians(outJacobians, -applyChainRule * sm::kinematics::crossMx(_rhs->toEuclidean())); _rhs->evaluateJacobians(outJacobians, applyChainRule * sm::kinematics::crossMx(_lhs->toEuclidean())); } EuclideanExpressionNodeAddEuclidean::EuclideanExpressionNodeAddEuclidean(boost::shared_ptr<EuclideanExpressionNode> lhs, boost::shared_ptr<EuclideanExpressionNode> rhs) : _lhs(lhs), _rhs(rhs) {} EuclideanExpressionNodeAddEuclidean::~EuclideanExpressionNodeAddEuclidean() {} void EuclideanExpressionNodeAddEuclidean::getDesignVariablesImplementation( DesignVariable::set_t& designVariables) const { _lhs->getDesignVariables(designVariables); _rhs->getDesignVariables(designVariables); } Eigen::Vector3d EuclideanExpressionNodeAddEuclidean::toEuclideanImplementation() const { return _lhs->toEuclidean() + _rhs->toEuclidean(); } void EuclideanExpressionNodeAddEuclidean::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const { _lhs->evaluateJacobians(outJacobians); _rhs->evaluateJacobians(outJacobians); } void EuclideanExpressionNodeAddEuclidean::evaluateJacobiansImplementation(JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const { _lhs->evaluateJacobians(outJacobians, applyChainRule); _rhs->evaluateJacobians(outJacobians, applyChainRule); } EuclideanExpressionNodeSubtractEuclidean::EuclideanExpressionNodeSubtractEuclidean( boost::shared_ptr<EuclideanExpressionNode> lhs, boost::shared_ptr<EuclideanExpressionNode> rhs) : _lhs(lhs), _rhs(rhs) {} EuclideanExpressionNodeSubtractEuclidean::~EuclideanExpressionNodeSubtractEuclidean() {} void EuclideanExpressionNodeSubtractEuclidean::getDesignVariablesImplementation( DesignVariable::set_t& designVariables) const { _lhs->getDesignVariables(designVariables); _rhs->getDesignVariables(designVariables); } Eigen::Vector3d EuclideanExpressionNodeSubtractEuclidean::toEuclideanImplementation() const { return _lhs->toEuclidean() - _rhs->toEuclidean(); } void EuclideanExpressionNodeSubtractEuclidean::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const { _lhs->evaluateJacobians(outJacobians); _rhs->evaluateJacobians(outJacobians, -Eigen::Matrix3d::Identity()); } void EuclideanExpressionNodeSubtractEuclidean::evaluateJacobiansImplementation( JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const { _lhs->evaluateJacobians(outJacobians, applyChainRule); _rhs->evaluateJacobians(outJacobians, -applyChainRule); } EuclideanExpressionNodeConstant::EuclideanExpressionNodeConstant(const Eigen::Vector3d& p) : _p(p) {} EuclideanExpressionNodeConstant::~EuclideanExpressionNodeConstant() {} void EuclideanExpressionNodeConstant::getDesignVariablesImplementation( DesignVariable::set_t& /* designVariables */) const {} Eigen::Vector3d EuclideanExpressionNodeConstant::toEuclideanImplementation() const { return _p; } void EuclideanExpressionNodeConstant::evaluateJacobiansImplementation(JacobianContainer& /* outJacobians */) const {} void EuclideanExpressionNodeConstant::evaluateJacobiansImplementation( JacobianContainer& /* outJacobians */, const Eigen::MatrixXd& /* applyChainRule */) const {} EuclideanExpressionNodeSubtractVector::EuclideanExpressionNodeSubtractVector( boost::shared_ptr<EuclideanExpressionNode> lhs, const Eigen::Vector3d& rhs) : _lhs(lhs), _rhs(rhs) {} EuclideanExpressionNodeSubtractVector::~EuclideanExpressionNodeSubtractVector() {} void EuclideanExpressionNodeSubtractVector::getDesignVariablesImplementation( DesignVariable::set_t& designVariables) const { _lhs->getDesignVariables(designVariables); } Eigen::Vector3d EuclideanExpressionNodeSubtractVector::toEuclideanImplementation() const { return _lhs->toEuclidean() - _rhs; } void EuclideanExpressionNodeSubtractVector::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const { _lhs->evaluateJacobians(outJacobians); } void EuclideanExpressionNodeSubtractVector::evaluateJacobiansImplementation( JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const { _lhs->evaluateJacobians(outJacobians, applyChainRule); } EuclideanExpressionNodeNegated::EuclideanExpressionNodeNegated(boost::shared_ptr<EuclideanExpressionNode> operand) : _operand(operand) {} EuclideanExpressionNodeNegated::~EuclideanExpressionNodeNegated() {} void EuclideanExpressionNodeNegated::getDesignVariablesImplementation(DesignVariable::set_t& designVariables) const { _operand->getDesignVariables(designVariables); } Eigen::Vector3d EuclideanExpressionNodeNegated::toEuclideanImplementation() const { return -_operand->toEuclidean(); } void EuclideanExpressionNodeNegated::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const { _operand->evaluateJacobians(outJacobians, -Eigen::Matrix3d::Identity()); } void EuclideanExpressionNodeNegated::evaluateJacobiansImplementation(JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const { _operand->evaluateJacobians(outJacobians, -applyChainRule); } EuclideanExpressionNodeScalarMultiply::EuclideanExpressionNodeScalarMultiply( boost::shared_ptr<EuclideanExpressionNode> p, boost::shared_ptr<ScalarExpressionNode> s) : _p(p), _s(s) {} EuclideanExpressionNodeScalarMultiply::~EuclideanExpressionNodeScalarMultiply() {} void EuclideanExpressionNodeScalarMultiply::getDesignVariablesImplementation( DesignVariable::set_t& designVariables) const { _p->getDesignVariables(designVariables); _s->getDesignVariables(designVariables); } Eigen::Vector3d EuclideanExpressionNodeScalarMultiply::toEuclideanImplementation() const { return _p->toEuclidean() * _s->toScalar(); } void EuclideanExpressionNodeScalarMultiply::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const { _p->evaluateJacobians(outJacobians, Eigen::Matrix3d::Identity() * _s->toScalar()); _s->evaluateJacobians(outJacobians, _p->toEuclidean()); } void EuclideanExpressionNodeScalarMultiply::evaluateJacobiansImplementation( JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const { _p->evaluateJacobians(outJacobians, applyChainRule * _s->toScalar()); _s->evaluateJacobians(outJacobians, applyChainRule * _p->toEuclidean()); } VectorExpression2EuclideanExpressionAdapter::VectorExpression2EuclideanExpressionAdapter( boost::shared_ptr<VectorExpressionNode<3> > vectorExpressionNode) : _vectorExpressionNode(vectorExpressionNode) {} VectorExpression2EuclideanExpressionAdapter::~VectorExpression2EuclideanExpressionAdapter() {} void VectorExpression2EuclideanExpressionAdapter::getDesignVariablesImplementation( DesignVariable::set_t& designVariables) const { _vectorExpressionNode->getDesignVariables(designVariables); } Eigen::Vector3d VectorExpression2EuclideanExpressionAdapter::toEuclideanImplementation() const { return _vectorExpressionNode->toVector(); } void VectorExpression2EuclideanExpressionAdapter::evaluateJacobiansImplementation( JacobianContainer& outJacobians) const { _vectorExpressionNode->evaluateJacobians(outJacobians, Eigen::Matrix3d::Identity()); } void VectorExpression2EuclideanExpressionAdapter::evaluateJacobiansImplementation( JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const { _vectorExpressionNode->evaluateJacobians(outJacobians, applyChainRule * Eigen::Matrix3d::Identity()); } EuclideanExpressionNodeTranslation::EuclideanExpressionNodeTranslation( boost::shared_ptr<TransformationExpressionNode> operand) : _operand(operand) {} EuclideanExpressionNodeTranslation::~EuclideanExpressionNodeTranslation() {} Eigen::Vector3d EuclideanExpressionNodeTranslation::toEuclideanImplementation() const { return _operand->toTransformationMatrix().topRightCorner<3, 1>(); } void EuclideanExpressionNodeTranslation::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const { Eigen::MatrixXd J = Eigen::MatrixXd::Identity(3, 6); Eigen::Vector3d p = _operand->toTransformationMatrix().topRightCorner<3, 1>(); J.topRightCorner<3, 3>() = sm::kinematics::crossMx(p); _operand->evaluateJacobians(outJacobians, J); } void EuclideanExpressionNodeTranslation::evaluateJacobiansImplementation(JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const { Eigen::MatrixXd J = Eigen::MatrixXd::Identity(3, 6); Eigen::Vector3d p = _operand->toTransformationMatrix().topRightCorner<3, 1>(); J.topRightCorner<3, 3>() = sm::kinematics::crossMx(p); _operand->evaluateJacobians(outJacobians, applyChainRule * J); } void EuclideanExpressionNodeTranslation::getDesignVariablesImplementation( DesignVariable::set_t& designVariables) const { return _operand->getDesignVariables(designVariables); } EuclideanExpressionNodeRotationParameters::EuclideanExpressionNodeRotationParameters( boost::shared_ptr<RotationExpressionNode> operand, sm::kinematics::RotationalKinematics::Ptr rk) : _operand(operand), _rk(rk) {} EuclideanExpressionNodeRotationParameters::~EuclideanExpressionNodeRotationParameters() {} Eigen::Vector3d EuclideanExpressionNodeRotationParameters::toEuclideanImplementation() const { return _rk->rotationMatrixToParameters(_operand->toRotationMatrix()); } void EuclideanExpressionNodeRotationParameters::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const { Eigen::MatrixXd J = _rk->parametersToSMatrix(_rk->rotationMatrixToParameters(_operand->toRotationMatrix())).inverse(); _operand->evaluateJacobians(outJacobians, J); } void EuclideanExpressionNodeRotationParameters::evaluateJacobiansImplementation( JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const { Eigen::MatrixXd J = _rk->parametersToSMatrix(_rk->rotationMatrixToParameters(_operand->toRotationMatrix())).inverse(); _operand->evaluateJacobians(outJacobians, applyChainRule * J); } void EuclideanExpressionNodeRotationParameters::getDesignVariablesImplementation( DesignVariable::set_t& designVariables) const { return _operand->getDesignVariables(designVariables); } EuclideanExpressionNodeFromHomogeneous::EuclideanExpressionNodeFromHomogeneous( boost::shared_ptr<HomogeneousExpressionNode> root) : _root(root) {} EuclideanExpressionNodeFromHomogeneous::~EuclideanExpressionNodeFromHomogeneous() {} Eigen::Vector3d EuclideanExpressionNodeFromHomogeneous::toEuclideanImplementation() const { return sm::kinematics::fromHomogeneous(_root->toHomogeneous()); } void EuclideanExpressionNodeFromHomogeneous::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const { // Eigen::Vector3d fromHomogeneous(const Eigen::Vector4d & v, Eigen::Matrix<double,3,4> * jacobian = NULL); Eigen::Matrix<double, 3, 4> Jh; sm::kinematics::fromHomogeneous(_root->toHomogeneous(), &Jh); _root->evaluateJacobians(outJacobians, Jh); } void EuclideanExpressionNodeFromHomogeneous::evaluateJacobiansImplementation( JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const { Eigen::Matrix<double, 3, 4> Jh; sm::kinematics::fromHomogeneous(_root->toHomogeneous(), &Jh); _root->evaluateJacobians(outJacobians, applyChainRule * Jh); } void EuclideanExpressionNodeFromHomogeneous::getDesignVariablesImplementation( DesignVariable::set_t& designVariables) const { _root->getDesignVariables(designVariables); } EuclideanExpressionNodeElementwiseMultiplyEuclidean::EuclideanExpressionNodeElementwiseMultiplyEuclidean( boost::shared_ptr<EuclideanExpressionNode> lhs, boost::shared_ptr<EuclideanExpressionNode> rhs) : _lhs(lhs), _rhs(rhs) {} EuclideanExpressionNodeElementwiseMultiplyEuclidean::~EuclideanExpressionNodeElementwiseMultiplyEuclidean() {} void EuclideanExpressionNodeElementwiseMultiplyEuclidean::getDesignVariablesImplementation( DesignVariable::set_t& designVariables) const { _lhs->getDesignVariables(designVariables); _rhs->getDesignVariables(designVariables); } Eigen::Vector3d EuclideanExpressionNodeElementwiseMultiplyEuclidean::toEuclideanImplementation() const { return (_lhs->toEuclidean()).cwiseProduct(_rhs->toEuclidean()); } void EuclideanExpressionNodeElementwiseMultiplyEuclidean::evaluateJacobiansImplementation( JacobianContainer& outJacobians) const { _lhs->evaluateJacobians(outJacobians, _rhs->toEuclidean().asDiagonal()); _rhs->evaluateJacobians(outJacobians, _lhs->toEuclidean().asDiagonal()); } void EuclideanExpressionNodeElementwiseMultiplyEuclidean::evaluateJacobiansImplementation( JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const { _lhs->evaluateJacobians(outJacobians, applyChainRule * _rhs->toEuclidean().asDiagonal()); _rhs->evaluateJacobians(outJacobians, applyChainRule * _lhs->toEuclidean().asDiagonal()); } } // namespace backend } // namespace aslam
45.828916
120
0.784636
chengfzy
b4136df13a37303d5f549e6931c671aa95b8a28b
7,099
cpp
C++
ProtoRPC_UE4/Source/ProtoRPC_UE4/FHttpModuleRpc/HttpRpcRequest.cpp
fire/Grpc_UE4
b3d1246ee2c2b7e50bee7cb5f6c42366f7497e86
[ "BSD-2-Clause" ]
5
2017-02-28T00:53:52.000Z
2018-08-02T10:06:13.000Z
ProtoRPC_UE4/Source/ProtoRPC_UE4/FHttpModuleRpc/HttpRpcRequest.cpp
fire/Grpc_UE4
b3d1246ee2c2b7e50bee7cb5f6c42366f7497e86
[ "BSD-2-Clause" ]
null
null
null
ProtoRPC_UE4/Source/ProtoRPC_UE4/FHttpModuleRpc/HttpRpcRequest.cpp
fire/Grpc_UE4
b3d1246ee2c2b7e50bee7cb5f6c42366f7497e86
[ "BSD-2-Clause" ]
1
2020-10-07T07:20:25.000Z
2020-10-07T07:20:25.000Z
// Copyright 2015 Paddle Creek Games Inc. All Rights Reserved. #include "HttpRpcRequest.h" #include <google/protobuf/descriptor.h> #include <google/protobuf/message.h> #include <google/protobuf/text_format.h> #include <google/protobuf/util/json_util.h> #include <google/protobuf/util/type_resolver_util.h> DEFINE_LOG_CATEGORY_STATIC(HttpRpcRequestLog, Log, All); #define LOCTEXT_NAMESPACE "HttpRpcRequest" using google::protobuf::Closure; using google::protobuf::Descriptor; using google::protobuf::DescriptorPool; using google::protobuf::Message; using google::protobuf::MethodDescriptor; using google::protobuf::RpcController; using google::protobuf::Message; using google::protobuf::MethodDescriptor; using google::protobuf::util::JsonOptions; using google::protobuf::util::JsonToBinaryString; using google::protobuf::util::NewTypeResolverForDescriptorPool; using google::protobuf::util::Status; using google::protobuf::util::TypeResolver; static const char kTypeUrlPrefix[] = "type.googleapis.com"; static std::string GetTypeUrl(const Descriptor* message) { return std::string(kTypeUrlPrefix) + "/" + message->full_name(); } const FString HttpRpcRequest::kContentTypeJson = "application/json"; const FString HttpRpcRequest::kContentTypeBinary = "application/x-protobuf"; const FString HttpRpcRequest::kContentTypeASCII = "application/x-protobuf-text"; HttpRpcRequest::HttpRpcRequest( HttpRpcRequestStrategy RequestStrategy, TypeResolver* ProtoTypeResolver, int64 RequestId, const FString& ServiceUri, const MethodDescriptor* Method, RpcController* Controller, const Message* Request, Message* Response, Closure* Done) : callState_(Method, Controller, Request, Response, Done), httpRequest_(FHttpModule::Get().CreateRequest()), requestId_(RequestId), typeResolver_(ProtoTypeResolver), requestStrategy_(RequestStrategy) { httpRequest_->SetVerb(TEXT("POST")); httpRequest_->SetURL(ServiceUri); httpRequest_->SetHeader("X-Request-ID", FString::Printf(TEXT("%u"), RequestId)); httpRequest_->SetHeader("X-Method", FString(Method->name().c_str())); } HttpRpcRequest::~HttpRpcRequest() {} bool HttpRpcRequest::Init() { if (requestStrategy_ == HttpRpcRequestStrategy::HRRS_JSON) { std::string jsonString; JsonOptions jsonOptions; jsonOptions.always_print_primitive_fields = true; jsonOptions.add_whitespace = true; Status status = google::protobuf::util::BinaryToJsonString( typeResolver_, GetTypeUrl(callState_.GetRequest()->GetDescriptor()), callState_.GetRequest()->SerializeAsString(), &jsonString, jsonOptions); if (!status.ok()) { UE_LOG(HttpRpcRequestLog, Error, TEXT("Failed to serialize to json (%s)"), *FString(status.error_message().ToString().c_str())); callState_.GetController()->SetFailed("JSON serialization failed"); return false; } httpRequest_->SetHeader("Content-Type", kContentTypeJson); httpRequest_->SetContentAsString(FString(jsonString.c_str())); } else if (requestStrategy_ == HttpRpcRequestStrategy::HRRS_PROTOASCII) { std::string textString; if (!google::protobuf::TextFormat::PrintToString(*callState_.GetRequest(), &textString)) { UE_LOG(HttpRpcRequestLog, Error, TEXT("Failed to serialize to text")); callState_.GetController()->SetFailed("Text serialization failed"); return false; } httpRequest_->SetHeader("Content-Type", kContentTypeASCII); httpRequest_->SetContentAsString(FString(textString.c_str())); } else if (requestStrategy_ == HttpRpcRequestStrategy::HRRS_PROTOBINARY) { std::string binaryString = callState_.GetRequest()->SerializeAsString(); httpRequest_->SetHeader("Content-Type", kContentTypeBinary); httpRequest_->SetContentAsString(FString(binaryString.c_str())); } else { UE_LOG(HttpRpcRequestLog, Error, TEXT("Invalid HTTP request strategy")); callState_.GetController()->SetFailed("Invalid HTTP request strategy"); return false; } httpRequest_->OnProcessRequestComplete().BindRaw(this, &HttpRpcRequest::onHttpRequestCompleted); return true; } bool HttpRpcRequest::Execute() { if (!httpRequest_->ProcessRequest()) { UE_LOG(HttpRpcRequestLog, Error, TEXT("ProcessRequest failed")); callState_.GetController()->SetFailed("ProcessRequest failed"); return false; } return true; } void HttpRpcRequest::onHttpRequestCompleted(FHttpRequestPtr request, FHttpResponsePtr response, bool bWasSuccessful) { if (!bWasSuccessful) { UE_LOG(HttpRpcRequestLog, Error, TEXT("HTTP request failed")); callState_.GetController()->SetFailed("HTTP request failed"); } else { const int responseCode = response->GetResponseCode(); if (responseCode != 200) { if ((responseCode >= 300) && (responseCode < 400)) { // TODO(san): Handle redirects. callState_.GetController()->SetFailed("Unsupported redirect"); } else { UE_LOG(HttpRpcRequestLog, Error, TEXT("HTTP response code %d (%s)"), response->GetResponseCode(), *response->GetContentAsString()); callState_.GetController()->SetFailed("Bad HTTP response code"); } } else { // Successful HTTP response. int requestId = ParseRequestIdFromResponse(response); if (requestId == -1) { UE_LOG(HttpRpcRequestLog, Error, TEXT("HTTP response missing request id")); callState_.GetController()->SetFailed("Response missing request id"); // TODO(san): Think about whether we should be strict about this given we have the request handy. } else if (requestId != FCString::Atoi(*request->GetHeader("X-Request-ID"))) { // If this happens legitimately then we are most likely inheriting a 'threading issue' from the // HTTP module - in which case we'll probably need to track outstanding requests ourselves. UE_LOG(HttpRpcRequestLog, Error, TEXT("Mismatched Request/Response!")); callState_.GetController()->SetFailed("Mismatched Request/Response ID"); } else { // Request ID is valid. Extract the protobuf from the HTTP content buffer. if (!ParseMessageFromResponse(response)) { UE_LOG(HttpRpcRequestLog, Warning, TEXT("Failed to parse response protobuf")); callState_.GetController()->SetFailed("Failed to parse response protobuf"); } } } } Closure* cachedClosure = callState_.GetDone(); delete this; cachedClosure->Run(); } int HttpRpcRequest::ParseRequestIdFromResponse(FHttpResponsePtr response) { FString requestIdString = response->GetHeader("X-Request-ID"); if (requestIdString == "") { return -1; } return FCString::Atoi(*requestIdString); } bool HttpRpcRequest::ParseMessageFromResponse(FHttpResponsePtr response) { const FString contentType = response->GetContentType(); if (contentType.StartsWith(kContentTypeJson)) { } else if (contentType.StartsWith(kContentTypeASCII)) { if (!google::protobuf::TextFormat::ParseFromString(TCHAR_TO_UTF8(*response->GetContentAsString()), callState_.GetResponse())) { UE_LOG(HttpRpcRequestLog, Error, TEXT("ASCII response parse failed")); return false; } return true; } else if (contentType.StartsWith(kContentTypeBinary)) { } else { UE_LOG(HttpRpcRequestLog, Error, TEXT("Invalid content type '%s'"), *contentType); } return false; }
42.255952
135
0.755881
fire
b4151e70d7555aff9046b564a293832c45a831a3
680
cpp
C++
hackerrank/practice/mathematics/combinatorics/game_of_thrones_ii.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
4
2018-06-05T14:15:52.000Z
2022-02-08T05:14:23.000Z
hackerrank/practice/mathematics/combinatorics/game_of_thrones_ii.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
null
null
null
hackerrank/practice/mathematics/combinatorics/game_of_thrones_ii.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
1
2018-10-21T11:01:35.000Z
2018-10-21T11:01:35.000Z
// https://www.hackerrank.com/challenges/game-of-throne-ii #include "common/modular/static/factorial.h" #include "common/modular_io.h" #include "common/stl/base.h" #include <string> using TFactorial = modular::mstatic::Factorial<TModularD, false>; int main_game_of_thrones_ii() { TFactorial f; string s; cin >> s; sort(s.begin(), s.end()); unsigned n = unsigned(s.size()); s.push_back(' '); unsigned ls = 0, so = 0; TModularD r = 1; for (unsigned i = 1; i <= n; ++i) { if (s[i] == s[i - 1]) continue; unsigned l = i - ls; ls = i; so += (l & 1); r *= f(l / 2); } cout << ((so > 1) ? TModularD(0) : f(n / 2) / r) << endl; return 0; }
22.666667
65
0.582353
Loks-
b41a3eaba77ff98259b271b1b784bc4b6fe6749c
2,479
cpp
C++
ql/instruments/dividendbarrieroption.cpp
jiangjiali/QuantLib
37c98eccfa18a95acb1e98b276831641be92b38e
[ "BSD-3-Clause" ]
3,358
2015-12-18T02:56:17.000Z
2022-03-31T02:42:47.000Z
ql/instruments/dividendbarrieroption.cpp
jiangjiali/QuantLib
37c98eccfa18a95acb1e98b276831641be92b38e
[ "BSD-3-Clause" ]
965
2015-12-21T10:35:28.000Z
2022-03-30T02:47:00.000Z
ql/instruments/dividendbarrieroption.cpp
jiangjiali/QuantLib
37c98eccfa18a95acb1e98b276831641be92b38e
[ "BSD-3-Clause" ]
1,663
2015-12-17T17:45:38.000Z
2022-03-31T07:58:29.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2008 Andreas Gaida Copyright (C) 2008 Ralph Schreyer Copyright (C) 2008 Klaus Spanderen This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <ql/instruments/dividendbarrieroption.hpp> #include <ql/utilities/dataformatters.hpp> #include <ql/exercise.hpp> namespace QuantLib { DividendBarrierOption::DividendBarrierOption( Barrier::Type barrierType, Real barrier, Real rebate, const ext::shared_ptr<StrikedTypePayoff>& payoff, const ext::shared_ptr<Exercise>& exercise, const std::vector<Date>& dividendDates, const std::vector<Real>& dividends) : BarrierOption(barrierType, barrier, rebate, payoff, exercise), cashFlow_(DividendVector(dividendDates, dividends)) {} void DividendBarrierOption::setupArguments( PricingEngine::arguments* args) const { BarrierOption::setupArguments(args); auto* arguments = dynamic_cast<DividendBarrierOption::arguments*>(args); QL_REQUIRE(arguments != nullptr, "wrong engine type"); arguments->cashFlow = cashFlow_; } void DividendBarrierOption::arguments::validate() const { BarrierOption::arguments::validate(); Date exerciseDate = exercise->lastDate(); for (Size i = 0; i < cashFlow.size(); i++) { QL_REQUIRE(cashFlow[i]->date() <= exerciseDate, "the " << io::ordinal(i+1) << " dividend date (" << cashFlow[i]->date() << ") is later than the exercise date (" << exerciseDate << ")"); } } }
37
80
0.628479
jiangjiali
b41b4ba95eb97f5ac038b6d586fc8653980195f9
8,874
cpp
C++
src/unity/lib/extensions/option_info.cpp
LeeCenY/turicreate
fb2f3bf313e831ceb42a2e10aacda6e472ea8d93
[ "BSD-3-Clause" ]
1
2018-11-15T15:32:26.000Z
2018-11-15T15:32:26.000Z
src/unity/lib/extensions/option_info.cpp
LeeCenY/turicreate
fb2f3bf313e831ceb42a2e10aacda6e472ea8d93
[ "BSD-3-Clause" ]
2
2022-01-13T04:03:55.000Z
2022-03-12T01:02:31.000Z
src/unity/lib/extensions/option_info.cpp
ZeroInfinite/turicreate
dd210c2563930881abd51fd69cb73007955b33fd
[ "BSD-3-Clause" ]
null
null
null
/* Copyright © 2017 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #include <unity/lib/extensions/option_info.hpp> #include <boost/lexical_cast.hpp> namespace turi { namespace option_handling { flexible_type option_info::to_dictionary() const { flex_dict n; n.push_back({"description", description}); n.push_back({"default_value", default_value}); switch(parameter_type) { case REAL: { n.push_back({"parameter_type", "REAL"}); n.push_back({"lower_bound", lower_bound}); n.push_back({"upper_bound", upper_bound}); break; } case INTEGER: { n.push_back({"parameter_type", "INTEGER"}); n.push_back({"lower_bound", lower_bound}); n.push_back({"upper_bound", upper_bound}); break; } case BOOL: { n.push_back({"parameter_type", "BOOL"}); break; } case CATEGORICAL: { n.push_back({"parameter_type", "CATEGORICAL"}); flex_list a; for (const flexible_type& v : allowed_values) { a.push_back(v); } n.push_back({"possible_values", a}); break; } case STRING: { n.push_back({"parameter_type", "STRING"}); break; } case FLEXIBLE_TYPE: { n.push_back({"parameter_type", "DYNAMIC"}); break; } } return n; } flexible_type option_info::interpret_value(const flexible_type& value) const { std::string sep_char = (value.get_type() == flex_type_enum::STRING) ? "'" : ""; flexible_type ret_v; switch(parameter_type) { case option_info::REAL: { bool value_type_okay = false; switch(value.get_type()) { case flex_type_enum::INTEGER: ret_v = double(value); value_type_okay = true; break; case flex_type_enum::FLOAT: ret_v = value; value_type_okay = true; break; case flex_type_enum::STRING: { try { ret_v = boost::lexical_cast<double>(value.get<flex_string>()); value_type_okay = true; } catch(const boost::bad_lexical_cast&) { value_type_okay = false; } break; } case flex_type_enum::UNDEFINED: ret_v = default_value; value_type_okay = true; break; default: value_type_okay = false; break; } if(!value_type_okay) { std::ostringstream msg; msg << "Expected numeric value for option '" << name << "'. Cannot cast " << sep_char << value << sep_char << " to a numeric value."; log_and_throw(msg.str()); } if( (!(double(ret_v) >= lower_bound)) || (!(double(ret_v) <= upper_bound))) { std::ostringstream msg; msg << "Option '" << name << "' must be in the range [" << lower_bound << ", " << upper_bound << "]."; log_and_throw(msg.str()); } break; } case option_info::INTEGER: { bool value_type_okay = false; switch(value.get_type()) { case flex_type_enum::INTEGER: ret_v = value; value_type_okay = true; break; case flex_type_enum::FLOAT: ret_v = int64_t(value.get<double>()); if(double(ret_v) != value.get<double>()) value_type_okay = false; else value_type_okay = true; break; case flex_type_enum::STRING: { try { ret_v = boost::lexical_cast<int64_t>(value.get<flex_string>()); value_type_okay = true; } catch(const boost::bad_lexical_cast&) { value_type_okay = false; } break; } case flex_type_enum::UNDEFINED: ret_v = default_value; value_type_okay = true; break; default: value_type_okay = false; break; } if(!value_type_okay) { std::ostringstream msg; msg << "Expected integer value for option '" << name << "'. Cannot cast " << sep_char << value << sep_char << " to an integer value."; log_and_throw(msg.str()); } if( (!(flex_int(ret_v) >= lower_bound)) || (!(flex_int(ret_v) <= upper_bound))) { std::ostringstream msg; msg << "Option '" << name << "' must be in the range [" << lower_bound << ", " << upper_bound << "]."; log_and_throw(msg.str()); } break; } case option_info::BOOL: { bool value_type_okay = false; switch(value.get_type()) { case flex_type_enum::INTEGER: if(value.get<flex_int>() == 0) { ret_v = false; value_type_okay = true; } else if (value.get<flex_int>() == 1) { ret_v = true; value_type_okay = true; } else { value_type_okay = false; } break; case flex_type_enum::FLOAT: if(value.get<flex_float>() == 0.0) { ret_v = false; value_type_okay = true; } else if (value.get<flex_float>() == 1.0) { ret_v = true; value_type_okay = true; } else { value_type_okay = false; } break; case flex_type_enum::STRING: { static const std::map<std::string, bool> okay_values = { {"1", true}, {"True", true}, {"T", true}, {"true", true}, {"Y", true}, {"y", true}, {"yes", true}, {"0", false}, {"False", false}, {"F", false}, {"false", false}, {"N", false}, {"n", false}, {"no", false} }; auto it = okay_values.find(value.get<flex_string>()); if(it != okay_values.end()) { ret_v = it->second; value_type_okay = true; } else { value_type_okay = false; } } case flex_type_enum::UNDEFINED: ret_v = default_value; value_type_okay = true; break; default: value_type_okay = false; break; } if(!value_type_okay) { std::ostringstream msg; msg << "Expected boolean value for option '" << name << sep_char << "'. Cannot interpret " << sep_char << value << sep_char << " as True or False."; log_and_throw(msg.str()); } break; } case option_info::CATEGORICAL: { DASSERT_EQ(std::set<flexible_type>(allowed_values.begin(), allowed_values.end()).count(default_value), 1); bool is_okay = false; for(const auto& okay_v : allowed_values) { if(value == okay_v) { is_okay = true; break; } } if(!is_okay){ std::ostringstream msg; msg << "Option '" << name << "' must be one of ("; for(size_t i = 0; i < allowed_values.size()-1; i++){ msg << sep_char << allowed_values[i] << sep_char << ", "; } msg << "or " << sep_char << allowed_values[allowed_values.size()-1] << sep_char << ")."; log_and_throw(msg.str()); } ret_v = value; break; } case option_info::STRING: ret_v = value; // Maybe more on this later? break; case option_info::FLEXIBLE_TYPE: ret_v = value; break; default: log_and_throw("Internal error. Option type un-implemented"); break; } return ret_v; } /** * Check to make sure that the options satisfy the requirements. */ void option_info::check_value(const flexible_type& value) const { interpret_value(value); } /** * Save */ void option_info::save(turi::oarchive& oarc) const { oarc << name << description << default_value << parameter_type << lower_bound << upper_bound << allowed_values; } /** * Load */ void option_info::load(turi::iarchive& iarc) { iarc >> name >> description >> default_value >> parameter_type >> lower_bound >> upper_bound >> allowed_values; } }}
28.082278
92
0.49414
LeeCenY
b41b4eca36363074c8862854919c61e5a453e8c2
2,612
hpp
C++
3rdparty/GPSTk/core/lib/Math/RACRotation.hpp
mfkiwl/ICE
e660d031bb1bcea664db1de4946fd8781be5b627
[ "MIT" ]
50
2019-10-12T01:22:20.000Z
2022-02-15T23:28:26.000Z
3rdparty/GPSTk/core/lib/Math/RACRotation.hpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
null
null
null
3rdparty/GPSTk/core/lib/Math/RACRotation.hpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
14
2019-11-05T01:50:29.000Z
2021-08-06T06:23:44.000Z
//============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 3.0 of the License, or // any later version. // // The GPSTk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= // // #ifndef GPSTK_RACROTATION_HPP #define GPSTK_RACROTATION_HPP // gpstk #include "Triple.hpp" #include "Matrix.hpp" #include "Vector.hpp" #include "Xvt.hpp" namespace gpstk { /// @ingroup MathGroup //@{ class RACRotation : public gpstk::Matrix<double> { public: // Constructors RACRotation( const gpstk::Triple& SVPositionVector, const gpstk::Triple& SVVelocityVector); RACRotation(const gpstk::Xvt& xvt); // Methods gpstk::Vector<double> convertToRAC( const gpstk::Vector<double>& inV ); gpstk::Triple convertToRAC( const gpstk::Triple& inVec ); gpstk::Xvt convertToRAC( const gpstk::Xvt& in ); // Utilities protected: void compute( const gpstk::Triple& SVPositionVector, const gpstk::Triple& SVVelocityVector); }; //@} } #endif
34.826667
80
0.57389
mfkiwl
b41df9984c6db6f292ef5791700d994616d976fc
623
cpp
C++
C++/0077-Combinations/soln-2.cpp
wyaadarsh/LeetCode-Solutions
3719f5cb059eefd66b83eb8ae990652f4b7fd124
[ "MIT" ]
5
2020-07-24T17:48:59.000Z
2020-12-21T05:56:00.000Z
C++/0077-Combinations/soln-2.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
null
null
null
C++/0077-Combinations/soln-2.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
2
2020-07-24T17:49:01.000Z
2020-08-31T19:57:35.000Z
class Solution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> combis; vector<int> combi; dfs(0, n, k, &combi, &combis); return combis; } private: void dfs(int pre, int n, int k, vector<int> * combi, vector<vector<int>> * combis) { if (static_cast<int>(combi->size()) == k) { combis->push_back(*combi); } else { for(int nxt = pre + 1; nxt <= n; ++nxt) { combi->push_back(nxt); dfs(nxt, n, k, combi, combis); combi->pop_back(); } } } };
27.086957
88
0.473515
wyaadarsh
b41e5f828d24cb6c1eaeb8e7482a19299621676a
3,595
cc
C++
content/browser/renderer_host/render_widget_host_delegate.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
content/browser/renderer_host/render_widget_host_delegate.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
content/browser/renderer_host/render_widget_host_delegate.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/render_widget_host_delegate.h" #include "build/build_config.h" #include "components/rappor/public/sample.h" #include "content/browser/renderer_host/render_view_host_delegate_view.h" #include "content/public/browser/keyboard_event_processing_result.h" #include "ui/gfx/geometry/rect.h" namespace content { KeyboardEventProcessingResult RenderWidgetHostDelegate::PreHandleKeyboardEvent( const NativeWebKeyboardEvent& event) { return KeyboardEventProcessingResult::NOT_HANDLED; } bool RenderWidgetHostDelegate::HandleWheelEvent( const blink::WebMouseWheelEvent& event) { return false; } bool RenderWidgetHostDelegate::PreHandleGestureEvent( const blink::WebGestureEvent& event) { return false; } BrowserAccessibilityManager* RenderWidgetHostDelegate::GetRootBrowserAccessibilityManager() { return nullptr; } BrowserAccessibilityManager* RenderWidgetHostDelegate::GetOrCreateRootBrowserAccessibilityManager() { return nullptr; } // If a delegate does not override this, the RenderWidgetHostView will // assume it is the sole platform event consumer. RenderWidgetHostInputEventRouter* RenderWidgetHostDelegate::GetInputEventRouter() { return nullptr; } // If a delegate does not override this, the RenderWidgetHostView will // assume its own RenderWidgetHost should consume keyboard events. RenderWidgetHostImpl* RenderWidgetHostDelegate::GetFocusedRenderWidgetHost( RenderWidgetHostImpl* receiving_widget) { return receiving_widget; } RenderWidgetHostImpl* RenderWidgetHostDelegate::GetRenderWidgetHostWithPageFocus() { return nullptr; } bool RenderWidgetHostDelegate::IsFullscreenForCurrentTab() const { return false; } blink::WebDisplayMode RenderWidgetHostDelegate::GetDisplayMode( RenderWidgetHostImpl* render_widget_host) const { return blink::kWebDisplayModeBrowser; } bool RenderWidgetHostDelegate::HasMouseLock( RenderWidgetHostImpl* render_widget_host) { return false; } RenderWidgetHostImpl* RenderWidgetHostDelegate::GetMouseLockWidget() { return nullptr; } bool RenderWidgetHostDelegate::RequestKeyboardLock(RenderWidgetHostImpl* host, bool esc_key_locked) { return false; } RenderWidgetHostImpl* RenderWidgetHostDelegate::GetKeyboardLockWidget() { return nullptr; } TextInputManager* RenderWidgetHostDelegate::GetTextInputManager() { return nullptr; } bool RenderWidgetHostDelegate::IsHidden() { return false; } RenderViewHostDelegateView* RenderWidgetHostDelegate::GetDelegateView() { return nullptr; } RenderWidgetHostImpl* RenderWidgetHostDelegate::GetFullscreenRenderWidgetHost() const { return nullptr; } bool RenderWidgetHostDelegate::OnUpdateDragCursor() { return false; } bool RenderWidgetHostDelegate::IsWidgetForMainFrame(RenderWidgetHostImpl*) { return false; } bool RenderWidgetHostDelegate::AddDomainInfoToRapporSample( rappor::Sample* sample) { sample->SetStringField("Domain", "Unknown"); return false; } void RenderWidgetHostDelegate::UpdateUrlForUkmSource( ukm::UkmRecorder* service, ukm::SourceId ukm_source_id) {} gfx::Size RenderWidgetHostDelegate::GetAutoResizeSize() { return gfx::Size(); } WebContents* RenderWidgetHostDelegate::GetAsWebContents() { return nullptr; } bool RenderWidgetHostDelegate::IsShowingContextMenuOnPage() const { return false; } } // namespace content
26.828358
79
0.793324
zipated
b41f006eec6c233661f0236cfdfe350b776197b9
21,696
cc
C++
ash/wm/lock_state_controller.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
ash/wm/lock_state_controller.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
ash/wm/lock_state_controller.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/wm/lock_state_controller.h" #include <algorithm> #include <string> #include <utility> #include "ash/accessibility/accessibility_controller.h" #include "ash/cancel_mode.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/public/interfaces/shutdown.mojom.h" #include "ash/session/session_controller.h" #include "ash/shell.h" #include "ash/shell_delegate.h" #include "ash/shell_port.h" #include "ash/shutdown_controller.h" #include "ash/shutdown_reason.h" #include "ash/wallpaper/wallpaper_controller.h" #include "ash/wm/session_state_animator.h" #include "ash/wm/session_state_animator_impl.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/location.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics.h" #include "base/strings/string_util.h" #include "base/sys_info.h" #include "base/timer/timer.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager_client.h" #include "ui/aura/window_tree_host.h" #include "ui/views/controls/menu/menu_controller.h" #include "ui/wm/core/compound_event_filter.h" #define UMA_HISTOGRAM_LOCK_TIMES(name, sample) \ UMA_HISTOGRAM_CUSTOM_TIMES(name, sample, \ base::TimeDelta::FromMilliseconds(1), \ base::TimeDelta::FromSeconds(50), 100) namespace ash { namespace { // ASan/TSan/MSan instrument each memory access. This may slow the execution // down significantly. #if defined(MEMORY_SANITIZER) // For MSan the slowdown depends heavily on the value of msan_track_origins GYP // flag. The multiplier below corresponds to msan_track_origins=1. constexpr int kTimeoutMultiplier = 6; #elif defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) constexpr int kTimeoutMultiplier = 2; #else constexpr int kTimeoutMultiplier = 1; #endif constexpr int kMaxShutdownSoundDurationMs = 1500; // Amount of time to wait for our lock requests to be honored before giving up. constexpr int kLockFailTimeoutMs = 8000 * kTimeoutMultiplier; // When the button has been held continuously from the unlocked state, amount of // time that we wait after the screen locker window is shown before starting the // pre-shutdown animation. constexpr int kLockToShutdownTimeoutMs = 150; // Additional time (beyond kFastCloseAnimMs) to wait after starting the // fast-close shutdown animation before actually requesting shutdown, to give // the animation time to finish. constexpr int kShutdownRequestDelayMs = 50; } // namespace // static const int LockStateController::kPreLockContainersMask = SessionStateAnimator::NON_LOCK_SCREEN_CONTAINERS | SessionStateAnimator::SHELF; LockStateController::LockStateController( ShutdownController* shutdown_controller) : animator_(new SessionStateAnimatorImpl()), shutdown_controller_(shutdown_controller), scoped_session_observer_(this), weak_ptr_factory_(this) { DCHECK(shutdown_controller_); Shell::GetPrimaryRootWindow()->GetHost()->AddObserver(this); } LockStateController::~LockStateController() { Shell::GetPrimaryRootWindow()->GetHost()->RemoveObserver(this); } void LockStateController::StartLockAnimation() { if (animating_lock_) return; can_cancel_lock_animation_ = true; StartCancellablePreLockAnimation(); } void LockStateController::StartLockThenShutdownAnimation( ShutdownReason shutdown_reason) { shutdown_after_lock_ = true; shutdown_reason_ = shutdown_reason; StartLockAnimation(); } void LockStateController::StartShutdownAnimation(ShutdownReason reason) { shutdown_reason_ = reason; StartCancellableShutdownAnimation(); } void LockStateController::StartLockAnimationAndLockImmediately() { if (animating_lock_) return; StartImmediatePreLockAnimation(true /* request_lock_on_completion */); } void LockStateController::LockWithoutAnimation() { if (animating_lock_) return; animating_lock_ = true; post_lock_immediate_animation_ = true; animator_->StartAnimation(kPreLockContainersMask, SessionStateAnimator::ANIMATION_HIDE_IMMEDIATELY, SessionStateAnimator::ANIMATION_SPEED_IMMEDIATE); ShellPort::Get()->OnLockStateEvent( LockStateObserver::EVENT_LOCK_ANIMATION_STARTED); Shell::Get()->session_controller()->LockScreen(); } bool LockStateController::LockRequested() { return lock_fail_timer_.IsRunning(); } bool LockStateController::ShutdownRequested() { return shutting_down_; } bool LockStateController::CanCancelLockAnimation() { return can_cancel_lock_animation_; } void LockStateController::CancelLockAnimation() { if (!CanCancelLockAnimation()) return; shutdown_after_lock_ = false; animating_lock_ = false; CancelPreLockAnimation(); } bool LockStateController::CanCancelShutdownAnimation() { return pre_shutdown_timer_.IsRunning() || shutdown_after_lock_ || lock_to_shutdown_timer_.IsRunning(); } void LockStateController::CancelShutdownAnimation() { if (!CanCancelShutdownAnimation()) return; if (lock_to_shutdown_timer_.IsRunning()) { lock_to_shutdown_timer_.Stop(); return; } if (shutdown_after_lock_) { shutdown_after_lock_ = false; return; } animator_->StartAnimation( SessionStateAnimator::ROOT_CONTAINER, SessionStateAnimator::ANIMATION_UNDO_GRAYSCALE_BRIGHTNESS, SessionStateAnimator::ANIMATION_SPEED_REVERT_SHUTDOWN); pre_shutdown_timer_.Stop(); } void LockStateController::OnStartingLock() { if (shutting_down_ || system_is_locked_) return; if (animating_lock_) return; StartImmediatePreLockAnimation(false /* request_lock_on_completion */); } void LockStateController::RequestShutdown(ShutdownReason reason) { if (shutting_down_) return; shutting_down_ = true; shutdown_reason_ = reason; ShellPort* port = ShellPort::Get(); port->HideCursor(); port->LockCursor(); animator_->StartAnimation( SessionStateAnimator::ROOT_CONTAINER, SessionStateAnimator::ANIMATION_GRAYSCALE_BRIGHTNESS, SessionStateAnimator::ANIMATION_SPEED_SHUTDOWN); StartRealShutdownTimer(true); } void LockStateController::OnLockScreenHide(base::OnceClosure callback) { StartUnlockAnimationBeforeUIDestroyed(std::move(callback)); } void LockStateController::SetLockScreenDisplayedCallback( base::OnceClosure callback) { DCHECK(lock_screen_displayed_callback_.is_null()); lock_screen_displayed_callback_ = std::move(callback); } void LockStateController::OnHostCloseRequested(aura::WindowTreeHost* host) { Shell::Get()->session_controller()->RequestSignOut(); } void LockStateController::OnChromeTerminating() { // If we hear that Chrome is exiting but didn't request it ourselves, all we // can really hope for is that we'll have time to clear the screen. // This is also the case when the user signs off. if (!shutting_down_) { shutting_down_ = true; Shell* shell = Shell::Get(); if (shell->cursor_manager()) { shell->cursor_manager()->HideCursor(); shell->cursor_manager()->LockCursor(); } animator_->StartAnimation(SessionStateAnimator::kAllNonRootContainersMask, SessionStateAnimator::ANIMATION_HIDE_IMMEDIATELY, SessionStateAnimator::ANIMATION_SPEED_IMMEDIATE); } } void LockStateController::OnLockStateChanged(bool locked) { DCHECK((lock_fail_timer_.IsRunning() && lock_duration_timer_ != nullptr) || (!lock_fail_timer_.IsRunning() && lock_duration_timer_ == nullptr)); VLOG(1) << "OnLockStateChanged called with locked: " << locked << ", shutting_down_: " << shutting_down_ << ", system_is_locked_: " << system_is_locked_ << ", lock_fail_timer_.IsRunning(): " << lock_fail_timer_.IsRunning(); if (shutting_down_ || (system_is_locked_ == locked)) return; system_is_locked_ = locked; if (locked) { StartPostLockAnimation(); lock_fail_timer_.Stop(); if (lock_duration_timer_) { UMA_HISTOGRAM_LOCK_TIMES("Ash.WindowManager.Lock.Success", lock_duration_timer_->Elapsed()); lock_duration_timer_.reset(); } } else { StartUnlockAnimationAfterUIDestroyed(); } } void LockStateController::OnLockFailTimeout() { UMA_HISTOGRAM_LOCK_TIMES("Ash.WindowManager.Lock.Timeout", lock_duration_timer_->Elapsed()); lock_duration_timer_.reset(); DCHECK(!system_is_locked_); LOG(FATAL) << "Screen lock took too long; crashing intentionally"; } void LockStateController::StartLockToShutdownTimer() { DCHECK(shutdown_reason_); shutdown_after_lock_ = false; lock_to_shutdown_timer_.Stop(); lock_to_shutdown_timer_.Start( FROM_HERE, base::TimeDelta::FromMilliseconds(kLockToShutdownTimeoutMs), this, &LockStateController::OnLockToShutdownTimeout); } void LockStateController::OnLockToShutdownTimeout() { DCHECK(system_is_locked_); StartCancellableShutdownAnimation(); } void LockStateController::StartPreShutdownAnimationTimer() { pre_shutdown_timer_.Stop(); pre_shutdown_timer_.Start( FROM_HERE, animator_->GetDuration(SessionStateAnimator::ANIMATION_SPEED_SHUTDOWN), this, &LockStateController::OnPreShutdownAnimationTimeout); } void LockStateController::OnPreShutdownAnimationTimeout() { VLOG(1) << "OnPreShutdownAnimationTimeout"; shutting_down_ = true; Shell* shell = Shell::Get(); if (shell->cursor_manager()) shell->cursor_manager()->HideCursor(); StartRealShutdownTimer(false); } void LockStateController::StartRealShutdownTimer(bool with_animation_time) { base::TimeDelta duration = base::TimeDelta::FromMilliseconds(kShutdownRequestDelayMs); if (with_animation_time) { duration += animator_->GetDuration(SessionStateAnimator::ANIMATION_SPEED_SHUTDOWN); } // Play and get shutdown sound duration from chrome in |sound_duration|. And // start real shutdown after a delay of |duration|. Shell::Get()->accessibility_controller()->PlayShutdownSound(base::BindOnce( [](base::WeakPtr<LockStateController> self, base::TimeDelta duration, base::TimeDelta sound_duration) { if (!self) return; sound_duration = std::min( sound_duration, base::TimeDelta::FromMilliseconds(kMaxShutdownSoundDurationMs)); duration = std::max(duration, sound_duration); self->real_shutdown_timer_.Start( FROM_HERE, duration, self.get(), &LockStateController::OnRealPowerTimeout); }, weak_ptr_factory_.GetWeakPtr(), duration)); } void LockStateController::OnRealPowerTimeout() { VLOG(1) << "OnRealPowerTimeout"; DCHECK(shutting_down_); DCHECK(shutdown_reason_); // Shut down or reboot based on device policy. shutdown_controller_->ShutDownOrReboot(*shutdown_reason_); } void LockStateController::StartCancellableShutdownAnimation() { Shell* shell = Shell::Get(); // Hide cursor, but let it reappear if the mouse moves. if (shell->cursor_manager()) shell->cursor_manager()->HideCursor(); animator_->StartAnimation( SessionStateAnimator::ROOT_CONTAINER, SessionStateAnimator::ANIMATION_GRAYSCALE_BRIGHTNESS, SessionStateAnimator::ANIMATION_SPEED_SHUTDOWN); StartPreShutdownAnimationTimer(); } void LockStateController::StartImmediatePreLockAnimation( bool request_lock_on_completion) { VLOG(1) << "StartImmediatePreLockAnimation " << request_lock_on_completion; animating_lock_ = true; StoreUnlockedProperties(); PreLockAnimation(SessionStateAnimator::ANIMATION_SPEED_MOVE_WINDOWS, request_lock_on_completion); DispatchCancelMode(); ShellPort::Get()->OnLockStateEvent( LockStateObserver::EVENT_LOCK_ANIMATION_STARTED); } void LockStateController::StartCancellablePreLockAnimation() { animating_lock_ = true; StoreUnlockedProperties(); VLOG(1) << "StartCancellablePreLockAnimation"; PreLockAnimation(SessionStateAnimator::ANIMATION_SPEED_UNDOABLE, true); DispatchCancelMode(); ShellPort::Get()->OnLockStateEvent( LockStateObserver::EVENT_PRELOCK_ANIMATION_STARTED); } void LockStateController::PreLockAnimation( SessionStateAnimator::AnimationSpeed speed, bool request_lock_on_completion) { Shell::Get()->wallpaper_controller()->PrepareWallpaperForLockScreenChange( true); base::Closure next_animation_starter = base::Bind(&LockStateController::PreLockAnimationFinished, weak_ptr_factory_.GetWeakPtr(), request_lock_on_completion); SessionStateAnimator::AnimationSequence* animation_sequence = animator_->BeginAnimationSequence(next_animation_starter); animation_sequence->StartAnimation( SessionStateAnimator::NON_LOCK_SCREEN_CONTAINERS, SessionStateAnimator::ANIMATION_LIFT, speed); animation_sequence->StartAnimation(SessionStateAnimator::SHELF, SessionStateAnimator::ANIMATION_FADE_OUT, speed); // Hide the screen locker containers so we can raise them later. animator_->StartAnimation(SessionStateAnimator::LOCK_SCREEN_CONTAINERS, SessionStateAnimator::ANIMATION_HIDE_IMMEDIATELY, SessionStateAnimator::ANIMATION_SPEED_IMMEDIATE); AnimateWallpaperAppearanceIfNecessary(speed, animation_sequence); animation_sequence->EndSequence(); } void LockStateController::CancelPreLockAnimation() { VLOG(1) << "CancelPreLockAnimation"; Shell::Get()->wallpaper_controller()->PrepareWallpaperForLockScreenChange( false); base::Closure next_animation_starter = base::Bind(&LockStateController::LockAnimationCancelled, weak_ptr_factory_.GetWeakPtr()); SessionStateAnimator::AnimationSequence* animation_sequence = animator_->BeginAnimationSequence(next_animation_starter); animation_sequence->StartAnimation( SessionStateAnimator::NON_LOCK_SCREEN_CONTAINERS, SessionStateAnimator::ANIMATION_UNDO_LIFT, SessionStateAnimator::ANIMATION_SPEED_UNDO_MOVE_WINDOWS); animation_sequence->StartAnimation( SessionStateAnimator::SHELF, SessionStateAnimator::ANIMATION_FADE_IN, SessionStateAnimator::ANIMATION_SPEED_UNDO_MOVE_WINDOWS); AnimateWallpaperHidingIfNecessary( SessionStateAnimator::ANIMATION_SPEED_UNDO_MOVE_WINDOWS, animation_sequence); animation_sequence->EndSequence(); } void LockStateController::StartPostLockAnimation() { VLOG(1) << "StartPostLockAnimation"; base::Closure next_animation_starter = base::Bind(&LockStateController::PostLockAnimationFinished, weak_ptr_factory_.GetWeakPtr()); SessionStateAnimator::AnimationSequence* animation_sequence = animator_->BeginAnimationSequence(next_animation_starter); animation_sequence->StartAnimation( SessionStateAnimator::LOCK_SCREEN_CONTAINERS, SessionStateAnimator::ANIMATION_RAISE_TO_SCREEN, post_lock_immediate_animation_ ? SessionStateAnimator::ANIMATION_SPEED_IMMEDIATE : SessionStateAnimator::ANIMATION_SPEED_MOVE_WINDOWS); // Show the lock screen shelf. This is a no-op if views-based shelf is // disabled, since shelf is in NonLockScreenContainersContainer. animation_sequence->StartAnimation( SessionStateAnimator::SHELF, SessionStateAnimator::ANIMATION_FADE_IN, post_lock_immediate_animation_ ? SessionStateAnimator::ANIMATION_SPEED_IMMEDIATE : SessionStateAnimator::ANIMATION_SPEED_MOVE_WINDOWS); animation_sequence->EndSequence(); } void LockStateController::StartUnlockAnimationBeforeUIDestroyed( base::OnceClosure callback) { VLOG(1) << "StartUnlockAnimationBeforeUIDestroyed"; animator_->StartAnimationWithCallback( SessionStateAnimator::LOCK_SCREEN_CONTAINERS, SessionStateAnimator::ANIMATION_LIFT, SessionStateAnimator::ANIMATION_SPEED_MOVE_WINDOWS, std::move(callback)); // Hide the lock screen shelf. This is a no-op if views-based shelf is // disabled, since shelf is in NonLockScreenContainersContainer. animator_->StartAnimation(SessionStateAnimator::SHELF, SessionStateAnimator::ANIMATION_FADE_OUT, SessionStateAnimator::ANIMATION_SPEED_MOVE_WINDOWS); } void LockStateController::StartUnlockAnimationAfterUIDestroyed() { VLOG(1) << "StartUnlockAnimationAfterUIDestroyed"; base::Closure next_animation_starter = base::Bind(&LockStateController::UnlockAnimationAfterUIDestroyedFinished, weak_ptr_factory_.GetWeakPtr()); SessionStateAnimator::AnimationSequence* animation_sequence = animator_->BeginAnimationSequence(next_animation_starter); animation_sequence->StartAnimation( SessionStateAnimator::NON_LOCK_SCREEN_CONTAINERS, SessionStateAnimator::ANIMATION_DROP, SessionStateAnimator::ANIMATION_SPEED_MOVE_WINDOWS); animation_sequence->StartAnimation( SessionStateAnimator::SHELF, SessionStateAnimator::ANIMATION_FADE_IN, SessionStateAnimator::ANIMATION_SPEED_MOVE_WINDOWS); AnimateWallpaperHidingIfNecessary( SessionStateAnimator::ANIMATION_SPEED_MOVE_WINDOWS, animation_sequence); animation_sequence->EndSequence(); } void LockStateController::LockAnimationCancelled() { can_cancel_lock_animation_ = false; RestoreUnlockedProperties(); } void LockStateController::PreLockAnimationFinished(bool request_lock) { VLOG(1) << "PreLockAnimationFinished"; can_cancel_lock_animation_ = false; // Don't do anything (including starting the lock-fail timer) if the screen // was already locked while the animation was going. if (system_is_locked_) { DCHECK(!request_lock) << "Got request to lock already-locked system " << "at completion of pre-lock animation"; return; } if (request_lock) { if (shutdown_after_lock_) { base::RecordAction( base::UserMetricsAction("Accel_LockScreen_PowerButton")); } else { base::RecordAction( base::UserMetricsAction("Accel_LockScreen_LockButton")); } chromeos::DBusThreadManager::Get() ->GetSessionManagerClient() ->RequestLockScreen(); } base::TimeDelta timeout = base::TimeDelta::FromMilliseconds(kLockFailTimeoutMs); // TODO(derat): Remove this scaling after October 2017 when daisy (Samsung // Chromebook XE303) is unsupported. if (base::SysInfo::GetStrippedReleaseBoard() == "daisy") timeout *= 2; lock_fail_timer_.Start(FROM_HERE, timeout, this, &LockStateController::OnLockFailTimeout); lock_duration_timer_.reset(new base::ElapsedTimer()); } void LockStateController::PostLockAnimationFinished() { animating_lock_ = false; post_lock_immediate_animation_ = false; VLOG(1) << "PostLockAnimationFinished"; ShellPort::Get()->OnLockStateEvent( LockStateObserver::EVENT_LOCK_ANIMATION_FINISHED); if (!lock_screen_displayed_callback_.is_null()) std::move(lock_screen_displayed_callback_).Run(); CHECK(!views::MenuController::GetActiveInstance()); if (shutdown_after_lock_) { shutdown_after_lock_ = false; StartLockToShutdownTimer(); } } void LockStateController::UnlockAnimationAfterUIDestroyedFinished() { Shell::Get()->wallpaper_controller()->PrepareWallpaperForLockScreenChange( false); RestoreUnlockedProperties(); } void LockStateController::StoreUnlockedProperties() { if (!unlocked_properties_) { unlocked_properties_.reset(new UnlockedStateProperties()); unlocked_properties_->wallpaper_is_hidden = animator_->IsWallpaperHidden(); } if (unlocked_properties_->wallpaper_is_hidden) { // Hide wallpaper so that it can be animated later. animator_->StartAnimation(SessionStateAnimator::WALLPAPER, SessionStateAnimator::ANIMATION_HIDE_IMMEDIATELY, SessionStateAnimator::ANIMATION_SPEED_IMMEDIATE); animator_->ShowWallpaper(); } } void LockStateController::RestoreUnlockedProperties() { if (!unlocked_properties_) return; if (unlocked_properties_->wallpaper_is_hidden) { animator_->HideWallpaper(); // Restore wallpaper visibility. animator_->StartAnimation(SessionStateAnimator::WALLPAPER, SessionStateAnimator::ANIMATION_FADE_IN, SessionStateAnimator::ANIMATION_SPEED_IMMEDIATE); } unlocked_properties_.reset(); } void LockStateController::AnimateWallpaperAppearanceIfNecessary( SessionStateAnimator::AnimationSpeed speed, SessionStateAnimator::AnimationSequence* animation_sequence) { if (unlocked_properties_.get() && unlocked_properties_->wallpaper_is_hidden) { animation_sequence->StartAnimation(SessionStateAnimator::WALLPAPER, SessionStateAnimator::ANIMATION_FADE_IN, speed); } } void LockStateController::AnimateWallpaperHidingIfNecessary( SessionStateAnimator::AnimationSpeed speed, SessionStateAnimator::AnimationSequence* animation_sequence) { if (unlocked_properties_.get() && unlocked_properties_->wallpaper_is_hidden) { animation_sequence->StartAnimation(SessionStateAnimator::WALLPAPER, SessionStateAnimator::ANIMATION_FADE_OUT, speed); } } } // namespace ash
36.463866
80
0.744653
zipated
b41fd8559b5f8aeca2f61deed83aecc81fefc773
51,281
cpp
C++
src/wxTTM/wx/TT32App.cpp
ttm-tt/wxTTM
f9c75f05a564a0d82034412c1eb4c94d943e267f
[ "MIT" ]
null
null
null
src/wxTTM/wx/TT32App.cpp
ttm-tt/wxTTM
f9c75f05a564a0d82034412c1eb4c94d943e267f
[ "MIT" ]
null
null
null
src/wxTTM/wx/TT32App.cpp
ttm-tt/wxTTM
f9c75f05a564a0d82034412c1eb4c94d943e267f
[ "MIT" ]
null
null
null
/* Copyright (C) 2020 Christoph Theis */ #include "stdafx.h" #include <wx/progdlg.h> #include <wx/xrc/xh_aui.h> #include "tt32App.h" #include "MainFrm.h" #include "ChildFrm.h" #include "FormViewEx.h" #include "ImportOnlineEntries.h" #include "ItemCtrl.h" #include "Profile.h" #include "InfoSystem.h" #include "CpListStore.h" #include "PlListStore.h" #include "IdStore.h" #include "Request.h" #include "Rec.h" #include "Res.h" #if __has_include("../Crypt/crypt.h") # include "../Crypt/crypt.h" #else # include "../Crypt/crypt_template.h" #endif static int defaultType = TT_REGULAR; static int defaultTable = TT_ITTF; // Muss hier stehen, weil es sonst nicht compiliert static const wxString versionNumber = "21.09"; static const wxString version = "Version " + versionNumber; static wxString licensee = " Christoph Theis"; static wxString copyright = "(C) Christoph Theis 2021"; static wxString expire = ""; wxProgressDialog * CTT32App::m_progressDialog = NULL; IMPLEMENT_APP(CTT32App) Profile ttProfile; InfoSystem infoSystem; CTT32App::~CTT32App() { } bool CTT32App::OnInit() { _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); // Create Mutex fuer Inno Setup CreateMutex(NULL, FALSE, wxT("TTM")); wxTheApp->SetAppName("TTM"); static const wxChar ps = wxFileName::GetPathSeparator(); if (!wxApp::OnInit()) return false; // INI-File suchen wxString iniDir = wxGetCwd(); // Default: aktuelles Verzeichnis wxString iniFile = iniDir + ps + TT_PROFILE; // Wenn nicht: Common App Data if (!wxFile::Exists(iniFile)) iniFile = wxStandardPaths::Get().GetConfigDir() + ps + TT_PROFILE; // Wenn nicht: User App Data if (!wxFile::Exists(iniFile)) iniFile = wxStandardPaths::Get().GetUserLocalDataDir() + ps + TT_PROFILE; // Wenn nicht: User Local App Data if (!wxFile::Exists(iniFile)) iniFile = wxStandardPaths::Get().GetUserLocalDataDir() + ps + TT_PROFILE; if (!wxFile::Exists(iniFile)) { infoSystem.Fatal(wxT("Cannot locate \"tt32.ini\" file")); } wxSetWorkingDirectory(iniFile.SubString(0, iniFile.Len() - wxStrlen(TT_PROFILE) - 2)); // Resourcen bestimmen wxString xrcPath = GetResourcesPath(); if (!wxFile::Exists(xrcPath + "/" TT_XRCFILE)) infoSystem.Fatal(wxT("Cannot locate resource file \"%S\", exiting"), TT_XRCFILE); wxLocale::AddCatalogLookupPathPrefix(xrcPath); ttProfile.Open(iniFile.data()); int langId = wxLocale::GetSystemLanguage(); wxString lang = ttProfile.GetString(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_LANGUAGE, wxT("en_US")); if (wxLocale::FindLanguageInfo(lang) != NULL) langId = wxLocale::FindLanguageInfo(lang)->Language; m_locale.Init((wxLanguage) langId, wxLOCALE_DONT_LOAD_DEFAULT); m_locale.AddCatalog("ttm"); m_locale.AddCatalog("wxstd"); #if 0 // Lizenzueberpruefung wxString licenseFileName = wxGetCwd() + ps + "license.ini"; licensee = ""; expire = ""; if (!CheckLicenseCode(licenseFileName)) { // Warnung nur, wenn es kein "last open" gibt: // Ansonsten haben Clients, die keine Lizenz brauchen, immer eine Warnung zu Beginn. if (ttProfile.GetString(PRF_OPEN, PRF_LAST).IsEmpty()) infoSystem.Information(_("The license is not valid! You are allowed to use existing tournaments but you cannot create new ones.")); } else if (HasLicenseExpired(licenseFileName)) { infoSystem.Information( _("Your license has expired! You are allowed to use existing tournaments but you cannot create new ones.")); } else { ReadLicense(licenseFileName); } #endif // Setup von [Raster] if (!ttProfile.GetFirstKey(PRF_RASTER)) { ttProfile.AddString(PRF_RASTER, PRF_RASTER_TINY, wxT("Arial, 6, 0, 0, 0, 400, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_SMALL, wxT("Arial, 8, 0, 0, 0, 400, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_MEDIUM, wxT("Arial, 9, 0, 0, 0, 400, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_NORMAL, wxT("Arial, 10, 0, 0, 0, 400, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_PAGE, wxT("Arial, 10, 0, 0, 0, 400, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_GROUP, wxT("Arial, 12, 0, 0, 0, 400, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_COMP, wxT("Arial, 14, 0, 0, 0, 800, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_NORMALB, wxT("Arial, 10, 0, 0, 0, 700, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_MEDIUMB, wxT("Arial, 9, 0, 0, 0, 700, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_SMALLB, wxT("Arial, 8, 0, 0, 0, 700, 0, 0, 0")); } if (!ttProfile.GetFirstKey(PRF_REPORTS)) { ttProfile.AddString(PRF_REPORTS, wxT("Registration"), _("Registration")); // ttProfile.AddString(PRF_REPORTS, wxT("TeamEntries"), _("List of Team Players")); ttProfile.AddString(PRF_REPORTS, wxT("PlayerlistPerName"), _("List of Players Sorted by Name")); ttProfile.AddString(PRF_REPORTS, wxT("PlayerlistPerNumber"), _("List of Players Sorted by Number")); ttProfile.AddString(PRF_REPORTS, wxT("Participants"), _("List of Players with their Events")); ttProfile.AddString(PRF_REPORTS, wxT("Entries"), _("Participants per Event")); ttProfile.AddString(PRF_REPORTS, wxT("ChampionshipEntries"), _("Participants in Championship")); ttProfile.AddString(PRF_REPORTS, wxT("ConsolationEntries"), _("Participants in Consolation")); ttProfile.AddString(PRF_REPORTS, wxT("PartnerMissing"), _("Players with Partner Missing")); } if ( wxStrlen(ttProfile.GetString(PRF_REPORTS, wxT("Ranking"))) == 0 ) { ttProfile.DeleteString(PRF_REPORTS, wxT("RankingSingle")); ttProfile.DeleteString(PRF_REPORTS, wxT("RankingDouble")); ttProfile.DeleteString(PRF_REPORTS, wxT("RankingTeam")); ttProfile.AddString(PRF_REPORTS, wxT("Ranking"), _("Ranking by Association")); } if ( wxStrlen(ttProfile.GetString(PRF_REPORTS, wxT("WorldRanking"))) == 0 ) ttProfile.AddString(PRF_REPORTS, wxT("WorldRanking"), _("International Ranking")); if ( wxStrlen(ttProfile.GetString(PRF_REPORTS, wxT("MatchList"))) == 0 ) ttProfile.AddString(PRF_REPORTS, wxT("MatchList"), _("List of Matches")); if (wxStrlen(ttProfile.GetString(PRF_REPORTS, wxT("FinalStandings"))) == 0) ttProfile.AddString(PRF_REPORTS, wxT("FinalStandings"), _("Final Standings")); // Init image handler ::wxInitAllImageHandlers(); // Init der Resourcen wxXmlResource::Get()->InitAllHandlers(); wxXmlResource::Get()->AddHandler(new CItemCtrlXmlResourceHandler()); wxXmlResource::Get()->AddHandler(new wxAuiXmlHandler()); wxXmlResource::Get()->Load(xrcPath + "/" TT_XRCFILE); m_pMainWnd = (CMainFrame *) wxXmlResource::Get()->LoadObject(NULL, "MainFrame", "wxMDIParentFrame"); m_pMainWnd->SetIcon(wxIcon("main")); SetMenuBar("NOMenuBar"); m_pMainWnd->Maximize(true); m_pMainWnd->GetEventHandler()->ProcessEvent(wxInitDialogEvent()); m_pMainWnd->Show(true); OpenLastTournament(); Connect(IDC_PROGRESSBAR_STEP, wxThreadEventHandler(CTT32App::OnProgressBarStep), NULL, this); Connect(IDC_PROGRESSBAR_EXIT, wxThreadEventHandler(CTT32App::OnProgressBarExit), NULL, this); return true; } int CTT32App::OnExit() { return 0; } // ----------------------------------------------------------------------- class CUpdateViewEvent : public wxCommandEvent { public: CUpdateViewEvent(const CRequest &req) : wxCommandEvent(IDC_UPDATEVIEW) { SetClientData(new CRequest(req)); } ~CUpdateViewEvent() {delete (CRequest *) GetClientData();} }; void CTT32App::NotifyChange(CRequest &req) { if (wxTheApp == nullptr) return; wxTheApp->QueueEvent(new CUpdateViewEvent(req)); } void CTT32App::CommitChanges() { } void CTT32App::AbortChanges() { } class CTT32Thread : public wxThread { public: CTT32Thread(unsigned (*func)(void *arg), void *arg) : wxThread(wxTHREAD_JOINABLE), m_func(func), m_arg(arg) { Create(); } virtual ExitCode Entry() { int rc = (*m_func)(m_arg); CTT32App::ProgressBarExit(rc); return (ExitCode) rc; } void *m_arg; unsigned (*m_func)(void *arg); }; class CProgressDialog : public wxProgressDialog { public: CProgressDialog(const wxString &title, long count, wxWindow *parent, wxThread *thread, bool indefinite) : wxProgressDialog(title, title, count > 0 ? count : 100, parent), m_thread(thread), m_indefinite(indefinite), m_step(0) { if (thread) thread->Run(); if (m_indefinite) { timer.SetOwner(this); timer.Start(50); Connect(wxEVT_TIMER, wxTimerEventHandler(CProgressDialog::OnTimer), NULL, this); Connect(wxEVT_SHOW, wxShowEventHandler(CProgressDialog::OnShow), NULL, this); } } CProgressDialog::~CProgressDialog() { } public: bool Update(int value, const wxString &msg = wxEmptyString, bool *skip = 0) { if (!m_indefinite) return wxProgressDialog::Update(value, msg, skip); else if (!msg.IsEmpty() && msg != GetMessage()) return wxProgressDialog::Update(0, msg, skip); else return Pulse(); } bool IsIndefinite() const {return m_indefinite;} int IncrementCounter() { return ++m_step;} private: void OnTimer(wxTimerEvent &evt) { if (!m_thread || !m_thread->IsAlive()) timer.Stop(); else Pulse(); } void OnShow(wxShowEvent &evt) { if (!evt.IsShown()) { if (timer.IsRunning()) timer.Stop(); m_thread->Wait(); delete m_thread; m_thread = NULL; } } wxTimer timer; wxThread *m_thread; bool m_indefinite; int m_step; }; bool CTT32App::ProgressBarThread(unsigned (*func)(void * arg), void *arg, const wxString &buf, long count, bool indefinite) { if (m_progressDialog) { if (m_progressDialog->IsShown()) return false; } delete m_progressDialog; m_progressDialog = new CProgressDialog( buf, count, CTT32App::instance()->m_pMainWnd, new CTT32Thread(func, arg), indefinite); return true; } // wxProgressDialog::Update ruft DispatchEvent / YieldFor auf, das wiederum die naechsten Events verarbeiten wuerde // Ausgenommen davon sind Events der Category USER_INPUT aber nicht THREAD. Daher eine eigene Klase bauen, // die GetEventCategory entsprechend ueberlaedt class MyThreadEvent : public wxThreadEvent { public: MyThreadEvent(wxEventType evtType = wxEVT_THREAD, int id = wxID_ANY) : wxThreadEvent(evtType, id) {} wxEventCategory GetEventCategory() const{return wxEVT_CATEGORY_USER_INPUT;} wxEvent * Clone() const {return new MyThreadEvent(*this);} }; // Step progress bar void CTT32App::ProgressBarStep() { if (wxTheApp == nullptr) return; wxGetApp().AddPendingEvent(MyThreadEvent(IDC_PROGRESSBAR_STEP)); } void CTT32App::ProgressBarExit(int retCode) { if (wxTheApp == nullptr) return; wxGetApp().AddPendingEvent(MyThreadEvent(IDC_PROGRESSBAR_EXIT)); } void CTT32App::OnProgressBarStep(wxThreadEvent &) { if (m_progressDialog) { int val = ((CProgressDialog *) m_progressDialog)->IncrementCounter(); if (val <= m_progressDialog->GetRange()) m_progressDialog->Update(val); else OutputDebugString(wxT("OnProgressBarStep called to many times")); } } void CTT32App::SetProgressBarText(const wxString &text) { if (m_progressDialog) m_progressDialog->Update(0, text); } void CTT32App::OnProgressBarExit(wxThreadEvent &) { if (!m_progressDialog) return; // Ich loesche m_progressDialog, Destruktor oder Update koennten aber wiederum Exit aufrufen wxProgressDialog *tmp = m_progressDialog; m_progressDialog = NULL; if (tmp) tmp->Update(tmp->GetRange()); delete(tmp); } wxPanel * CTT32App::OpenView(const wxString &title, const wxChar *xrcName, ...) { va_list vaList; va_start(vaList, xrcName); return OpenViewChildFrame("ChildFrame", title, xrcName, vaList); } wxPanel * CTT32App::OpenViewNoResize(const wxString &title, const wxChar *xrcName, ...) { va_list vaList; va_start(vaList, xrcName); return OpenViewChildFrame("ChildFrameNoResize", title, xrcName, vaList); } wxPanel * CTT32App::OpenViewChildFrame(const wxString &childFrame, const wxString &title, const wxChar *xrcName, va_list vaList) { CChildFrame *child = (CChildFrame *) wxXmlResource::Get()->LoadObject(m_pMainWnd, childFrame, "wxMDIChildFrame"); CFormViewEx *panel = (CFormViewEx *) wxXmlResource::Get()->LoadPanel(child, xrcName); if (!panel) { delete child; return NULL; } child->SetTitle(title); child->SetIcon(wxIcon("child")); child->SetClientSize(panel->GetSize()); child->SetSize(panel->GetSize()); // child->CenterOnParent(); // panel->RestoreSettings(); panel->GetEventHandler()->ProcessEvent(wxInitDialogEvent()); panel->Edit(vaList); va_end(vaList); child->Show(); return panel; } wxPanel * CTT32App::OpenDialog(bool modal, const wxString &title, const wxChar *xrcName, ...) { va_list vaList; va_start(vaList, xrcName); wxDialog *child = new wxDialog(m_pMainWnd, wxID_ANY, title); CFormViewEx *panel = NULL; if ( !(panel = (CFormViewEx *) wxXmlResource::Get()->LoadPanel(child, xrcName)) ) { delete child; return NULL; } child->SetIcon(wxIcon("child")); child->SetClientSize(panel->GetSize()); child->SetSize(panel->GetSize()); panel->GetEventHandler()->ProcessEvent(wxInitDialogEvent()); panel->Edit(vaList); va_end(vaList); if (modal) child->ShowModal(); else child->Show(); return panel; } // ----------------------------------------------------------------------- void CTT32App::ShowHtmlDialog(const wxString &filename) { wxFileName file; file.SetFullName(filename); // Falls nicht im cwd dann beim Exe suchen (default bei Installation) if (!file.Exists()) file.SetPath(wxFileName(wxStandardPaths::Get().GetExecutablePath()).GetPath()); // Falls auch nicht dort, dann aus workspace (aktuellste Version) if (!file.Exists()) { // file.SetPath("\\user\\cht\\wxTTM\\src\\Resources"); wxFileName exe = wxFileName(wxStandardPaths::Get().GetExecutablePath()); exe.RemoveLastDir(); exe.RemoveLastDir(); exe.RemoveLastDir(); exe.AppendDir("Resources"); wxString path = exe.GetPath(); file.SetPath(path); } if (file.Exists()) wxLaunchDefaultBrowser(file.GetFullPath()); } // ----------------------------------------------------------------------- void CTT32App::ShowAboutDialog() { wxAboutDialogInfo info; info.SetName(wxT("TTM")); info.SetDescription(_T("Table Tennis Manager")); info.SetCopyright(copyright); info.SetVersion(version); info.SetWebSite("http://downloads.ttm.co.at/ttm/changes.html", _("View changes")); #if 0 if (!expire.IsEmpty()) { int day = wxAtoi(expire.c_str()) % 100; int mon = (wxAtoi(expire.c_str()) / 100) % 100; int year = wxAtoi(expire.c_str()) / 10000; struct tm tm; memset(&tm, 0, sizeof(tm)); tm.tm_year = year - 1900; tm.tm_mon = mon-1; tm.tm_mday = day; wxString expireStr = wxDateTime(tm).FormatDate(); info.SetLicense(wxString::Format(_("Licensed by %s. License expires %s"), licensee, expireStr.c_str())); } else { info.SetLicense(wxString::Format(_("Unlicensed copy"))); } #endif ::wxAboutBox(info, m_pMainWnd); } // ----------------------------------------------------------------------- // Turnierspezifische Einstellungen bool CTT32App::GetPrintCombinedScoresheet() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_COMBINED_SCORESHEET, 0) ? true : false; } void CTT32App::SetPrintCombinedScoresheet(bool set) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_COMBINED_SCORESHEET, set ? 1 : 0); } bool CTT32App::GetPrintKONamesBold() const { return false; } int CTT32App::GetPrintAssociation() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION, 1); } void CTT32App::SetPrintAssociation(int set) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION, set); } int CTT32App::GetPrintAssociationTeam() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION_TEAM, 1); } void CTT32App::SetPrintAssociationTeam(int set) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION_TEAM, set); } int CTT32App::GetPrintNationNameWidth() const { // -1 means "auto" int ret = ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION_NAME_WIDTH, -2); if (ret == -2) ret = ttProfile.GetInt(PRF_GLOBAL_SETTINGS, PRF_PRINT_NATION_NAME_WIDTH, -1); return ret; } void CTT32App::SetPrintNationNameWidth(int width) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION_NAME_WIDTH, width); } int CTT32App::GetPrintNationDescWidth() const { // -1 means "auto" int ret = ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION_DESC_WIDTH, -2); if (ret == -2) ret = ttProfile.GetInt(PRF_GLOBAL_SETTINGS, PRF_PRINT_NATION_DESC_WIDTH, -1); return ret; } void CTT32App::SetPrintNationDescWidth(int width) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION_DESC_WIDTH, width); } int CTT32App::GetPrintNationRegionWidth() const { // -1 means "auto" int ret = ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION_REGION_WIDTH, -2); if (ret == -2) ret = ttProfile.GetInt(PRF_GLOBAL_SETTINGS, PRF_PRINT_NATION_REGION_WIDTH, -1); return ret; } void CTT32App::SetPrintNationRegionWidth(int width) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION_REGION_WIDTH, width); } int CTT32App::GetPrintTeamNameWidth() const { // -1 means "auto" int ret = ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_TEAM_NAME_WIDTH, -2); if (ret == -2) ret = ttProfile.GetInt(PRF_GLOBAL_SETTINGS, PRF_PRINT_TEAM_NAME_WIDTH, -1); return ret; } void CTT32App::SetPrintTeamNameWidth(int width) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_TEAM_NAME_WIDTH, width); } int CTT32App::GetPrintStartNrWidth() const { // -1 means "auto" int ret = ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_PLNR_WIDTH, -2); if (ret == -2) // Undefined, try global ret = ttProfile.GetInt(PRF_GLOBAL_SETTINGS, PRF_PRINT_PLNR_WIDTH, -1); return ret; } void CTT32App::SetPrintStartNrWidth(int width) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_PLNR_WIDTH, width); } bool CTT32App::GetPrintPreview() const { if ( ttProfile.GetInt(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_PREVIEW, 0) ) return true; return false; } void CTT32App::SetPrintPreview(bool state) const { ttProfile.AddInt(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_PREVIEW, state ? 1 : 0); if (state) ttProfile.AddInt(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_PDF, 0); } bool CTT32App::GetPrintPdf() const { if ( ttProfile.GetInt(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_PDF, 0) ) return true; return false; } void CTT32App::SetPrintPdf(bool state) const { ttProfile.AddInt(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_PDF, state ? 1 : 0); if (state) ttProfile.AddInt(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_PREVIEW, 0); } double CTT32App::GetPrintCaptionMarginKO() const { return ((double) ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_CAPTIONMARGINKO, 100)) / 100.; } void CTT32App::SetPrintCaptionMarginKO(double margin) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_CAPTIONMARGINKO, std::floor(100. * margin)); } wxString CTT32App::GetDateFormat() const { wxString format = ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_SETTINGS_DATESTRING); if (format.IsEmpty()) format = ttProfile.GetString(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_DATESTRING, wxT("%a, %d %b")); // %d %b %y return format; } wxString CTT32App::GetTimeFormat() const { wxString format = ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_SETTINGS_TIMESTRING); if (format.IsEmpty()) format = ttProfile.GetString(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_TIMESTRING, wxT("%H:%M")); return format; } // ----------------------------------------------------------------------- wxString CTT32App::GetTournament() const { return tournament; } wxString CTT32App::GetPath() const { return wxString(ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_PATH)); } wxString CTT32App::GetBackupPath() const { return wxString(ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPPATH)); } void CTT32App::SetBackupPath(const wxString &path) { ttProfile.AddString(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPPATH, path); } int CTT32App::GetBackupTime() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPTIME, 30); } void CTT32App::SetBackupTime(int t) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPTIME, t); } bool CTT32App::GetBackupAppendTimestamp() const { return ttProfile.GetBool(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPAPPENDTIMESTAMP, false); } void CTT32App::SetBackupAppendTimestamp(bool a) { ttProfile.AddBool(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPAPPENDTIMESTAMP, a); } bool CTT32App::GetBackupKeepLast() const { // Make sure at least one if "append timestamp" and "keep last" is set return ttProfile.GetBool(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPKEEPLAST, !GetBackupAppendTimestamp()); } void CTT32App::SetBackupKeepLast(bool a) { ttProfile.AddBool(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPKEEPLAST, a); } int CTT32App::GetBackupKeepNofItems() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPKEEPNOFITEMS, 0); } void CTT32App::SetBackupKeepNofItems(int a) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPKEEPNOFITEMS, a); } void CTT32App::SetDefaultCP(const wxString &cpName) const { ttProfile.AddString(PRF_LOCAL_SETTINGS, PRF_DEFCP, cpName); ((CMainFrame *) m_pMainWnd)->SetDefaultCP(cpName); } void CTT32App::SetDefaultGR(const wxString &grName) const { ttProfile.AddString(PRF_LOCAL_SETTINGS, PRF_DEFGR, grName); ((CMainFrame *) m_pMainWnd)->SetDefaultGR(grName); } void CTT32App::SetDefaultNA(const wxString &naName) const { ttProfile.AddString(PRF_LOCAL_SETTINGS, PRF_DEFNA, naName); ((CMainFrame *) m_pMainWnd)->SetDefaultNA(naName); } wxString CTT32App::GetDefaultCP() const { return ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_DEFCP); } wxString CTT32App::GetDefaultGR() const { return ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_DEFGR); } wxString CTT32App::GetDefaultNA() const { return ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_DEFNA); } void CTT32App::SetType(short type, bool writeDB) { if (type == GetType()) return; if (writeDB) IdStore::SetType(type); ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_TYPE, type); } short CTT32App::GetType() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_TYPE); } short CTT32App::GetDefaultType() const { return defaultType; } void CTT32App::SetTable(short table, bool writeDB) { if (table == GetTable()) return; if (writeDB) IdStore::SetTable(table); ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_TABLE, table); } short CTT32App::GetTable() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_TABLE); } short CTT32App::GetDefaultTable() const { return defaultTable; } void CTT32App::SetReportTitle(const wxString &title, bool writeDB) const { wxString oldTitle = GetReportTitle(); if (!oldTitle.IsEmpty() && !title.IsEmpty() && !wxStrcoll(oldTitle, title)) return; if (writeDB) IdStore::SetReportTitle(title); ttProfile.AddString(PRF_LOCAL_SETTINGS, PRF_STRTITLE, title); } wxString CTT32App::GetReportTitle() const { return ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_STRTITLE); } void CTT32App::SetReportSubtitle(const wxString &subtitle, bool writeDB) const { wxString oldSubTitle = GetReportSubtitle(); if (oldSubTitle.IsEmpty() && subtitle.IsEmpty() && !wxStrcoll(oldSubTitle, subtitle)) return; if (writeDB) IdStore::SetReportSubtitle(subtitle); ttProfile.AddString(PRF_LOCAL_SETTINGS, PRF_STRSUBTITLE, subtitle); } wxString CTT32App::GetReportSubtitle() const { return ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_STRSUBTITLE); } bool CTT32App::GetPrintBanner() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTBANNER, 0) != 0; } void CTT32App::SetPrintBanner(bool printBanner) const { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTBANNER, printBanner ? 1 : 0); } bool CTT32App::GetPrintLogo() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTLOGO, 0) != 0; } void CTT32App::SetPrintLogo(bool printLogo) const { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTLOGO, printLogo? 1 : 0); } bool CTT32App::GetPrintSponsor() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTSPONSOR, 0) != 0; } void CTT32App::SetPrintSponsor(bool printSponsor) const { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTSPONSOR, printSponsor ? 1 : 0); } wxString CTT32App::GetPrintLanguage() const { wxString printLang = ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTLANG); if (!printLang) printLang = ttProfile.GetString(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_LANGUAGE); return printLang; } void CTT32App::SetPrintLanguage(const wxString &printLang) { ttProfile.AddString(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTLANG, printLang); } bool CTT32App::GetPrintScaleToPaperSize() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTSCALEPAPER, 0) != 0; } void CTT32App::SetPrintScaleToPaperSize(bool printScale) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTSCALEPAPER, printScale ? 1 : 0); } wxString CTT32App::GetLanguage() const { wxString lang = ttProfile.GetString(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_LANGUAGE); if (!lang) lang = wxLocale(wxLocale::GetSystemLanguage()).GetCanonicalName(); return lang; } void CTT32App::SetLanguage(const wxString &lang) { ttProfile.AddString(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_LANGUAGE, lang); const wxLanguageInfo *info = wxLocale::FindLanguageInfo(lang); wxTranslations *trans = new wxTranslations(); if (info) trans->SetLanguage(info->CanonicalName); wxTranslations::Set(trans); } bool CTT32App::GetPrintPlayersSignature() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREPLSIG, 1) != 0; } void CTT32App::SetPrintPlayersSignature(bool f, bool writeDB) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREPLSIG, f ? 1 : 0); if (writeDB) IdStore::SetPrintPlayersSignature(f); } bool CTT32App::GetPrintScoreCoaches() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCORECOACHES, 1) != 0; } void CTT32App::SetPrintScoreCoaches(bool f, bool writeDB) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCORECOACHES, f ? 1 : 0); if (writeDB) IdStore::SetPrintScoreCoaches(f); } bool CTT32App::GetPrintScoreUmpires() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREUMPIRES, 1) != 0; } void CTT32App::SetPrintScoreUmpires(bool f, bool writeDB) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREUMPIRES, f ? 1 : 0); if (writeDB) IdStore::SetPrintScoreUmpires(f); } bool CTT32App::GetPrintScoreExtras() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREEXTRAS, 0) != 0; } bool CTT32App::GetPrintScoreUmpireName() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREUMPIRENAME, 1) != 0; } void CTT32App::SetPrintScoreUmpireName(bool f, bool writeDB) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREUMPIRENAME, f ? 1 : 0); if (writeDB) IdStore::SetPrintScoreUmpireName(f); } void CTT32App::SetPrintScoreExtras(bool f, bool writeDB) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREEXTRAS, f ? 1 : 0); if (writeDB) IdStore::SetPrintScoreExtras(f); } bool CTT32App::GetPrintScoreStartEnd() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCORESTARTENDTIME, 0) != 0; } void CTT32App::SetPrintScoreStartEnd(bool f, bool writeDB) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCORESTARTENDTIME, f ? 1 : 0); if (writeDB) IdStore::SetPrintScoreRemarks(f); } bool CTT32App::GetPrintScoreRemarks() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREREMARKS, 0) != 0; } void CTT32App::SetPrintScoreRemarks(bool f, bool writeDB) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREREMARKS, f ? 1 : 0); if (writeDB) IdStore::SetPrintScoreRemarks(f); } bool CTT32App::GetPrintScoreServiceTimeout() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCORESERVICETIMEOUT, 0) != 0; } void CTT32App::SetPrintScoreServiceTimeout(bool f, bool writeDB) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCORESERVICETIMEOUT, f ? 1 : 0); if (writeDB) IdStore::SetPrintScoreServiceTimeout(f); } void CTT32App::SetOvFgColor(const wxString &which, const wxColor &color) { wxArrayString colors = wxStringTokenize(ttProfile.GetString(PRF_SETTINGS, PRF_OVLIST_COLORS, ""), ";"); wxString result; bool found = false; for (size_t i = 0; i < colors.GetCount(); i++) { wxString tmp = colors[i]; if (tmp.StartsWith(which + ":")) { found = true; wxArrayString sa = wxStringTokenize(tmp.Mid(which.Length() + 1), " "); result += which; result += ":"; result += ColorToString(color); result += " "; if (sa.GetCount() > 1) result += sa[1]; else result += ColorToString(wxNullColour); result += ";"; } else result += tmp + ";"; } if (!found) { result += which; result += ":"; result += color.GetAsString(wxC2S_HTML_SYNTAX); result += " "; result += ColorToString(wxNullColour); result += ";"; } ttProfile.AddString(PRF_SETTINGS, PRF_OVLIST_COLORS, result); } wxColor CTT32App::GetOvFgColor(const wxString &which) const { wxArrayString colors = wxStringTokenize(ttProfile.GetString(PRF_SETTINGS, PRF_OVLIST_COLORS, ""), ";"); wxColor result = wxNullColour; for (size_t i = 0; i < colors.GetCount(); i++) { wxString tmp = colors[i]; if (tmp.StartsWith(which + ":")) { wxArrayString sa = wxStringTokenize(tmp.Mid(which.Length() + 1), " "); if (sa.GetCount() > 0) result = StringToColor(sa[0]); break; } } return result; } void CTT32App::SetOvBkColor(const wxString &which, const wxColor &color) { wxArrayString colors = wxStringTokenize(ttProfile.GetString(PRF_SETTINGS, PRF_OVLIST_COLORS, ""), ";"); wxString result; bool found = false; for (size_t i = 0; i < colors.GetCount(); i++) { wxString tmp = colors[i]; if (tmp.StartsWith(which + ":")) { found = true; wxArrayString sa = wxStringTokenize(tmp.Mid(which.Length() + 1), " "); result += which; result += ":"; if (sa.GetCount() > 0) result += sa[0]; else result += ColorToString(wxNullColour); result += " "; result += ColorToString(color); result += ";"; } else result += tmp + ";"; } if (!found) { result += which; result += ":"; result += ColorToString(wxNullColour); result += " "; result += ColorToString(color); result += ";"; } ttProfile.AddString(PRF_SETTINGS, PRF_OVLIST_COLORS, result); } wxColor CTT32App::GetOvBkColor(const wxString &which) const { wxArrayString colors = wxStringTokenize(ttProfile.GetString(PRF_SETTINGS, PRF_OVLIST_COLORS, ""), ";"); wxColor result = wxNullColour; for (size_t i = 0; i < colors.GetCount(); i++) { wxString tmp = colors[i]; if (tmp.StartsWith(which + ":")) { wxArrayString sa = wxStringTokenize(tmp.Mid(which.Length() + 1), " "); if (sa.GetCount() > 1) result = StringToColor(sa[1]); break; } } return result; } // ----------------------------------------------------------------------- bool CTT32App::CreateTournament( const wxString &name, const wxString &database, const wxString &server, bool windowsAuthentication, const wxString &user, const wxString &passwd, short type, short table) { #if 0 if (expire.IsEmpty()) { if (server.IsEmpty() || TTDbse::IsLocalAddress(server)) { infoSystem.Error(_("No valid license found")); return false; } } #endif if (name == "") { infoSystem.Error(_("Illegal tournament name")); return false; } if (database == "") { infoSystem.Error(_("Illegal database name")); return false; } static const char chars[] = "abcdefghijklmnopqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"; for (const char *ptr = database.data(); *ptr; ptr++) { if (strchr(chars, *ptr) == NULL) { infoSystem.Error(_("Illegal database name")); return false; } } CloseTournament(); if (!TTDbse::instance()->CreateDatabase(database, server, windowsAuthentication, user, passwd, type, table)) return false; char *tmp = _getcwd(NULL, _MAX_PATH); wxString dir = wxString(tmp) + "\\" + database; free(tmp); // Falls es eine remote DB war _mkdir(dir.data()); m_pMainWnd->SetTitle(wxT("TTM - ") + name); // Update TT32.ini wxString connStr = TTDbse::instance()->GetConnectionString(); ttProfile.AddString(PRF_TURNIER, name.data(), connStr.data()); ttProfile.AddString(PRF_OPEN, PRF_LAST, name.data()); ttProfile.AddString(name.data(), PRF_PATH, database.data()); // SetXXX will das Turnier haben. tournament = name; SetMenuBar("ITTFMenuBar"); // Nur in lokaler DB auch in DB schreiben, sonst nur in ini file SetType(type, TTDbse::IsLocalAddress(server)); SetTable(table, TTDbse::IsLocalAddress(server)); ((CMainFrame *) m_pMainWnd)->SetDefaultCP(GetDefaultCP()); ((CMainFrame *) m_pMainWnd)->SetDefaultGR(GetDefaultGR()); ((CMainFrame *) m_pMainWnd)->SetDefaultNA(GetDefaultNA()); if (TTDbse::IsLocalAddress(server)) { Connect(wxEVT_TIMER, wxTimerEventHandler(CTT32App::OnTimer), NULL, this); m_backupTimer.Start(GetBackupTime() * 60 * 1000, false); } return true; } bool CTT32App::OpenTournament(const wxString &name) { CloseTournament(); wxString tmp = ttProfile.GetString(PRF_TURNIER, name); if (tmp.IsEmpty()) return false; wxString connStr = tmp; wxString server = TTDbse::GetServer(connStr); wxString database = TTDbse::GetDatabase(connStr); bool throwError = !TTDbse::IsLocalAddress(server); throwError |= database.IsEmpty(); throwError |= _taccess(ttProfile.GetString(name, PRF_PATH).t_str(), 00) != 0; short type = 0; short table = 0; if (!TTDbse::instance()->OpenDatabase(connStr, throwError)) { if (throwError) return false; // Nochmals lesen, tmp ist eine statische Variable in ttProfile tmp = ttProfile.GetString(PRF_TURNIER, name); type = ttProfile.GetInt(name, PRF_SETTINGS_TYPE); table = ttProfile.GetInt(name, PRF_SETTINGS_TABLE); bool trustedConn = TTDbse::GetWindowsAuthentication(connStr); wxString user = trustedConn ? TTDbse::GetUser(connStr) : wxEmptyString; wxString pwd = trustedConn ? TTDbse::GetPassword(connStr) : wxEmptyString; TTDbse::instance()->DetachDatabase(connStr, false); if (!TTDbse::instance()->CreateDatabase(database, server, trustedConn, user, pwd, type, table)) return false; } m_pMainWnd->SetTitle(wxT("TTM - ") + name); ttProfile.AddString(PRF_OPEN, PRF_LAST, name); tournament = name; type = IdStore::GetType(); table = IdStore::GetTable(); if (table == 0) { // Tabelle steht noch nicht in der DB if (ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_TABLE) == -1) { // Auch nicht im Profile, also ermitteln CpListStore cp; cp.SelectAll(); cp.Next(); cp.Close(); short newType = defaultType; if (cp.cpYear == 0) newType = defaultType; else if (cp.cpYear < 1970) newType = TT_SCI; else if (cp.cpYear > 1990) newType = TT_YOUTH; wxString oldType = ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_SETTINGS_TYPE); if (!oldType) { IdStore::SetType(newType); IdStore::SetTable(defaultTable); } else if (!wxStrcmp(wxT("SCI"), oldType)) { IdStore::SetType(newType); IdStore::SetTable(TT_ITTF); } else if (!wxStrcmp(wxT("DTTB"), oldType)) { IdStore::SetType(newType); IdStore::SetTable(TT_DTTB); } else { IdStore::SetType(newType); IdStore::SetTable(TT_ITTF); } IdStore::SetReportTitle(GetReportTitle()); IdStore::SetReportSubtitle(GetReportSubtitle()); } } // Intern cachen, ohne in die DB zu schreiben SetType(IdStore::GetType(), false); SetTable(IdStore::GetTable(), false); SetReportTitle(IdStore::GetReportTitle().data(), false); SetReportSubtitle(IdStore::GetReportSubtitle().data(), false); SetPrintScoreExtras(IdStore::GetPrintScoreExtras(), false); SetPrintPlayersSignature(IdStore::GetPrintPlayersSignature(), false); SetPrintScoreRemarks(IdStore::GetPrintScoreRemarks(), false); SetPrintScoreCoaches(IdStore::GetPrintScoreCoaches(), false); SetPrintScoreUmpires(IdStore::GetPrintScoreUmpires(), false); SetPrintScoreServiceTimeout(IdStore::GetPrintScoreServiceTimeout(), false); SetMenuBar("ITTFMenuBar"); ((CMainFrame *) m_pMainWnd)->SetDefaultCP(GetDefaultCP()); ((CMainFrame *) m_pMainWnd)->SetDefaultGR(GetDefaultGR()); ((CMainFrame *) m_pMainWnd)->SetDefaultNA(GetDefaultNA()); if (connStr.find(wxString("localhost")) != wxString::npos) { Connect(wxEVT_TIMER, wxTimerEventHandler(CTT32App::OnTimer), NULL, this); m_backupTimer.Start(GetBackupTime() * 60 * 1000, false); } return true; } bool CTT32App::OpenLastTournament() { wxString tour = ttProfile.GetString(PRF_OPEN, PRF_LAST); if (!tour.IsEmpty()) return OpenTournament(tour); return false; } bool CTT32App::CloseTournament() { wxWindowList list = m_pMainWnd->GetChildren(); for (wxWindowList::iterator it = list.begin(); it != list.end(); it++) (*it)->Close(); m_pMainWnd->SetTitle(wxT("TTM")); // ttProfile.DeleteString(PRF_OPEN, PRF_LAST); tournament = ""; SetMenuBar("NOMenuBar"); if (m_backupTimer.IsRunning()) { Disconnect(wxEVT_TIMER, wxTimerEventHandler(CTT32App::OnTimer), NULL, this); m_backupTimer.Stop(); } TTDbse::instance()->CloseDatabase(); return true; } bool CTT32App::DetachTournament(const wxString &name, bool deleteDir) { wxString tmp = ttProfile.GetString(PRF_TURNIER, name.data()); if (!tmp) return false; if (name == tournament) CloseTournament(); wxString connStr = tmp; // Wenn es eine lokale DB ist, im Server austragen. if (TTDbse::IsLocalAddress(TTDbse::GetServer(connStr))) { // Im Fehlerfall das ini-File belassen if (!TTDbse::instance()->DetachDatabase(connStr)) return false; } if (deleteDir) { wxString dir = ttProfile.GetString(name, PRF_PATH); if (!dir.IsEmpty()) wxFileName::Rmdir(dir, wxPATH_RMDIR_RECURSIVE); ttProfile.DeleteSection(name); } ttProfile.DeleteString(PRF_TURNIER, name); return true; } void CTT32App::ImportOnlineEntries() { CImportOnlineEntries::Import(); } // ----------------------------------------------------------------------- void CTT32App::BackupDatabase() { time_t t = time(NULL); struct tm *tm = localtime(&t); wxChar tmp[16]; wxSprintf(tmp, "-%04d%02d%02dT%02d%02d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min); wxString name = GetDatabase() + tmp + ".bak"; wxFileDialog fileDlg( m_pMainWnd, _("Backup Database"), GetPath(), name, "Backup Files (*.bak)|*.bak|All Files (*.*)|*.*||", wxFD_SAVE); if (fileDlg.ShowModal() != wxID_OK) return; name = fileDlg.GetPath(); wxFileName saveName(name); // Filename fuer Backup wxFileName tmpName(name); // Filename, wie er an die DB uebergeben wird wxFileName dbPath(GetPath()); // Pfad, wo das DB-File liegt saveName.Normalize(); tmpName.Normalize(); dbPath.Normalize(); // dbPath ist ein Verzeichnis, GetFullPath also der komplette Name // tmpName ist ein Dateiname, GetPath also das Verzeichnis ohne Dateiname und -erweiterung if (tmpName.GetPath() != dbPath.GetFullPath()) { tmpName = wxFileName(GetPath(), wxString("tmp-") + fileDlg.GetFilename()).GetFullPath(); tmpName.Normalize(); } m_pMainWnd->SetCursor(wxCURSOR_WAIT); bool res = TTDbse::instance()->BackupDatabase(tmpName.GetFullPath()); // Falls eine temp. Kopie im DB-Verzeichnis gemacht wurde if (res && tmpName != saveName) { wxCopyFile(tmpName.GetFullPath(), saveName.GetFullPath()); wxRemoveFile(tmpName.GetFullPath()); } // Ebenfalls Kopie im alternativen Verzeichnis wxString backupPath = GetBackupPath(); if (!backupPath.IsEmpty() && backupPath != saveName.GetPath()) { wxFileName fn(backupPath, saveName.GetFullName()); if (fn.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL)) wxCopyFile(saveName.GetFullPath(), fn.GetFullPath(), true); } m_pMainWnd->SetCursor(wxCURSOR_DEFAULT); if (res) infoSystem.Information(_("Backup successful")); } void CTT32App::RestoreDatabase() { wxString name = GetDatabase() + ".bak"; wxFileName tmpName(GetPath(), name); tmpName.Normalize(); wxFileDialog fileDlg( m_pMainWnd, _("Backup Database"), GetPath(), name, "Backup Files (*.bak)|*.bak|All Files (*.*)|*.*||", wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (fileDlg.ShowModal() != wxID_OK) return; name = fileDlg.GetPath(); if (name != tmpName.GetFullPath()) { tmpName = wxFileName(GetPath(), wxString("tmp-") + fileDlg.GetFilename()); tmpName.Normalize(); wxCopyFile(name, tmpName.GetFullPath()); } m_pMainWnd->SetCursor(wxCURSOR_WAIT); bool res = TTDbse::instance()->RestoreDatabase(tmpName.GetFullPath(), GetPath()); wxRemoveFile(tmpName.GetFullPath()); m_pMainWnd->SetCursor(wxCURSOR_DEFAULT); if (res) infoSystem.Information(_("Restore successful")); } // ----------------------------------------------------------------------- void CTT32App::OnTimer(wxTimerEvent &evt) { wxChar tmp[16]; *tmp = 0; if (GetBackupAppendTimestamp()) { // Zeitstempel anhaengen, wenn so gewuenscht time_t t = time(NULL); struct tm *tm = localtime(&t); wxSprintf(tmp, "-%04d%02d%02dT%02d%02d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min); } wxChar ps = wxFileName::GetPathSeparator(); wxString path = GetPath(); if (!wxFileName(path).IsAbsolute()) path = wxGetCwd() + ps + GetPath(); // move <database>.<n>.bak to <database>.<n+1>.bak if (CTT32App::GetBackupKeepLast() && CTT32App::instance()->GetBackupKeepNofItems() > 0) { std::vector<wxString> pathes; pathes.push_back(path); if (!GetBackupPath().IsEmpty()) pathes.push_back(GetBackupPath()); for (auto path : pathes) { // Numerierung beginnt bei 0 int nof = CTT32App::GetBackupKeepNofItems() - 1; { // Remove last file wxString ext = wxString::Format(".%d.bak", nof); wxFileName fn(path, GetDatabase() + tmp + ext); if (fn.Exists()) wxRemoveFile(fn.GetFullPath()); } while (nof--) { // Move files to next number wxString extf = wxString::Format(".%d.bak", nof); wxString extt = wxString::Format(".%d.bak", nof + 1); wxFileName fnf(path, GetDatabase() + tmp + extf); wxFileName fnt(path, GetDatabase() + tmp + extt); if (fnf.Exists()) wxRenameFile(fnf.GetFullPath(), fnt.GetFullPath(), true); } { // Move current file to first number wxFileName fnf(path, GetDatabase() + tmp + ".bak"); wxFileName fnt(path, GetDatabase() + tmp + ".0.bak"); if (fnf.Exists()) wxRenameFile(fnf.GetFullPath(), fnt.GetFullPath(), true); } } } // Backup Database m_pMainWnd->SetCursor(wxCURSOR_WAIT); TTDbse::instance()->BackupDatabase(wxFileName(path, GetDatabase() + tmp + ".bak").GetFullPath()); m_pMainWnd->SetCursor(wxCURSOR_DEFAULT); wxString backupPath = GetBackupPath(); if (!backupPath.IsEmpty()) { wxFileName fn(backupPath, GetDatabase() + tmp + ".bak"); if (fn.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL)) wxCopyFile(wxFileName(path, GetDatabase() + tmp + ".bak").GetFullPath(), fn.GetFullPath(), true); } } // ----------------------------------------------------------------------- wxString CTT32App::GetResourcesPath() const { wxFileName file; file.SetFullName(TT_XRCFILE); // Falls nicht im cwd dann beim Exe suchen (default bei Installation) if (!file.Exists()) file.SetPath(wxFileName(wxStandardPaths::Get().GetExecutablePath()).GetPath()); // Falls auch nicht dort, dann aus workspace (aktuellste Version) if (!file.Exists()) { // file.SetPath("\\user\\cht\\wxTTM\\src\\Resources"); wxFileName exe = wxFileName(wxStandardPaths::Get().GetExecutablePath()); exe.RemoveLastDir(); exe.RemoveLastDir(); exe.RemoveLastDir(); exe.AppendDir("Resources"); wxString path = exe.GetPath(); file.SetPath(path); } if (file.Exists()) return file.GetPath(); return ""; } // ----------------------------------------------------------------------- bool CTT32App::IsLicenseValid() const { #if 0 wxString name = wxGetCwd() + wxFileName::GetPathSeparator() + "License.ini"; return CheckLicenseCode(name) && !HasLicenseExpired(name); #else return true; #endif } bool CTT32App::CheckLicenseCode(const wxString &name) const { #if 0 char tmpLicensee[256]; char tmpExpires[256]; char buffer[512]; char code[64]; GetPrivateProfileStringA("License", "licensee", "", tmpLicensee, sizeof(tmpLicensee), name); GetPrivateProfileStringA("License", "expires", "", tmpExpires, sizeof(tmpExpires), name); GetPrivateProfileStringA("License", "code", "", code, sizeof(code), name); strcpy(buffer, tmpLicensee); strcat(buffer, tmpExpires); long tmp = crypt(buffer); return (tmp == atol(code)); #else return true; #endif } bool CTT32App::HasLicenseExpired(const wxString &name) const { #if 0 char tmpExpires[256]; GetPrivateProfileStringA("License", "expires", "", tmpExpires, sizeof(tmpExpires), name); wxString exp = tmpExpires; if (exp.IsEmpty()) return true; time_t t = time(0); struct tm *tm = localtime(&t); int day = wxAtoi(exp.c_str()) % 100; int mon = (wxAtoi(exp.c_str()) / 100) % 100; int year = wxAtoi(exp.c_str()) / 10000; if (tm->tm_year + 1900 > year) return true; else if (tm->tm_year + 1900 < year) return false; if (tm->tm_mon + 1 > mon) return true; else if (tm->tm_mon + 1 < mon) return false; if (tm->tm_mday > day) return true; return false; #else return false; #endif } // ----------------------------------------------------------------------- void CTT32App::CheckForUpdate() { wxURL url("http://downloads.ttm.co.at/ttm/current.txt"); if (url.GetError() == wxURL_NOERR) { wxString newVersionNumnber; wxInputStream *in = url.GetInputStream(); if (in && in->IsOk()) { wxStringOutputStream sos(&newVersionNumnber); in->Read(sos); newVersionNumnber.Trim(); if (newVersionNumnber > versionNumber) { wxDialog * dlg = wxXmlResource::Get()->LoadDialog(m_pMainWnd, "UpdateAvailable"); // Aus seltsamen Gruenden hat der Close-Button nicht die "affirmative ID" dlg->FindWindow("Close")->SetId(dlg->GetAffirmativeId()); dlg->ShowModal(); } else { infoSystem.Information(_("You are using the latest version of TTM")); } return; } } // Irgend ein Fehler ist aufgetreten infoSystem.Error(_("Could not determine the current version of TTM")); } // ----------------------------------------------------------------------- void CTT32App::InstallLicense() { wxString name = "License.ini"; wxFileDialog fileDlg( m_pMainWnd, _("Install License"), wxStandardPaths::Get().GetDocumentsDir(), name, "License Files (*.ini)|*.ini|All Files (*.*)|*.*||", wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (fileDlg.ShowModal() != wxID_OK) return; name = fileDlg.GetPath(); if (!CheckLicenseCode(name)) { infoSystem.Error(_("The license is not valid")); } else if (HasLicenseExpired(name)) { infoSystem.Error(_("The license has expired")); } else if (!::wxCopyFile(name, "License.ini")) { infoSystem.Error(_("Could not copy license file")); } else { infoSystem.Information(_("License file was copied")); ReadLicense(wxGetCwd() + wxFileName::GetPathSeparator() + "License.ini"); } } void CTT32App::ReadLicense(const wxString &name) { // Check License file // Wenn die Lizenz nicht gueltig ist, gelten die hart codierten defaults fuer // Licensee und expire if (wxFile::Exists(name)) { char tmpLicensee[256]; char tmpExpires[256]; char buffer[512]; char code[64]; GetPrivateProfileStringA("License", "licensee", "", tmpLicensee, sizeof(tmpLicensee), name); GetPrivateProfileStringA("License", "expires", "", tmpExpires, sizeof(tmpExpires), name); GetPrivateProfileStringA("License", "code", "", code, sizeof(code), name); strcpy(buffer, tmpLicensee); strcat(buffer, tmpExpires); if (crypt(buffer) == atol(code)) { licensee = tmpLicensee; expire = tmpExpires; defaultType = GetPrivateProfileIntA("Defaults", "Type", TT_REGULAR, name); defaultTable = GetPrivateProfileIntA("Defaults", "Table", -1, name); if (defaultTable == -1) defaultTable = GetPrivateProfileIntA("Defaults", "TableMode", -1, name); if (defaultTable == -1) defaultTable = GetPrivateProfileIntA("Defaults", "GroupMode", -1, name); if (defaultTable == -1) defaultTable = TT_ITTF; } else { licensee = ""; expire = ""; } } else { licensee = ""; expire = ""; } } wxString CTT32App::ColorToString(const wxColor &color) const { if (color == wxNullColour || !color.IsOk()) return "default"; return color.GetAsString(wxC2S_HTML_SYNTAX); } wxColor CTT32App::StringToColor(const wxString &name) const { if (name == "default") return wxNullColour; else return wxColor(name); } void CTT32App::SetMenuBar(const wxString &menuBar) { // m_pMainWnd->SetWindowMenu(NULL); m_pMainWnd->SetMenuBar(wxXmlResource::Get()->LoadMenuBar(menuBar)); }
25.100832
137
0.673505
ttm-tt
b42224b628d49ff61719872ead3497569d73be3d
360
cpp
C++
src/algorithms/insertion_sort.cpp
tmt514/sorting
3fe1ee129392c526d571931058f7726bcdb30ce8
[ "MIT" ]
null
null
null
src/algorithms/insertion_sort.cpp
tmt514/sorting
3fe1ee129392c526d571931058f7726bcdb30ce8
[ "MIT" ]
null
null
null
src/algorithms/insertion_sort.cpp
tmt514/sorting
3fe1ee129392c526d571931058f7726bcdb30ce8
[ "MIT" ]
null
null
null
#include "insertion_sort.h" void InsertionSort::Sort(vector<int> &A) { int n = A.size(); for (int i = 0; i < n; i++) { // 假設 A[0... i-1] 已經排好了。 for (int j = i; j > 0; j--) { if (A[j] < A[j - 1]) { Swap(A[j], A[j - 1]); } else { break; } } } } SorterFactoryRegistrar<Sorter, InsertionSort> InsertionSort::_;
21.176471
63
0.486111
tmt514
b42291cafbc63a20693652b56b1808c6d66c7043
9,581
cpp
C++
catboost/libs/data/load_data.cpp
ZhekehZ/catboost
3f774da539b8e57cca25686b89c473cbd1f61a6c
[ "Apache-2.0" ]
null
null
null
catboost/libs/data/load_data.cpp
ZhekehZ/catboost
3f774da539b8e57cca25686b89c473cbd1f61a6c
[ "Apache-2.0" ]
null
null
null
catboost/libs/data/load_data.cpp
ZhekehZ/catboost
3f774da539b8e57cca25686b89c473cbd1f61a6c
[ "Apache-2.0" ]
null
null
null
#include "baseline.h" #include "load_data.h" #include "cb_dsv_loader.h" #include "data_provider_builders.h" #include <catboost/libs/column_description/cd_parser.h> #include <catboost/libs/helpers/exception.h> #include <catboost/libs/helpers/int_cast.h> #include <catboost/libs/logging/logging.h> #include <util/datetime/base.h> namespace NCB { TDataProviderPtr ReadDataset( const TPathWithScheme& poolPath, const TPathWithScheme& pairsFilePath, // can be uninited const TPathWithScheme& groupWeightsFilePath, // can be uninited const TPathWithScheme& timestampsFilePath, // can be uninited const TPathWithScheme& baselineFilePath, // can be uninited const TPathWithScheme& featureNamesPath, // can be uninited const NCatboostOptions::TColumnarPoolFormatParams& columnarPoolFormatParams, const TVector<ui32>& ignoredFeatures, EObjectsOrder objectsOrder, TDatasetSubset loadSubset, TMaybe<TVector<NJson::TJsonValue>*> classLabels, NPar::TLocalExecutor* localExecutor ) { CB_ENSURE_INTERNAL(!baselineFilePath.Inited() || classLabels, "ClassLabels must be specified if baseline file is specified"); if (classLabels) { UpdateClassLabelsFromBaselineFile(baselineFilePath, *classLabels); } auto datasetLoader = GetProcessor<IDatasetLoader>( poolPath, // for choosing processor // processor args TDatasetLoaderPullArgs { poolPath, TDatasetLoaderCommonArgs { pairsFilePath, groupWeightsFilePath, baselineFilePath, timestampsFilePath, featureNamesPath, classLabels ? **classLabels : TVector<NJson::TJsonValue>(), columnarPoolFormatParams.DsvFormat, MakeCdProviderFromFile(columnarPoolFormatParams.CdFilePath), ignoredFeatures, objectsOrder, 10000, // TODO: make it a named constant loadSubset, localExecutor } } ); THolder<IDataProviderBuilder> dataProviderBuilder = CreateDataProviderBuilder( datasetLoader->GetVisitorType(), TDataProviderBuilderOptions{}, loadSubset, localExecutor ); CB_ENSURE_INTERNAL( dataProviderBuilder, "Failed to create data provider builder for visitor of type " << datasetLoader->GetVisitorType() ); datasetLoader->DoIfCompatible(dynamic_cast<IDatasetVisitor*>(dataProviderBuilder.Get())); return dataProviderBuilder->GetResult(); } TDataProviderPtr ReadDataset( const TPathWithScheme& poolPath, const TPathWithScheme& pairsFilePath, // can be uninited const TPathWithScheme& groupWeightsFilePath, // can be uninited const TPathWithScheme& timestampsFilePath, // can be uninited const TPathWithScheme& baselineFilePath, // can be uninited const TPathWithScheme& featureNamesPath, // can be uninited const NCatboostOptions::TColumnarPoolFormatParams& columnarPoolFormatParams, const TVector<ui32>& ignoredFeatures, EObjectsOrder objectsOrder, int threadCount, bool verbose, TMaybe<TVector<NJson::TJsonValue>*> classLabels ) { NPar::TLocalExecutor localExecutor; localExecutor.RunAdditionalThreads(threadCount - 1); TSetLoggingVerboseOrSilent inThisScope(verbose); TDataProviderPtr dataProviderPtr = ReadDataset( poolPath, pairsFilePath, groupWeightsFilePath, timestampsFilePath, baselineFilePath, featureNamesPath, columnarPoolFormatParams, ignoredFeatures, objectsOrder, TDatasetSubset::MakeColumns(), classLabels, &localExecutor ); return dataProviderPtr; } TDataProviderPtr ReadDataset( THolder<ILineDataReader> poolReader, const TPathWithScheme& pairsFilePath, // can be uninited const TPathWithScheme& groupWeightsFilePath, // can be uninited const TPathWithScheme& timestampsFilePath, // can be uninited const TPathWithScheme& baselineFilePath, // can be uninited const TPathWithScheme& featureNamesPath, // can be uninited const NCB::TDsvFormatOptions& poolFormat, const TVector<TColumn>& columnsDescription, // TODO(smirnovpavel): TVector<EColumn> const TVector<ui32>& ignoredFeatures, EObjectsOrder objectsOrder, TMaybe<TVector<NJson::TJsonValue>*> classLabels, NPar::TLocalExecutor* localExecutor ) { const auto loadSubset = TDatasetSubset::MakeColumns(); THolder<IDataProviderBuilder> dataProviderBuilder = CreateDataProviderBuilder( EDatasetVisitorType::RawObjectsOrder, TDataProviderBuilderOptions{}, loadSubset, localExecutor ); CB_ENSURE_INTERNAL( dataProviderBuilder, "Failed to create data provider builder for visitor of type RawObjectsOrder"; ); TCBDsvDataLoader datasetLoader( TLineDataLoaderPushArgs { std::move(poolReader), TDatasetLoaderCommonArgs { pairsFilePath, groupWeightsFilePath, baselineFilePath, timestampsFilePath, featureNamesPath, classLabels ? **classLabels : TVector<NJson::TJsonValue>(), poolFormat, MakeCdProviderFromArray(columnsDescription), ignoredFeatures, objectsOrder, 10000, // TODO: make it a named constant loadSubset, localExecutor } } ); datasetLoader.DoIfCompatible(dynamic_cast<IDatasetVisitor*>(dataProviderBuilder.Get())); return dataProviderBuilder->GetResult(); } TDataProviders ReadTrainDatasets( const NCatboostOptions::TPoolLoadParams& loadOptions, EObjectsOrder objectsOrder, bool readTestData, TDatasetSubset trainDatasetSubset, TMaybe<TVector<NJson::TJsonValue>*> classLabels, NPar::TLocalExecutor* const executor, TProfileInfo* const profile ) { if (readTestData) { loadOptions.Validate(); } else { loadOptions.ValidateLearn(); } TDataProviders dataProviders; if (loadOptions.LearnSetPath.Inited()) { CATBOOST_DEBUG_LOG << "Loading features..." << Endl; auto start = Now(); dataProviders.Learn = ReadDataset( loadOptions.LearnSetPath, loadOptions.PairsFilePath, loadOptions.GroupWeightsFilePath, loadOptions.TimestampsFilePath, loadOptions.BaselineFilePath, loadOptions.FeatureNamesPath, loadOptions.ColumnarPoolFormatParams, loadOptions.IgnoredFeatures, objectsOrder, trainDatasetSubset, classLabels, executor ); CATBOOST_DEBUG_LOG << "Loading features time: " << (Now() - start).Seconds() << Endl; if (profile) { profile->AddOperation("Build learn pool"); } } dataProviders.Test.resize(0); if (readTestData) { CATBOOST_DEBUG_LOG << "Loading test..." << Endl; for (int testIdx = 0; testIdx < loadOptions.TestSetPaths.ysize(); ++testIdx) { const NCB::TPathWithScheme& testSetPath = loadOptions.TestSetPaths[testIdx]; const NCB::TPathWithScheme& testPairsFilePath = testIdx == 0 ? loadOptions.TestPairsFilePath : NCB::TPathWithScheme(); const NCB::TPathWithScheme& testGroupWeightsFilePath = testIdx == 0 ? loadOptions.TestGroupWeightsFilePath : NCB::TPathWithScheme(); const NCB::TPathWithScheme& testTimestampsFilePath = testIdx == 0 ? loadOptions.TestTimestampsFilePath : NCB::TPathWithScheme(); const NCB::TPathWithScheme& testBaselineFilePath = testIdx == 0 ? loadOptions.TestBaselineFilePath : NCB::TPathWithScheme(); TDataProviderPtr testDataProvider = ReadDataset( testSetPath, testPairsFilePath, testGroupWeightsFilePath, testTimestampsFilePath, testBaselineFilePath, loadOptions.FeatureNamesPath, loadOptions.ColumnarPoolFormatParams, loadOptions.IgnoredFeatures, objectsOrder, TDatasetSubset::MakeColumns(), classLabels, executor ); dataProviders.Test.push_back(std::move(testDataProvider)); if (profile && (testIdx + 1 == loadOptions.TestSetPaths.ysize())) { profile->AddOperation("Build test pool"); } } } return dataProviders; } } // NCB
39.266393
133
0.602547
ZhekehZ
b4232b8a0751bd384cf1aa00e9995636b242165c
3,084
cpp
C++
Source/CPP_Tutorial/CPP_TutorialGameMode.cpp
Mordil/UE4-CPP-Tutorial
0ad3a50c0ef71949db25c67010738486e49c32fc
[ "MIT" ]
null
null
null
Source/CPP_Tutorial/CPP_TutorialGameMode.cpp
Mordil/UE4-CPP-Tutorial
0ad3a50c0ef71949db25c67010738486e49c32fc
[ "MIT" ]
null
null
null
Source/CPP_Tutorial/CPP_TutorialGameMode.cpp
Mordil/UE4-CPP-Tutorial
0ad3a50c0ef71949db25c67010738486e49c32fc
[ "MIT" ]
null
null
null
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "CPP_Tutorial.h" #include "Kismet/GameplayStatics.h" #include "Blueprint/UserWidget.h" #include "CPP_TutorialGameMode.h" #include "CPP_TutorialCharacter.h" #include "SpawnVolume.h" ACPP_TutorialGameMode::ACPP_TutorialGameMode() { // set default pawn class to our Blueprinted character static ConstructorHelpers::FClassFinder<APawn> PlayerPawnBPClass(TEXT("/Game/ThirdPersonCPP/Blueprints/ThirdPersonCharacter")); if (PlayerPawnBPClass.Class != NULL) { DefaultPawnClass = PlayerPawnBPClass.Class; } DecayRate = .01f; } void ACPP_TutorialGameMode::BeginPlay() { Super::BeginPlay(); // find all spawn volume Actors TArray<AActor*> foundActors; UGameplayStatics::GetAllActorsOfClass(GetWorld(), ASpawnVolume::StaticClass(), foundActors); for (auto actor : foundActors) { ASpawnVolume* spawnVolumeActor = Cast<ASpawnVolume>(actor); if (spawnVolumeActor) { _spawnVolumeActors.AddUnique(spawnVolumeActor); } } SetCurrentState(BatteryPlayState::Playing); // set the score to beat ACPP_TutorialCharacter* MyCharacter = Cast<ACPP_TutorialCharacter>(UGameplayStatics::GetPlayerPawn(this, 0)); if (MyCharacter) { PowerToWin = (MyCharacter->GetInitialPower()) * 1.25f; } if (HUDWidgetClass != nullptr) { CurrentWidget = CreateWidget<UUserWidget>(GetWorld(), HUDWidgetClass); if (CurrentWidget != nullptr) { CurrentWidget->AddToViewport(); } } } void ACPP_TutorialGameMode::Tick(float DeltaTime) { Super::Tick(DeltaTime); ACPP_TutorialCharacter* MyCharacter = Cast<ACPP_TutorialCharacter>(UGameplayStatics::GetPlayerPawn(this, 0)); if (MyCharacter) { if (MyCharacter->GetCurrentPower() > PowerToWin) { SetCurrentState(BatteryPlayState::Won); } else if (MyCharacter->GetCurrentPower() > 0) { MyCharacter->UpdatePower(-DeltaTime * DecayRate * (MyCharacter->GetInitialPower())); } else { SetCurrentState(BatteryPlayState::GameOver); } } } void ACPP_TutorialGameMode::SetCurrentState(BatteryPlayState newState) { _currentState = newState; _handleNewState(_currentState); } void ACPP_TutorialGameMode::_handleNewState(BatteryPlayState newState) { auto setVolumesActiveState = [&](bool valueToSet) { for (auto volume : _spawnVolumeActors) { volume->SetSpawningActive(valueToSet); } }; switch (newState) { case BatteryPlayState::Playing: { setVolumesActiveState(true); break; } case BatteryPlayState::Won: { setVolumesActiveState(false); break; } case BatteryPlayState::GameOver: { setVolumesActiveState(false); APlayerController* PlayerController = UGameplayStatics::GetPlayerController(this, 0); if (PlayerController) { PlayerController->SetCinematicMode(true, false, false, true, true); } ACharacter* MyCharacter = UGameplayStatics::GetPlayerCharacter(this, 0); if (MyCharacter) { MyCharacter->GetMesh()->SetSimulatePhysics(true); MyCharacter->GetMovementComponent()->MovementState.bCanJump = false; } break; } case BatteryPlayState::Unknown: default: break; } }
22.510949
128
0.74773
Mordil
b4242721bfa66823bdf0269a54f9be88bb901581
1,873
cpp
C++
dlib/dlib/matlab/example_mex_class.cpp
mohitjain4395/mosip
20ee978dc539be42c8b79cd4b604fdf681e7b672
[ "MIT" ]
11,719
2015-01-03T22:38:57.000Z
2022-03-30T21:45:04.000Z
dlib/matlab/example_mex_class.cpp
KiLJ4EdeN/dlib
eb1f08ce6ab3ca6f9d10425d899103de3c0df56c
[ "BSL-1.0" ]
2,518
2015-01-04T04:38:06.000Z
2022-03-31T11:55:43.000Z
dlib/matlab/example_mex_class.cpp
KiLJ4EdeN/dlib
eb1f08ce6ab3ca6f9d10425d899103de3c0df56c
[ "BSL-1.0" ]
3,308
2015-01-01T14:34:16.000Z
2022-03-31T07:20:07.000Z
// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt /* This mex file will create a MATLAB function called example_mex_class. If you call it with no arguments it will output the MATLAB .m code to create a MATLAB wrapper class. Paste that code into a .m file. Then you will be able to work with this C++ class directly in MATLAB. */ #include <iostream> #include <dlib/matrix.h> using namespace std; using namespace dlib; class example_class { public: // The class must have a default constructor. It's also the only kind of constructor // you can call from MATLAB. example_class() { xx.set_size(3,2); xx = 1; } // The rest of the member functions that you want to bind have to return void and // generally have the same syntax limitations as regular mex funcitons. void do_stuff(const matrix_colmajor& x) { cout << "in do_stuff" << endl; cout << x << endl; xx = x; } void do_other_stuff(int x) { cout << "in do_other_stuff" << endl; cout << "x: " << x << endl; } void print_state() { cout << xx << endl; } // saveobj() and load_obj() are special functions. If you provide these then you will // be able to save() and load() your objects using MATLAB's built in object // serialization. void saveobj(matrix_colmajor& state) { // save this object's state to state. state = xx; } void load_obj(const matrix_colmajor& state) { xx = state; } private: matrix_colmajor xx; }; // Just tell the mex wrapper the name of your class and list the methods you want to bind. #define MEX_CLASS_NAME example_class #define MEX_CLASS_METHODS do_stuff, do_other_stuff, print_state, saveobj, load_obj #include "mex_wrapper.cpp"
25.657534
91
0.651361
mohitjain4395
b4273506d5ef8e09b196621a037933b39a9e98d6
23,939
cpp
C++
os_frt.cpp
asheraryam/frt
d2803cd3877f6b6904664bc9b46cb5ff9db3c5a5
[ "MIT-0", "MIT" ]
null
null
null
os_frt.cpp
asheraryam/frt
d2803cd3877f6b6904664bc9b46cb5ff9db3c5a5
[ "MIT-0", "MIT" ]
null
null
null
os_frt.cpp
asheraryam/frt
d2803cd3877f6b6904664bc9b46cb5ff9db3c5a5
[ "MIT-0", "MIT" ]
null
null
null
// os_frt.cpp /* * FRT - A Godot platform targeting single board computers * Copyright (c) 2017-2019 Emanuele Fornara * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <unistd.h> #include "core/version.h" #include "core/os/os.h" #include "core/os/input.h" #include "core/os/file_access.h" #include "drivers/unix/os_unix.h" #include "servers/visual_server.h" #include "servers/visual/rasterizer.h" #include "servers/audio/audio_driver_dummy.h" #include "servers/visual/visual_server_raster.h" #include "drivers/alsa/audio_driver_alsa.h" #include "drivers/pulseaudio/audio_driver_pulseaudio.h" #include "main/main.h" #include "main/input_default.h" #include "main/performance.h" #include "core/print_string.h" #define VIDEO_DRIVER_GLES2 0 #define VIDEO_DRIVER_GLES3 1 #if VERSION_MAJOR == 2 #define VIDEO_DRIVER_COUNT 1 #include "platform/x11/joystick_linux.h" #include "servers/visual/visual_server_wrap_mt.h" #include "servers/audio/audio_server_sw.h" #include "servers/audio/sample_manager_sw.h" #include "servers/spatial_sound/spatial_sound_server_sw.h" #include "servers/spatial_sound_2d/spatial_sound_2d_server_sw.h" #include "servers/physics_server.h" #include "servers/physics/physics_server_sw.h" #include "servers/physics_2d/physics_2d_server_sw.h" #include "servers/physics_2d/physics_2d_server_wrap_mt.h" #include "drivers/gles2/rasterizer_gles2.h" static int event_id = 0; class InputModifierStateSetter { private: InputModifierState &mod; public: InputModifierStateSetter(InputModifierState &m) : mod(m) {} void set_shift(bool v) { mod.shift = v; } void set_control(bool v) { mod.control = v; } void set_alt(bool v) { mod.alt = v; } void set_metakey(bool v) { mod.meta = v; } }; class InputEventKeySetter : public InputModifierStateSetter { private: InputEvent &event; public: InputEventKeySetter(InputEvent &ev) : InputModifierStateSetter(ev.key.mod), event(ev) { event.type = InputEvent::KEY; event.device = 0; } void set_pressed(bool v) { event.key.pressed = v; } void set_scancode(uint32_t v) { event.key.scancode = v; } void set_unicode(uint32_t v) { event.key.unicode = v; } void set_echo(bool v) { event.key.echo = v; } }; class InputEventMouseMotionSetter : public InputModifierStateSetter { private: InputEvent &event; public: InputEventMouseMotionSetter(InputEvent &ev) : InputModifierStateSetter(ev.mouse_motion.mod), event(ev) { event.type = InputEvent::MOUSE_MOTION; event.device = 0; } void set_button_mask(int v) { event.mouse_motion.button_mask = v; } void set_position(const Vector2 &v) { event.mouse_motion.x = v.x; event.mouse_motion.y = v.y; } void set_global_position(const Vector2 &v) { event.mouse_motion.global_x = v.x; event.mouse_motion.global_y = v.y; } void set_speed(const Vector2 &v) { event.mouse_motion.speed_x = v.x; event.mouse_motion.speed_y = v.y; } void set_relative(const Vector2 &v) { event.mouse_motion.relative_x = v.x; event.mouse_motion.relative_y = v.y; } }; class InputEventMouseButtonSetter : public InputModifierStateSetter { private: InputEvent &event; public: InputEventMouseButtonSetter(InputEvent &ev) : InputModifierStateSetter(ev.mouse_button.mod), event(ev) { event.type = InputEvent::MOUSE_BUTTON; event.device = 0; } void set_button_mask(int v) { event.mouse_button.button_mask = v; } void set_position(const Vector2 &v) { event.mouse_button.x = v.x; event.mouse_button.y = v.y; } void set_global_position(const Vector2 &v) { event.mouse_button.global_x = v.x; event.mouse_button.global_y = v.y; } void set_pressed(bool v) { event.mouse_button.pressed = v; } void set_button_index(int v) { event.mouse_button.button_index = v; } void set_doubleclick(bool v) { event.mouse_button.doubleclick = v; } }; class InputModifierRef { private: InputModifierStateSetter setter; public: InputModifierRef(InputModifierStateSetter &s) : setter(s) {} InputModifierStateSetter *operator->() { return &setter; } }; template <typename T> class InputEventRef { private: InputEvent event; T setter; InputModifierRef mod; public: InputEventRef() : setter(event), mod(setter) { event.ID = ++event_id; }; void instance() {} operator InputEvent() { return event; } operator InputModifierRef() { return mod; } T *operator->() { return &setter; } }; #define INPUT_MODIFIER_REF InputModifierRef #define INPUT_EVENT_REF(t) InputEventRef<t##Setter> #include "core/globals.h" #define PROJECT_SETTINGS \ Globals *project_settings = Globals::get_singleton(); #elif VERSION_MAJOR == 3 #define VIDEO_DRIVER_COUNT 2 #include "platform/x11/joypad_linux.h" #include "drivers/gles3/rasterizer_gles3.h" #define FRT_DL_SKIP #include "drivers/gles2/rasterizer_gles2.h" typedef AudioDriverManager AudioDriverManagerSW; typedef AudioDriver AudioDriverSW; #define set_mouse_pos set_mouse_position #define get_mouse_pos get_mouse_position #define get_mouse_speed get_last_mouse_speed #define has has_setting #define FRT_MOCK_GODOT_INPUT_MODIFIER_STATE #define INPUT_MODIFIER_REF Ref<InputEventWithModifiers> #define INPUT_EVENT_REF(t) Ref<t> #define joystick_linux JoypadLinux #include "core/project_settings.h" #define PROJECT_SETTINGS \ ProjectSettings *project_settings = ProjectSettings::get_singleton(); #else #error "unhandled godot version" #endif #include "frt.h" #include "bits/mouse_virtual.h" using namespace frt; namespace frt { extern const char *perfmon_filename; extern const char *extract_resource_name; } static class PerfMon { private: FILE *f; char sep; void init_separator() { char s[32]; snprintf(s, sizeof(s), "%f", 2.5); s[sizeof(s) - 1] = '\0'; sep = strchr(s, ',') ? ';' : ','; } public: PerfMon() : f(0) {} ~PerfMon() { cleanup(); } bool is_valid() { return f; } void init() { if (!perfmon_filename) return; if (!(f = fopen(perfmon_filename, "w"))) return; init_separator(); Performance *p = Performance::get_singleton(); fprintf(f, "time/ticks_ms"); for (int i = 0; i < Performance::MONITOR_MAX; i++) fprintf(f, "%c%s", sep, p->get_monitor_name(Performance::Monitor(i)).ascii().get_data()); fprintf(f, "\n"); } void iteration(uint32_t t) { if (!f) return; Performance *p = Performance::get_singleton(); fprintf(f, "%u", (unsigned int)t); for (int i = 0; i < Performance::MONITOR_MAX; i++) fprintf(f, "%c%f", sep, p->get_monitor(Performance::Monitor(i))); fprintf(f, "\n"); } void cleanup() { if (f) fclose(f); f = 0; } } perfmon; class OS_FRT : public OS_Unix, public Runnable { private: App *app; Param *disable_meta_keys_param; Param *exit_on_shiftenter_param; Env *env; Vec2 screen_size; ContextGL *context_gl; VisualServer *visual_server; VideoMode current_videomode; int current_video_driver; List<String> args; MainLoop *main_loop; #ifdef PULSEAUDIO_ENABLED AudioDriverPulseAudio driver_pulseaudio; #endif #ifdef ALSA_ENABLED AudioDriverALSA driver_alsa; #endif AudioDriverDummy driver_dummy; int audio_driver_index; Point2 mouse_pos; Point2 last_mouse_pos; bool last_mouse_pos_valid; MouseMode mouse_mode; int mouse_state; bool grab; #if VERSION_MAJOR == 2 PhysicsServer *physics_server; Physics2DServer *physics_2d_server; Rasterizer *rasterizer; AudioServerSW *audio_server; SampleManagerMallocSW *sample_manager; SpatialSoundServerSW *spatial_sound_server; SpatialSound2DServerSW *spatial_sound_2d_server; #endif int event_id; InputDefault *input; #ifdef JOYDEV_ENABLED joystick_linux *joystick; #endif MouseVirtual mouse_virtual; uint64_t last_click; public: int get_video_driver_count() const { return VIDEO_DRIVER_COUNT; } int get_current_video_driver() const { return current_video_driver; } const char *get_video_driver_name(int driver) const { if (driver == VIDEO_DRIVER_GLES3) return "GLES3"; else return "GLES2"; } OS::VideoMode get_default_video_mode() const { return OS::VideoMode(screen_size.x, screen_size.y, true, false, true); } int get_audio_driver_count() const { return AudioDriverManagerSW::get_driver_count(); } const char *get_audio_driver_name(int driver) const { AudioDriverSW *driver_ = AudioDriverManagerSW::get_driver(driver); ERR_FAIL_COND_V(!driver_, ""); return driver_->get_name(); } bool _check_internal_feature_support(const String &feature) { if (current_video_driver == VIDEO_DRIVER_GLES3 && feature == "etc2") return true; return feature == "pc" || feature == "etc"; } #if VERSION_MAJOR >= 3 String get_config_path() const { if (has_environment("XDG_CONFIG_HOME")) return get_environment("XDG_CONFIG_HOME"); if (has_environment("HOME")) return get_environment("HOME").plus_file(".config"); return "."; } String get_data_path() const { if (has_environment("XDG_DATA_HOME")) return get_environment("XDG_DATA_HOME"); if (has_environment("HOME")) return get_environment("HOME").plus_file(".local/share"); return get_config_path(); } String get_cache_path() const { if (has_environment("XDG_CACHE_HOME")) return get_environment("XDG_CACHE_HOME"); if (has_environment("HOME")) return get_environment("HOME").plus_file(".cache"); return get_config_path(); } #endif void extract_resource_fatal(const char *msg) { fatal("failed extracting resource '%s': %s.", extract_resource_name, msg); } void extract_resource_if_requested() { const char *s = extract_resource_name; if (!s) return; if (!isalnum(*s)) extract_resource_fatal("invalid name"); for (int i = 0; s[i]; i++) if (!isalnum(*s) && !strchr(".-_", *s)) extract_resource_fatal("invalid name"); String name = "res://frt/"; name += s; if (!FileAccess::exists(name)) extract_resource_fatal("not found"); FileAccess *in = FileAccess::open(name, FileAccess::READ); if (!in) extract_resource_fatal("failed opening resource"); int len = in->get_len(); uint8_t *buf = new uint8_t[len]; // memory "leak" is fine here if (!buf) extract_resource_fatal("failed allocating memory"); int n = in->get_buffer(buf, len); if (n != len) extract_resource_fatal("failed reading resource"); in->close(); FileAccess *out = FileAccess::open(s, FileAccess::WRITE); if (!out) extract_resource_fatal("failed opening output file"); out->store_buffer(buf, len); out->close(); exit(0); } void get_project_frt_params() { PROJECT_SETTINGS String name; const int n = app->get_n_of_params(); for (int i = 0; i < n; i++) { Param *p = app->get_param(i); if (p->source == Param::CommandLine) continue; name = "frt/"; name += p->name; if (!project_settings->has(name)) continue; p->source = Param::ProjectSettings; Value &v = p->value; switch (v.t) { case Value::Bool: v.u.b = bool(project_settings->get(name)); break; case Value::Int: v.u.i = int(project_settings->get(name)); break; case Value::Float: v.u.f = float(project_settings->get(name)); break; case Value::String: { String s = String(project_settings->get(name)); v.u.s = strdup(s.ascii()); // TODO: keep track and dealloc string copy } break; } } } bool disable_meta_keys() { return disable_meta_keys_param->value.u.b; } bool exit_on_shiftenter() { return exit_on_shiftenter_param->value.u.b; } #if VERSION_MAJOR == 2 void #else Error #endif initialize(const VideoMode &desired, int video_driver, int audio_driver) { get_project_frt_params(); extract_resource_if_requested(); args = OS::get_singleton()->get_cmdline_args(); current_videomode = desired; main_loop = 0; Vec2 view(current_videomode.width, current_videomode.height); int gl_version = video_driver == VIDEO_DRIVER_GLES3 ? 3 : 2; context_gl = env->video->create_the_gl_context(gl_version, view); context_gl->initialize(); #if VERSION_MAJOR == 2 rasterizer = memnew(RasterizerGLES2); visual_server = memnew(VisualServerRaster(rasterizer)); if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) visual_server = memnew(VisualServerWrapMT( visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD)); #else if (video_driver == VIDEO_DRIVER_GLES3) { RasterizerGLES3::register_config(); RasterizerGLES3::make_current(); current_video_driver = VIDEO_DRIVER_GLES3; } else { RasterizerGLES2::register_config(); RasterizerGLES2::make_current(); current_video_driver = VIDEO_DRIVER_GLES2; } visual_server = memnew(VisualServerRaster); #endif // TODO: Audio Module AudioDriverManagerSW::get_driver(audio_driver)->set_singleton(); audio_driver_index = audio_driver; if (AudioDriverManagerSW::get_driver(audio_driver)->init() != OK) { audio_driver_index = -1; for (int i = 0; i < AudioDriverManagerSW::get_driver_count(); i++) { if (i == audio_driver) continue; AudioDriverManagerSW::get_driver(i)->set_singleton(); if (AudioDriverManagerSW::get_driver(i)->init() == OK) { audio_driver_index = i; break; } } } #if VERSION_MAJOR == 2 sample_manager = memnew(SampleManagerMallocSW); audio_server = memnew(AudioServerSW(sample_manager)); audio_server->init(); spatial_sound_server = memnew(SpatialSoundServerSW); spatial_sound_server->init(); spatial_sound_2d_server = memnew(SpatialSound2DServerSW); spatial_sound_2d_server->init(); ERR_FAIL_COND(!visual_server); #else if (!visual_server) return FAILED; #endif visual_server->init(); #if VERSION_MAJOR == 2 physics_server = memnew(PhysicsServerSW); physics_server->init(); physics_2d_server = memnew(Physics2DServerSW); physics_2d_server->init(); #endif input = memnew(InputDefault); #ifdef JOYDEV_ENABLED joystick = memnew(joystick_linux(input)); #endif last_click = 0; #if VERSION_MAJOR == 2 _ensure_data_dir(); #else #if VERSION_MINOR < 3 _ensure_user_data_dir(); #endif return OK; #endif } void finalize() { if (main_loop) memdelete(main_loop); main_loop = NULL; #if VERSION_MAJOR == 2 spatial_sound_server->finish(); memdelete(spatial_sound_server); spatial_sound_2d_server->finish(); memdelete(spatial_sound_2d_server); memdelete(sample_manager); audio_server->finish(); memdelete(audio_server); visual_server->finish(); #else // VERSION_MAJOR == 3 for (int i = 0; i < get_audio_driver_count(); i++) AudioDriverManager::get_driver(i)->finish(); #endif memdelete(visual_server); #if VERSION_MAJOR == 2 memdelete(rasterizer); physics_server->finish(); memdelete(physics_server); physics_2d_server->finish(); memdelete(physics_2d_server); #endif #ifdef JOYDEV_ENABLED memdelete(joystick); #endif memdelete(input); args.clear(); } void set_mouse_show(bool show) {} void set_mouse_grab(bool grab) { this->grab = grab; } bool is_mouse_grab_enabled() const { return grab; } int get_mouse_button_state() const { return mouse_state; } Point2 get_mouse_pos() const { return mouse_pos; } void set_mouse_mode(MouseMode mode) { mouse_mode = mode; } OS::MouseMode get_mouse_mode() const { return mouse_mode; } void set_window_title(const String &title) { env->video->set_title(title.utf8().get_data()); } void set_video_mode(const VideoMode &video_mode, int screen) {} OS::VideoMode get_video_mode(int screen) const { return current_videomode; } Size2 get_window_size() const { return Vector2(current_videomode.width, current_videomode.height); } void get_fullscreen_mode_list(List<VideoMode> *list, int screen) const {} MainLoop *get_main_loop() const { return main_loop; } void delete_main_loop() { if (main_loop) memdelete(main_loop); main_loop = 0; } void set_main_loop(MainLoop *main_loop) { this->main_loop = main_loop; input->set_main_loop(main_loop); } bool can_draw() const { return true; }; String get_name() #if (VERSION_MAJOR == 3) && (VERSION_MINOR >= 2) const #endif { return "FRT"; } void move_window_to_foreground() {} void set_cursor_shape(CursorShape shape) {} void set_custom_mouse_cursor(const RES&, OS::CursorShape, const Vector2&) {} void release_rendering_thread() { context_gl->release_current(); } void make_rendering_thread() { context_gl->make_current(); } void swap_buffers() { context_gl->swap_buffers(); } uint32_t unicode_fallback(int gd_code, bool pressed, const InputModifierState &st) { if (st.alt || st.control || st.meta || !pressed) return 0; if (gd_code >= 'A' && gd_code <= 'Z') return st.shift ? gd_code : gd_code + ('a' - 'A'); if (gd_code >= ' ' && gd_code <= '~') return gd_code; return 0; } void get_key_modifier_state(INPUT_MODIFIER_REF mod, InputModifierState *st = 0) { InputModifierState state; if (env->keyboard) { env->keyboard->get_modifier_state(state); } else { state.shift = false; state.control = false; state.alt = false; state.meta = false; } mod->set_shift(state.shift); mod->set_control(state.control); mod->set_alt(state.alt); mod->set_metakey(state.meta); if (st) *st = state; } void process_keyboard_event(int key, bool pressed, uint32_t unicode, bool echo) { INPUT_EVENT_REF(InputEventKey) k; k.instance(); InputModifierState st; get_key_modifier_state(k, &st); k->set_pressed(pressed); k->set_scancode(key); if (unicode) k->set_unicode(unicode); else k->set_unicode(unicode_fallback(key, pressed, st)); k->set_echo(echo); input->parse_input_event(k); } void process_mouse_motion(int x, int y) { mouse_pos.x = x; mouse_pos.y = y; if (!last_mouse_pos_valid) { last_mouse_pos = mouse_pos; last_mouse_pos_valid = true; } Vector2 rel = mouse_pos - last_mouse_pos; last_mouse_pos = mouse_pos; INPUT_EVENT_REF(InputEventMouseMotion) mm; mm.instance(); get_key_modifier_state(mm); mm->set_button_mask(mouse_state); mm->set_position(mouse_pos); mm->set_global_position(mouse_pos); mm->set_speed(input->get_mouse_speed()); mm->set_relative(rel); input->set_mouse_pos(mouse_pos); input->parse_input_event(mm); } void process_mouse_button(int index, bool pressed) { int bit = (1 << (index - 1)); if (pressed) mouse_state |= bit; else mouse_state &= ~bit; INPUT_EVENT_REF(InputEventMouseButton) mb; mb.instance(); get_key_modifier_state(mb); mb->set_button_mask(mouse_state); mb->set_position(mouse_pos); mb->set_global_position(mouse_pos); mb->set_button_index(index); mb->set_pressed(pressed); if (index == 1 && pressed) { const uint64_t t = get_ticks_usec(); const uint64_t dt = t - last_click; if (dt < 300000) { last_click = 0; mb->set_doubleclick(true); } else { last_click = t; } } input->parse_input_event(mb); } struct KeyboardHandler : Keyboard::Handler { OS_FRT *instance; Keyboard *keyboard; void handle_keyboard_key(int gd_code, bool pressed, uint32_t unicode, bool echo) { if (!instance->disable_meta_keys()) { InputModifierState st; keyboard->get_modifier_state(st); if (st.meta && instance->handle_meta(gd_code, pressed)) return; } if (instance->exit_on_shiftenter()) { InputModifierState st; keyboard->get_modifier_state(st); if (st.shift && pressed && (gd_code == GD_KEY_RETURN || gd_code == GD_KEY_ENTER)) App::instance()->quit(); } instance->process_keyboard_event(gd_code, pressed, unicode, echo); } } keyboard_handler; struct MouseHandler : Mouse::Handler { OS_FRT *instance; Video *video; void handle_mouse_button(Mouse::Button button, bool pressed) { int index; switch (button) { case Mouse::Left: index = 1; break; case Mouse::Middle: index = 3; break; case Mouse::Right: index = 2; break; case Mouse::WheelUp: index = BUTTON_WHEEL_UP; break; case Mouse::WheelDown: index = BUTTON_WHEEL_DOWN; break; default: return; } instance->process_mouse_button(index, pressed); } void handle_mouse_motion(Vec2 pos) { Vec2 view = video->move_pointer(pos); instance->process_mouse_motion(view.x, view.y); } } mouse_handler; bool dispatch_handle_meta(int gd_code, bool pressed) { // keep it simple: hard-coded order should be fine if (env->mouse && env->mouse->handle_meta(gd_code, pressed)) return true; if (env->keyboard && env->keyboard->handle_meta(gd_code, pressed)) return true; if (env->video && env->video->handle_meta(gd_code, pressed)) return true; return false; } void run() { if (!main_loop) return; disable_meta_keys_param = app->get_param("disable_meta_keys"); exit_on_shiftenter_param = app->get_param("exit_on_shiftenter"); keyboard_handler.instance = this; keyboard_handler.keyboard = env->keyboard; mouse_handler.instance = this; mouse_handler.video = env->video; if (env->keyboard && !env->mouse) { mouse_virtual.probe(); env->mouse = &mouse_virtual; } if (env->mouse) { env->mouse->set_size(screen_size); Vec2 pos = env->mouse->get_pos(); env->video->move_pointer(pos); } // mouse set_handler first to increase the chances of RETURN release if (env->mouse) { env->mouse->set_handler(&mouse_handler); } if (env->keyboard) { env->keyboard->set_handler(&keyboard_handler); } main_loop->init(); perfmon.init(); while (app->is_running()) { app->dispatch_events(); #ifdef JOYDEV_ENABLED #if VERSION_MAJOR == 2 event_id = joystick->process_joysticks(event_id); #else joystick->process_joypads(); #endif #endif if (Main::iteration() == true) break; if (perfmon.is_valid()) perfmon.iteration(get_ticks_msec()); }; perfmon.cleanup(); main_loop->finish(); } bool is_joy_known(int p_device) { return input->is_joy_mapped(p_device); } String get_joy_guid(int p_device) const { return input->get_joy_guid_remapped(p_device); } OS_FRT() { current_video_driver = VIDEO_DRIVER_GLES2; #ifdef PULSEAUDIO_ENABLED AudioDriverManagerSW::add_driver(&driver_pulseaudio); #endif #ifdef ALSA_ENABLED AudioDriverManagerSW::add_driver(&driver_alsa); #endif if (AudioDriverManagerSW::get_driver_count() == 0) AudioDriverManagerSW::add_driver(&driver_dummy); mouse_mode = MOUSE_MODE_VISIBLE; mouse_state = 0; grab = false; }; // Module const char *get_id() const { return "frt_os_unix"; } bool probe() { return true; } void cleanup() {} bool handle_meta(int gd_code, bool pressed) { switch (gd_code) { case 'Q': if (env->video->provides_quit()) return false; else app->quit(); break; default: return dispatch_handle_meta(gd_code, pressed); } return true; } // Runnable void setup_env(Env *env) { app = App::instance(); this->env = env; if (!env->video) fatal("no video module available."); screen_size = env->video->get_screen_size(); } void run_() { run(); } int get_exit_code_() { return get_exit_code(); } }; FRT_REGISTER(OS_FRT)
28.87696
85
0.717783
asheraryam
b4280f4bc1f83b8a7a5fdc0606d2441e0ba995c1
2,321
cpp
C++
dev/Generated/ToggleSplitButton.properties.cpp
johnpf74/microsoft-ui-xaml
db7b371a8155a81800f4432d6052ef54cb20642a
[ "MIT" ]
3
2018-12-06T08:02:41.000Z
2020-03-24T13:23:27.000Z
dev/Generated/ToggleSplitButton.properties.cpp
jsuarezruiz/microsoft-ui-xaml
b6f8806e07206caebccc81fb77d325efa67d29de
[ "MIT" ]
2
2018-12-07T16:49:26.000Z
2018-12-07T16:50:00.000Z
dev/Generated/ToggleSplitButton.properties.cpp
jsuarezruiz/microsoft-ui-xaml
b6f8806e07206caebccc81fb77d325efa67d29de
[ "MIT" ]
1
2020-08-28T10:29:11.000Z
2020-08-28T10:29:11.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // DO NOT EDIT! This file was generated by CustomTasks.DependencyPropertyCodeGen #include "pch.h" #include "common.h" #include "ToggleSplitButton.h" CppWinRTActivatableClassWithDPFactory(ToggleSplitButton) GlobalDependencyProperty ToggleSplitButtonProperties::s_IsCheckedProperty{ nullptr }; ToggleSplitButtonProperties::ToggleSplitButtonProperties() : m_isCheckedChangedEventSource{static_cast<ToggleSplitButton*>(this)} { EnsureProperties(); } void ToggleSplitButtonProperties::EnsureProperties() { SplitButton::EnsureProperties(); if (!s_IsCheckedProperty) { s_IsCheckedProperty = InitializeDependencyProperty( L"IsChecked", winrt::name_of<bool>(), winrt::name_of<winrt::ToggleSplitButton>(), false /* isAttached */, ValueHelper<bool>::BoxedDefaultValue(), winrt::PropertyChangedCallback(&OnPropertyChanged)); } } void ToggleSplitButtonProperties::ClearProperties() { s_IsCheckedProperty = nullptr; SplitButton::ClearProperties(); } void ToggleSplitButtonProperties::OnPropertyChanged( winrt::DependencyObject const& sender, winrt::DependencyPropertyChangedEventArgs const& args) { auto owner = sender.as<winrt::ToggleSplitButton>(); winrt::get_self<ToggleSplitButton>(owner)->OnPropertyChanged(args); } void ToggleSplitButtonProperties::IsChecked(bool value) { static_cast<ToggleSplitButton*>(this)->SetValue(s_IsCheckedProperty, ValueHelper<bool>::BoxValueIfNecessary(value)); } bool ToggleSplitButtonProperties::IsChecked() { return ValueHelper<bool>::CastOrUnbox(static_cast<ToggleSplitButton*>(this)->GetValue(s_IsCheckedProperty)); } winrt::event_token ToggleSplitButtonProperties::IsCheckedChanged(winrt::TypedEventHandler<winrt::ToggleSplitButton, winrt::ToggleSplitButtonIsCheckedChangedEventArgs> const& value) { return m_isCheckedChangedEventSource.add(value); } void ToggleSplitButtonProperties::IsCheckedChanged(winrt::event_token const& token) { m_isCheckedChangedEventSource.remove(token); }
34.132353
181
0.73589
johnpf74
b42813b7524836a38ae57b2595369ad6d057ae1b
1,613
cpp
C++
LCS/delta/LCSFormat.cpp
CNHume/Samples
2fdaa7a3193f19a882d0adebffaaf56af0984654
[ "MIT" ]
null
null
null
LCS/delta/LCSFormat.cpp
CNHume/Samples
2fdaa7a3193f19a882d0adebffaaf56af0984654
[ "MIT" ]
null
null
null
LCS/delta/LCSFormat.cpp
CNHume/Samples
2fdaa7a3193f19a882d0adebffaaf56af0984654
[ "MIT" ]
null
null
null
// Copyright (C) 2017, Christopher N. Hume. All rights reserved. // // 2017-07-04 CNHume Created LCSRecord subclass // 2015-01-23 CNHume Created file // #include "LCSRecord.h" // // Delta formatter // uint32_t LCSRecord::Show(shared_ptr<Delta> deltas, const RECORDS& r1, const RECORDS& r2, const string& label1, const string& label2) { uint32_t ndelta = 0; // # of deltas for (auto next = deltas; next != nullptr; next = dynamic_pointer_cast<Delta>(next->next)) { Series(ndelta, label1, r1, next->begin1, next->end1, label2, r2, next->begin2, next->end2); ndelta++; } return ndelta; } // Write both sides of a Delta in series void LCSRecord::Series(uint32_t counter, const string& label1, const RECORDS& r1, uint32_t begin1, uint32_t end1, const string& label2, const RECORDS& r2, uint32_t begin2, uint32_t end2) { Side("<<<<<", counter, label1, r1, begin1, end1); Side(">>>>>", counter, label2, r2, begin2, end2); } void LCSRecord::Side(string emblem, uint32_t counter, const string& label, const RECORDS& list, uint32_t begin, uint32_t end) { Head(emblem, counter, label, begin, end); Body(list, begin, end); } void LCSRecord::Head(string emblem, uint32_t counter, const string& label, uint32_t begin, uint32_t end) { if (begin < end) { cout << emblem << " " << counter + 1 << " " << label << " [" << begin << ":" << end << "] " << emblem << endl; } } void LCSRecord::Body(const RECORDS& records, uint32_t begin, uint32_t end) { for (auto index = begin; index < end; index++) cout << records[index] << endl; }
31.627451
88
0.646001
CNHume
b428fdb7829f92a157bbcc5c488e38a2d9b715c5
12,720
cpp
C++
pxr/usd/lib/usdSkel/skinningQuery.cpp
octarrow/USD
1845291a9701ab0a3a7d591bc243a1a80fdcba8a
[ "Unlicense" ]
3
2019-02-20T07:34:17.000Z
2019-08-13T08:17:04.000Z
pxr/usd/lib/usdSkel/skinningQuery.cpp
octarrow/USD
1845291a9701ab0a3a7d591bc243a1a80fdcba8a
[ "Unlicense" ]
null
null
null
pxr/usd/lib/usdSkel/skinningQuery.cpp
octarrow/USD
1845291a9701ab0a3a7d591bc243a1a80fdcba8a
[ "Unlicense" ]
1
2019-10-04T21:57:06.000Z
2019-10-04T21:57:06.000Z
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/usd/usdSkel/skinningQuery.h" #include "pxr/usd/usd/attribute.h" #include "pxr/usd/usd/prim.h" #include "pxr/usd/usd/relationship.h" #include "pxr/usd/usdGeom/boundable.h" #include "pxr/usd/usdGeom/primvar.h" #include "pxr/usd/usdSkel/utils.h" PXR_NAMESPACE_OPEN_SCOPE UsdSkelSkinningQuery::UsdSkelSkinningQuery() : _valid(false), _numInfluencesPerComponent(1), _interpolation(UsdGeomTokens->constant) {} UsdSkelSkinningQuery::UsdSkelSkinningQuery( const UsdPrim& prim, const VtTokenArray& skelJointOrder, const UsdAttribute& jointIndices, const UsdAttribute& jointWeights, const UsdAttribute& geomBindTransform, const UsdAttribute& joints) : _prim(prim), _valid(false), _numInfluencesPerComponent(1), _interpolation(UsdGeomTokens->constant), _jointIndicesPrimvar(jointIndices), _jointWeightsPrimvar(jointWeights), _geomBindTransformAttr(geomBindTransform) { VtTokenArray jointOrder; if (joints && joints.Get(&jointOrder)) { _jointOrder = jointOrder; _mapper = std::make_shared<UsdSkelAnimMapper>(skelJointOrder, jointOrder); } if(!jointIndices) { TF_WARN("'jointIndices' is invalid."); return; } if(!jointWeights) { TF_WARN("jointWeights' is invalid."); return; } // Validate joint influences. int indicesElementSize = _jointIndicesPrimvar.GetElementSize(); int weightsElementSize = _jointWeightsPrimvar.GetElementSize(); if(indicesElementSize != weightsElementSize) { TF_WARN("JointIndices element size (%d) != " "jointWeights element size (%d).", indicesElementSize, weightsElementSize); return; } if(indicesElementSize <= 0) { TF_WARN("Invalid element size [%d]: element size must " "be greater than zero.", indicesElementSize); return; } TfToken indicesInterpolation = _jointIndicesPrimvar.GetInterpolation(); TfToken weightsInterpolation = _jointWeightsPrimvar.GetInterpolation(); if(indicesInterpolation != weightsInterpolation) { TF_WARN("JointIndices interpolation (%s) != " "jointWeights interpolation (%s).", indicesInterpolation.GetText(), weightsInterpolation.GetText()); return; } if(indicesInterpolation != UsdGeomTokens->constant && indicesInterpolation != UsdGeomTokens->vertex) { TF_WARN("Invalid interpolation (%s) for joint influences: " "interpolation must be either 'constant' or 'vertex'.", indicesInterpolation.GetText()); return; } // Valid joint influences, to the extent that we can validate here. // Any further validation of joint influences requires the actual // indices/weights to be read in, which we won't do here. _numInfluencesPerComponent = indicesElementSize; _interpolation = indicesInterpolation; _valid = true; } bool UsdSkelSkinningQuery::IsRigidlyDeformed() const { return _interpolation == UsdGeomTokens->constant; } bool UsdSkelSkinningQuery::GetJointOrder(VtTokenArray* jointOrder) const { if(jointOrder) { if(_jointOrder) { *jointOrder = *_jointOrder; } return true; } else { TF_CODING_ERROR("'jointOrder' pointer is null."); return false; } } bool UsdSkelSkinningQuery::GetTimeSamples(std::vector<double>* times) const { return GetTimeSamplesInInterval(GfInterval::GetFullInterval(), times); } bool UsdSkelSkinningQuery::GetTimeSamplesInInterval(const GfInterval& interval, std::vector<double>* times) const { if(!times) { TF_CODING_ERROR("'times' pointer is null."); return false; } // TODO: Use Usd_MergeTimeSamples if it becomes public. std::vector<double> tmpTimes; for(const auto& pv : {_jointIndicesPrimvar, _jointWeightsPrimvar}) { if(pv.GetTimeSamplesInInterval(interval, &tmpTimes)) { times->insert(times->end(), tmpTimes.begin(), tmpTimes.end()); } } if(_geomBindTransformAttr.GetTimeSamplesInInterval(interval, &tmpTimes)) { times->insert(times->end(), tmpTimes.begin(), tmpTimes.end()); } std::sort(times->begin(), times->end()); times->erase(std::unique(times->begin(), times->end()), times->end()); return true; } bool UsdSkelSkinningQuery::ComputeJointInfluences(VtIntArray* indices, VtFloatArray* weights, UsdTimeCode time) const { TRACE_FUNCTION(); if(!TF_VERIFY(IsValid(), "invalid skinning query") || !TF_VERIFY(_jointIndicesPrimvar) || !TF_VERIFY(_jointWeightsPrimvar)) { return false; } if(_jointIndicesPrimvar.ComputeFlattened(indices, time) && _jointWeightsPrimvar.ComputeFlattened(weights, time)) { if(indices->size() != weights->size()) { TF_WARN("Size of jointIndices [%zu] != size of " "jointWeights [%zu].", indices->size(), weights->size()); return false; } if(!TF_VERIFY(_numInfluencesPerComponent > 0)) { return false; } if(indices->size()%_numInfluencesPerComponent != 0) { TF_WARN("unexpected size of jointIndices and jointWeights " "arrays [%zu]: size must be a multiple of the number of " "influences per component (%d).", indices->size(), _numInfluencesPerComponent); return false; } if(IsRigidlyDeformed() && indices->size() != static_cast<size_t>(_numInfluencesPerComponent)) { TF_WARN("Unexpected size of jointIndices and jointWeights " "arrays [%zu]: joint influences are defined with 'constant'" " interpolation, so the array size must be equal to the " "element size (%d).", indices->size(), _numInfluencesPerComponent); return false; } return true; } return false; } bool UsdSkelSkinningQuery::ComputeVaryingJointInfluences(size_t numPoints, VtIntArray* indices, VtFloatArray* weights, UsdTimeCode time) const { TRACE_FUNCTION(); if(ComputeJointInfluences(indices, weights, time)) { if(IsRigidlyDeformed()) { if(!UsdSkelExpandConstantInfluencesToVarying(indices, numPoints) || !UsdSkelExpandConstantInfluencesToVarying(weights, numPoints)) { return false; } if(!TF_VERIFY(indices->size() == weights->size())) return false; } else if(indices->size() != numPoints*_numInfluencesPerComponent) { TF_WARN("Unexpected size of jointIndices and jointWeights " "arrays [%zu]: varying influences should be sized to " "numPoints [%zu] * numInfluencesPerComponent [%d].", indices->size(), numPoints, _numInfluencesPerComponent); return false; } return true; } return false; } bool UsdSkelSkinningQuery::ComputeSkinnedPoints(const VtMatrix4dArray& xforms, VtVec3fArray* points, UsdTimeCode time) const { TRACE_FUNCTION(); if(!points) { TF_CODING_ERROR("'points' pointer is null."); return false; } VtIntArray jointIndices; VtFloatArray jointWeights; if(ComputeVaryingJointInfluences(points->size(), &jointIndices, &jointWeights, time)) { // If the binding site has a custom joint ordering, the query will have // a mapper that should be used to reorder transforms // (skel order -> binding order) VtMatrix4dArray orderedXforms(xforms); if(_mapper) { if(!_mapper->Remap(xforms, &orderedXforms)) { return false; } } GfMatrix4d geomBindXform = GetGeomBindTransform(time); return UsdSkelSkinPointsLBS(geomBindXform, orderedXforms, jointIndices, jointWeights, _numInfluencesPerComponent, points); } return false; } bool UsdSkelSkinningQuery::ComputeSkinnedTransform(const VtMatrix4dArray& xforms, GfMatrix4d* xform, UsdTimeCode time) const { TRACE_FUNCTION(); if(!xform) { TF_CODING_ERROR("'xform' pointer is null."); return false; } if(!IsRigidlyDeformed()) { TF_CODING_ERROR("Attempted to skin a transform, but " "joint influences are not constant."); return false; } VtIntArray jointIndices; VtFloatArray jointWeights; if(ComputeJointInfluences(&jointIndices, &jointWeights, time)) { // If the binding site has a custom joint ordering, the query will have // a mapper that should be used to reorder transforms // (skel order -> binding order) VtMatrix4dArray orderedXforms(xforms); if(_mapper) { if(!_mapper->Remap(xforms, &orderedXforms)) { return false; } } GfMatrix4d geomBindXform = GetGeomBindTransform(time); return UsdSkelSkinTransformLBS(geomBindXform, orderedXforms, jointIndices, jointWeights, xform); } return false; } USDSKEL_API float UsdSkelSkinningQuery::ComputeExtentsPadding( const VtMatrix4dArray& skelRestXforms, const UsdGeomBoundable& boundable) const { // Don't use default time; properties may be keyed (and still unvarying) // We do, however, expect the computed quantity to not be time varying. UsdTimeCode time = UsdTimeCode::EarliestTime(); VtVec3fArray boundableExtent; if(boundable && boundable.GetExtentAttr().Get(&boundableExtent, time) && boundableExtent.size() == 2) { VtVec3fArray jointsExtent; if(UsdSkelComputeJointsExtent(skelRestXforms, &jointsExtent)) { GfRange3d range = GfBBox3d(GfRange3d(boundableExtent[0], boundableExtent[1]), GetGeomBindTransform(time)).ComputeAlignedRange(); GfVec3f minDiff = jointsExtent[0] - GfVec3f(range.GetMin()); GfVec3f maxDiff = GfVec3f(range.GetMax()) - jointsExtent[1]; float padding = 0.0f; for(int i = 0; i < 3; ++i) { padding = std::max(padding, minDiff[i]); padding = std::max(padding, maxDiff[i]); } return padding; } } return 0.0f; } GfMatrix4d UsdSkelSkinningQuery::GetGeomBindTransform(UsdTimeCode time) const { // Geom bind transform attr is optional. GfMatrix4d xform; if(!_geomBindTransformAttr || !_geomBindTransformAttr.Get(&xform, time)) { xform.SetIdentity(); } return xform; } std::string UsdSkelSkinningQuery::GetDescription() const { if(IsValid()) { return TfStringPrintf("UsdSkelSkinningQuery <%s>", _prim.GetPath().GetText()); } return "invalid UsdSkelSkinningQuery"; } PXR_NAMESPACE_CLOSE_SCOPE
32.44898
80
0.619182
octarrow
b42af0c603698dc93264550ad8a2840bcd4d7d90
11,229
cpp
C++
Modules/MapperExt/src/mitkVolumeMapperVtkSmart3D.cpp
samsmu/MITK
c93dce6dc38d8f4c961de4440e4dd113b9841c8c
[ "BSD-3-Clause" ]
5
2015-02-05T10:58:41.000Z
2019-04-17T15:04:07.000Z
Modules/MapperExt/src/mitkVolumeMapperVtkSmart3D.cpp
samsmu/MITK
c93dce6dc38d8f4c961de4440e4dd113b9841c8c
[ "BSD-3-Clause" ]
141
2015-03-03T06:52:01.000Z
2020-12-10T07:28:14.000Z
Modules/MapperExt/src/mitkVolumeMapperVtkSmart3D.cpp
samsmu/MITK
c93dce6dc38d8f4c961de4440e4dd113b9841c8c
[ "BSD-3-Clause" ]
4
2015-02-19T06:48:13.000Z
2020-06-19T16:20:25.000Z
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkVolumeMapperVtkSmart3D.h" #include "mitkTransferFunctionProperty.h" #include "mitkTransferFunctionInitializer.h" #include "mitkLevelWindowProperty.h" #include <mitkImageVtkAccessor.h> #include <vtkObjectFactory.h> #include <vtkRenderingOpenGL2ObjectFactory.h> #include <vtkRenderingVolumeOpenGL2ObjectFactory.h> #include <vtkColorTransferFunction.h> #include <vtkPiecewiseFunction.h> void mitk::VolumeMapperVtkSmart3D::initialize() { mitk::Image *input = const_cast<mitk::Image *>(static_cast<const mitk::Image *>(this->GetDataNode()->GetData())); int displayedComponent = 0; this->GetDataNode()->GetIntProperty("Image.Displayed Component", displayedComponent); int numberOfComponents = input->GetPixelType().GetNumberOfComponents(); int timeStep = 0; this->GetDataNode()->GetIntProperty("Image.Displayed Timestep", timeStep); int numberOfTimeSteps = input->GetTimeSteps(); if (!m_Volume->GetMapper() || (numberOfTimeSteps > 1 && timeStep != m_LastTimeStep) || (numberOfComponents > 1 && displayedComponent != m_LastComponent)) { createMapper(GetInputImage()); createVolume(); createVolumeProperty(); } } void mitk::VolumeMapperVtkSmart3D::GenerateDataForRenderer(mitk::BaseRenderer *renderer) { initialize(); bool value; this->GetDataNode()->GetBoolProperty("volumerendering", value, renderer); if (!value) { m_Volume->VisibilityOff(); return; } else { m_Volume->VisibilityOn(); } UpdateTransferFunctions(renderer); UpdateRenderMode(renderer); this->Modified(); } vtkProp* mitk::VolumeMapperVtkSmart3D::GetVtkProp(mitk::BaseRenderer *renderer) { initialize(); return m_Volume; } void mitk::VolumeMapperVtkSmart3D::ApplyProperties(vtkActor *actor, mitk::BaseRenderer *renderer) { } void mitk::VolumeMapperVtkSmart3D::SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer, bool overwrite) { // GPU_INFO << "SetDefaultProperties"; node->AddProperty("volumerendering", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("volumerendering.usemip", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("volumerendering.cpu.ambient", mitk::FloatProperty::New(0.10f), renderer, overwrite); node->AddProperty("volumerendering.cpu.diffuse", mitk::FloatProperty::New(0.50f), renderer, overwrite); node->AddProperty("volumerendering.cpu.specular", mitk::FloatProperty::New(0.40f), renderer, overwrite); node->AddProperty("volumerendering.cpu.specular.power", mitk::FloatProperty::New(16.0f), renderer, overwrite); node->AddProperty("volumerendering.usegpu", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("volumerendering.useray", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("volumerendering.gpu.ambient", mitk::FloatProperty::New(0.25f), renderer, overwrite); node->AddProperty("volumerendering.gpu.diffuse", mitk::FloatProperty::New(0.50f), renderer, overwrite); node->AddProperty("volumerendering.gpu.specular", mitk::FloatProperty::New(0.40f), renderer, overwrite); node->AddProperty("volumerendering.gpu.specular.power", mitk::FloatProperty::New(16.0f), renderer, overwrite); node->AddProperty("binary", mitk::BoolProperty::New(false), renderer, overwrite); mitk::Image::Pointer image = dynamic_cast<mitk::Image *>(node->GetData()); if (image.IsNotNull() && image->IsInitialized()) { if ((overwrite) || (node->GetProperty("levelwindow", renderer) == nullptr)) { mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); mitk::LevelWindow levelwindow; levelwindow.SetAuto(image); levWinProp->SetLevelWindow(levelwindow); node->SetProperty("levelwindow", levWinProp, renderer); } if ((overwrite) || (node->GetProperty("TransferFunction", renderer) == nullptr)) { // add a default transfer function mitk::TransferFunction::Pointer tf = mitk::TransferFunction::New(); mitk::TransferFunctionInitializer::Pointer tfInit = mitk::TransferFunctionInitializer::New(tf); tfInit->SetTransferFunctionMode(0); node->SetProperty("TransferFunction", mitk::TransferFunctionProperty::New(tf.GetPointer())); } } Superclass::SetDefaultProperties(node, renderer, overwrite); } void mitk::VolumeMapperVtkSmart3D::setClippingPlanes(vtkPlanes* planes) { initialize(); m_SmartVolumeMapper->SetClippingPlanes(planes); } vtkImageData* mitk::VolumeMapperVtkSmart3D::GetInputImage() { mitk::Image *input = const_cast<mitk::Image *>(static_cast<const mitk::Image *>(this->GetDataNode()->GetData())); mitk::ImageVtkAccessor accessor(input); vtkImageData* img = accessor.getVtkImageData(this->GetTimestep()); m_LastTimeStep = this->GetTimestep(); if (input->GetPixelType().GetNumberOfComponents() > 1) { int displayedComponent = 0; this->GetDataNode()->GetIntProperty("Image.Displayed Component", displayedComponent); m_VectorComponentExtractor->SetComponents(displayedComponent); m_VectorComponentExtractor->SetInputData(img); m_VectorComponentExtractor->Modified(); m_VectorComponentExtractor->Update(); img = m_VectorComponentExtractor->GetOutput(); m_LastComponent = displayedComponent; } if (img) { img->SetSpacing(1,1,1); } return img; } void mitk::VolumeMapperVtkSmart3D::createMapper(vtkImageData* imageData) { m_SmartVolumeMapper = vtkSmartPointer<vtkSmartVolumeMapper>::New(); m_SmartVolumeMapper->SetBlendModeToComposite(); m_SmartVolumeMapper->SetInputData(imageData); } void mitk::VolumeMapperVtkSmart3D::createVolume() { m_Volume->VisibilityOff(); m_Volume->SetMapper(m_SmartVolumeMapper); m_Volume->SetProperty(m_VolumeProperty); } void mitk::VolumeMapperVtkSmart3D::createVolumeProperty() { m_VolumeProperty->ShadeOn(); m_VolumeProperty->SetInterpolationType(VTK_LINEAR_INTERPOLATION); } void mitk::VolumeMapperVtkSmart3D::UpdateTransferFunctions(mitk::BaseRenderer *renderer) { vtkSmartPointer<vtkPiecewiseFunction> opacityTransferFunction; vtkSmartPointer<vtkPiecewiseFunction> gradientTransferFunction; vtkSmartPointer<vtkColorTransferFunction> colorTransferFunction; bool isBinary = false; this->GetDataNode()->GetBoolProperty("binary", isBinary, renderer); if (isBinary) { colorTransferFunction = vtkSmartPointer<vtkColorTransferFunction>::New(); float rgb[3]; if (!GetDataNode()->GetColor(rgb, renderer)) rgb[0] = rgb[1] = rgb[2] = 1; colorTransferFunction->AddRGBPoint(0, rgb[0], rgb[1], rgb[2]); colorTransferFunction->Modified(); opacityTransferFunction = m_BinaryOpacityTransferFunction; gradientTransferFunction = m_BinaryGradientTransferFunction; } else { mitk::TransferFunctionProperty *transferFunctionProp = dynamic_cast<mitk::TransferFunctionProperty *>(this->GetDataNode()->GetProperty("TransferFunction", renderer)); if (transferFunctionProp) { opacityTransferFunction = transferFunctionProp->GetValue()->GetScalarOpacityFunction(); gradientTransferFunction = transferFunctionProp->GetValue()->GetGradientOpacityFunction(); colorTransferFunction = transferFunctionProp->GetValue()->GetColorTransferFunction(); } else { opacityTransferFunction = vtkSmartPointer<vtkPiecewiseFunction>::New(); gradientTransferFunction = vtkSmartPointer<vtkPiecewiseFunction>::New(); colorTransferFunction = vtkSmartPointer<vtkColorTransferFunction>::New(); } } m_VolumeProperty->SetColor(colorTransferFunction); m_VolumeProperty->SetScalarOpacity(opacityTransferFunction); m_VolumeProperty->SetGradientOpacity(gradientTransferFunction); } void mitk::VolumeMapperVtkSmart3D::UpdateRenderMode(mitk::BaseRenderer *renderer) { bool usegpu = false; bool useray = false; bool usemip = false; this->GetDataNode()->GetBoolProperty("volumerendering.usegpu", usegpu); this->GetDataNode()->GetBoolProperty("volumerendering.useray", useray); this->GetDataNode()->GetBoolProperty("volumerendering.usemip", usemip); if (usegpu) m_SmartVolumeMapper->SetRequestedRenderModeToGPU(); else if (useray) m_SmartVolumeMapper->SetRequestedRenderModeToRayCast(); else m_SmartVolumeMapper->SetRequestedRenderModeToDefault(); int blendMode; if (this->GetDataNode()->GetIntProperty("volumerendering.blendmode", blendMode)) m_SmartVolumeMapper->SetBlendMode(blendMode); else if (usemip) m_SmartVolumeMapper->SetBlendMode(vtkSmartVolumeMapper::MAXIMUM_INTENSITY_BLEND); // shading parameter if (m_SmartVolumeMapper->GetRequestedRenderMode() == vtkSmartVolumeMapper::GPURenderMode) { float value = 0; if (this->GetDataNode()->GetFloatProperty("volumerendering.gpu.ambient", value, renderer)) m_VolumeProperty->SetAmbient(value); if (this->GetDataNode()->GetFloatProperty("volumerendering.gpu.diffuse", value, renderer)) m_VolumeProperty->SetDiffuse(value); if (this->GetDataNode()->GetFloatProperty("volumerendering.gpu.specular", value, renderer)) m_VolumeProperty->SetSpecular(value); if (this->GetDataNode()->GetFloatProperty("volumerendering.gpu.specular.power", value, renderer)) m_VolumeProperty->SetSpecularPower(value); } else { float value = 0; if (this->GetDataNode()->GetFloatProperty("volumerendering.cpu.ambient", value, renderer)) m_VolumeProperty->SetAmbient(value); if (this->GetDataNode()->GetFloatProperty("volumerendering.cpu.diffuse", value, renderer)) m_VolumeProperty->SetDiffuse(value); if (this->GetDataNode()->GetFloatProperty("volumerendering.cpu.specular", value, renderer)) m_VolumeProperty->SetSpecular(value); if (this->GetDataNode()->GetFloatProperty("volumerendering.cpu.specular.power", value, renderer)) m_VolumeProperty->SetSpecularPower(value); } } mitk::VolumeMapperVtkSmart3D::VolumeMapperVtkSmart3D() : m_VectorComponentExtractor(vtkSmartPointer<vtkImageExtractComponents>::New()), m_LastTimeStep(-1), m_LastComponent(-1) { vtkObjectFactory::RegisterFactory(vtkRenderingOpenGL2ObjectFactory::New()); vtkObjectFactory::RegisterFactory(vtkRenderingVolumeOpenGL2ObjectFactory::New()); m_VolumeProperty = vtkSmartPointer<vtkVolumeProperty>::New(); m_Volume = vtkSmartPointer<vtkVolume>::New(); m_BinaryOpacityTransferFunction = vtkSmartPointer<vtkPiecewiseFunction>::New(); m_BinaryOpacityTransferFunction->AddPoint(0, 0.0); m_BinaryOpacityTransferFunction->AddPoint(1, 1.0); m_BinaryGradientTransferFunction = vtkSmartPointer<vtkPiecewiseFunction>::New(); m_BinaryGradientTransferFunction->AddPoint(0.0, 1.0); } mitk::VolumeMapperVtkSmart3D::~VolumeMapperVtkSmart3D() { }
37.059406
123
0.747618
samsmu
b42c343c4fb58d12235d44b514de72192de9ae29
49,344
cpp
C++
decreasoner.macosx/software/relsat-dist/SATSolver.cpp
problem-frames/openpf
55100bd9cca61a182fc00cd3818bd59a6343ae6e
[ "BSD-3-Clause" ]
1
2019-05-03T20:03:11.000Z
2019-05-03T20:03:11.000Z
decreasoner.x86/software/relsat-dist/SATSolver.cpp
problem-frames/openpf
55100bd9cca61a182fc00cd3818bd59a6343ae6e
[ "BSD-3-Clause" ]
null
null
null
decreasoner.x86/software/relsat-dist/SATSolver.cpp
problem-frames/openpf
55100bd9cca61a182fc00cd3818bd59a6343ae6e
[ "BSD-3-Clause" ]
null
null
null
///////////////// // OS Includes #include <memory.h> #include <stdlib.h> ////////////// // Includes #include "Clause.h" #include "Random.h" #include "SATInstance.h" #include "SATSolver.h" #include "VariableList.h" ///////////////////////////// // Static Data Initialization ///////////// // Defines ////////////////////////////////////////////////////////////////////////////////////////////////// // Public Methods SATSolver::SATSolver(SATInstance* pSATInstance_, ostream& xOutputStream_) : xOutputStream(xOutputStream_), _pPrimaryVariables(0) { _pInstance = pSATInstance_; _aAssignment = 0; // Set intelligent defaults for runtime parameters: _bFindAll = 1; // default to finding one solution _iMaxSolutions = 1; _fFudgeFactor = .9; _iLearnOrder = 3; _bNoTimeLimit = 0; _iMaxTime = 43200; // 12 hours _bFavorSmallClauses = 1; _bRelevanceBounding = 1; _bPrintStack = 1; _iPrintStackPeriod = 10; _bRestarts = 0; _iRestartIncrement = 0; } SATSolver::~SATSolver() { _xLearnedClauses.vDestroy(); delete _pPrimaryVariables; } relsat_enum SATSolver::eSolve() { time(&_iElapsedTime); _iLastCheckTime = _iElapsedTime; relsat_enum eReturn; _iBranchSelections = _iVariablesLabeled = _iContradictions = 0; if (!_bInitialize()) { eReturn = UNSAT; } else { // Here we do an initial unit propagation to handle base unit clauses. if (_bUnitPropagate()) { eReturn = UNSAT; } else { boolean bFailed_; boolean bReturn; if (_bRestarts) { bReturn = _bRestartLoop(bFailed_); } else { bReturn = _bLoop(bFailed_); } if (bFailed_) { eReturn = TIMEOUT; xOutputStream << "c Timeout." << endl; } else if (bReturn == 1) { eReturn = SAT; } else { eReturn = UNSAT; } } } _vCleanup(); time_t iEnd; time(&iEnd); _iElapsedTime = iEnd - _iElapsedTime; return eReturn; } void SATSolver::vSetPrintStackPeriod(long int iSeconds_) { _iPrintStackPeriod = iSeconds_; _bPrintStack = 1; } void SATSolver::vSetRestartInterval(int iSeconds_) { _iRestartInterval = iSeconds_; _bRestarts = 1; } void SATSolver::vSetRestartIncrement(int iSeconds_) { _iRestartIncrement = iSeconds_; } void SATSolver::vOutputStatusUpdateInterval() { if (_bPrintStack) { xOutputStream << "c Status update interval: " << _iPrintStackPeriod << " seconds." << endl; } } void SATSolver::vOutputWarnings() { xOutputStream << "c Learn order: " << _iLearnOrder << endl; xOutputStream << "c Fudge factor: " << _fFudgeFactor << endl; if (!_bNoTimeLimit) { xOutputStream << "c Solution phase timeout after: " << _iMaxTime << " seconds." << endl; } if (_bRestarts) { xOutputStream << "c Restart interval: " << _iRestartInterval << " seconds." << endl; if (_iRestartIncrement) { xOutputStream << "c Restart interval increment: " << _iRestartIncrement << " seconds." << endl; } if (!_bFindAll) { xOutputStream << "c WARNING: Restarts override model counting. Searching for first solution only." << endl; _bFindAll = 1; _iMaxSolutions = 1; } else { if (_iMaxSolutions == 0) { xOutputStream << "c WARNING: Find all solutions not a valid option when using restarts.\n" << "c Searching for first solution only." << endl; _iMaxSolutions = 1; } } xOutputStream << "c Finding up to " << _iMaxSolutions << " solutions with restarts." << endl; if (_iMaxSolutions > 1) { xOutputStream <<"c WARNING: With restarts, some solutions may be duplicates." << endl; } } else { if (!_bFindAll) { xOutputStream << "c Counting solutions (will output first solution if one exists)..." << endl; #ifdef NO_GMP xOutputStream << "c WARNING: Not using a bignum package. Solution counts may overflow." << endl; #endif } else { if (_iMaxSolutions == 0) { xOutputStream << "c Finding all solutions..." << endl; } else { xOutputStream << "c Finding up to " << _iMaxSolutions << " solutions..." << endl; } } } } ////////////////////////////////////////////////////////////////////////////////////////////////// // Protected Methods ////////////////////////////////////////////////////////////////////////////////////////////////// // Private Methods boolean SATSolver::_bLoop(boolean& bFailed_) { bFailed_ = 0; boolean bReturnValue = 0; while (1) { if (_bTimeLimitExpired()) { bFailed_ = 1; return bReturnValue; } if (_bPrintStackCheck()) { _vPrintStack(); } VariableID eBestID; boolean bZeroFirst; if (_pPrimaryVariables) { eBestID = _eGiveMeTheBest(bZeroFirst, true); } else { eBestID = _eGiveMeTheBest(bZeroFirst, false); } if (eBestID == -1) { bReturnValue = 1; if (_iCurrentVariable == _iVariableCount) { if (_bOutputSolution()) { xOutputStream << "c Solution limit reached. " << endl; return bReturnValue; } } if (_bSpecialBackup()) { xOutputStream << "c All solutions found." << endl; return bReturnValue; } } else { _aVariableStruct[eBestID].bBranch = 1; if (bZeroFirst) { _pUnitVariables0->vAddVariableNoCheck(eBestID); } else { _pUnitVariables1->vAddVariableNoCheck(eBestID); } if (_bUnitPropagate()) { if (_bBackup()) { return bReturnValue; } } } } } boolean SATSolver::_bOutputSolution() { _iSolutionCount++; if (_bFindAll || _iSolutionCount == 1) { // output only first solution found if counting xOutputStream << "Solution " << _iSolutionCount << ": "; for (int i=0; i<_iVariableCount; i++) { assert(_aAssignment[i] != NON_VALUE); if (_aAssignment[i]) { xOutputStream << i+1 << " "; } } xOutputStream << endl; } #ifndef NDEBUG if (_bVerifySolution()) { // xOutputStream << "c Solution verified" << endl; } else { Debug::vErrorReport("Found an invalid solution."); } #endif if (_bFindAll && _iSolutionCount >= _iMaxSolutions && _iMaxSolutions) { return 1; } return 0; } boolean SATSolver::_bVerifySolution() { // returns 1 if solution checks out OK for (int i=0; i<_pInstance->iClauseCount(); i++) { Clause* pTestMe = _pInstance->pClause(i); boolean bSatisfied = 0; for (int j=0; j<pTestMe->iVariableCount(); j++) { VariableID eCheckMe = pTestMe->eConstrainedVariable(j); if (_aAssignment[eCheckMe] && !pTestMe->iIsNegated(j) || !_aAssignment[eCheckMe] && pTestMe->iIsNegated(j)) { bSatisfied = 1; break; } } if (!bSatisfied) { return 0; } } return 1; } VariableStruct* SATSolver::_pBackupToFirstBranch() { //returns 1 if the search is complete. int i=0; while (i< _iCurrentVariable) { if(_aVariableStruct[_aPositionToID[i]].bBranch) { break; } i++; } VariableStruct* pWork = &(_aVariableStruct[_eCurrentID]); while (_iCurrentVariable != i) { pWork = &(_aVariableStruct[_eCurrentID]); _vUndoClauseModifications(); pWork->bBranch = 0; _aAssignment[_eCurrentID] = NON_VALUE; pWork->pReason = 0; _iCurrentVariable--; if (_iCurrentVariable != i) { pWork->xUnitClause.vClear(); } if (_iCurrentVariable) { _eCurrentID = _aPositionToID[_iCurrentVariable-1]; } else { _eCurrentID = -1; } } return pWork; } boolean SATSolver::_bRestartLoop(boolean& bFailed_) { bFailed_ = 0; boolean bReturnValue = 0; time(&iLastRestart); time_t now; while (1) { if (_bTimeLimitExpired()) { bFailed_ = 1; return bReturnValue; } if (_bPrintStackCheck()) { _vPrintStack(); } time(&now); if (now - iLastRestart > _iRestartInterval) { _iRestartInterval += _iRestartIncrement; xOutputStream << "c Restarting. Next restart in " << _iRestartInterval << " seconds. " <<endl; VariableStruct* pWork = _pBackupToFirstBranch(); if (_bNonTrivialUnitPropagate(pWork->xUnitClause) || _bUnitPropagate()) { return 0; } time(&iLastRestart); } VariableID eBestID; boolean bZeroFirst; if (_pPrimaryVariables) { eBestID = _eGiveMeTheBest(bZeroFirst, true); } else { eBestID = _eGiveMeTheBest(bZeroFirst, false); } if (eBestID == -1) { bReturnValue = 1; if (_iCurrentVariable == _iVariableCount) { if (_bOutputSolution()) { xOutputStream << "c Solution limit reached. " << endl; return bReturnValue; } } if (_bSpecialBackup()) { xOutputStream << "c All solutions found." << endl; return bReturnValue; } } else { _aVariableStruct[eBestID].bBranch = 1; if (bZeroFirst) { _pUnitVariables0->vAddVariableNoCheck(eBestID); } else { _pUnitVariables1->vAddVariableNoCheck(eBestID); } if (_bUnitPropagate()) { if (_bBackup()) { return bReturnValue; } } } } } VariableID SATSolver::_eGiveMeTheBest(boolean& bZeroFirst, boolean bFavorPrimary) { // Select the best branch variable. assert(_pUnitVariables0->iCount() == 0); assert(_pUnitVariables1->iCount() == 0); double fBest = -1.0; VariableStruct* pWorkStruct; VariableID eID, eID2; int i, j; int iScore0, iScore1; boolean bNoBinary = 1; for (i=0; i<_pGoodList->iCount(); i++) { eID = _pGoodList->iVariable(i); if (_aAssignment[eID] == NON_VALUE) { if (_aBinaryCount0[eID] || _aBinaryCount1[eID]) { bNoBinary = 0; } // Compute iScore0 if (_aBinaryCount0[eID] > 0 && _aScore0[eID] != -1 && _aBinaryCount0[eID] > _aScore0[eID]) { if (_bFastUnitPropagate(eID, 1, iScore0)) { for (j=0; j<i; j++) { eID2 = _pGoodList->iVariable(j); if (_aAssignment[eID2] == NON_VALUE) { _aScore0[eID2] = _aBinaryCount0[eID2]; _aScore1[eID2] = _aBinaryCount1[eID2]; } } for (j=i; j<_pGoodList->iCount(); j++) { eID2 = _pGoodList->iVariable(j); if (_aAssignment[eID2] == NON_VALUE) { if (_aScore0[eID2] == -1) { _aScore0[eID2] = _aBinaryCount0[eID2]; } if (_aScore1[eID2] == -1) { _aScore1[eID2] = _aBinaryCount1[eID2]; } } } bZeroFirst = 0; return eID; // leads to contradiction } //if (_bFastUnit... } else { iScore0 = _aBinaryCount0[eID]; } // Compute iScore1 if (_aBinaryCount1[eID] > 0 && _aScore1[eID] != -1 && _aBinaryCount1[eID] > _aScore1[eID]) { if (_bFastUnitPropagate(eID, 0, iScore1)) { for (j=0; j<i; j++) { eID2 = _pGoodList->iVariable(j); if (_aAssignment[eID2] == NON_VALUE) { _aScore0[eID2] = _aBinaryCount0[eID2]; _aScore1[eID2] = _aBinaryCount1[eID2]; } } for (j=i; j<_pGoodList->iCount(); j++) { eID2 = _pGoodList->iVariable(j); if (_aAssignment[eID2] == NON_VALUE) { if (_aScore0[eID2] == -1) { _aScore0[eID2] = _aBinaryCount0[eID2]; } if (_aScore1[eID2] == -1) { _aScore1[eID2] = _aBinaryCount1[eID2]; } } } bZeroFirst = 1; return eID; // leads to contradiction } // if (_bFastUnit... } else { iScore1 = _aBinaryCount1[eID]; } _aScore[eID] = _iCombineScores(iScore1, iScore0); if (!bFavorPrimary || _pPrimaryVariables->bHasVariable(eID)) { if (_aScore[eID] > fBest) { fBest = _aScore[eID]; } } } // if (...NON_VALUE... } // for (int i=0;... if (bNoBinary) { _vComputeNoBinaryScores(fBest, bFavorPrimary); if (fBest == -2.0 && !bFavorPrimary) { return -1; } else if (fBest == -2.0) { //cout << "Setting primary to false: " << fBest << endl; bFavorPrimary = false; _vComputeNoBinaryScores(fBest, bFavorPrimary); } if (fBest == -2.0) { return -1; } } _iBranchSelections++; try_with_non_primary: // Danger: reusing _pUnitList for (i=0; i<_pGoodList->iCount(); i++) { eID = _pGoodList->iVariable(i); if (_aAssignment[eID] == NON_VALUE) { if (bFavorPrimary) { if (!_pPrimaryVariables->bHasVariable(eID)) { continue; } } if (_aScore[eID] >= fBest * _fFudgeFactor) { //cout << "Adding: " << eID << endl; _pUnitList->vAdd(eID); } } } if (bFavorPrimary && _pUnitList->iCount() == 0) { //cout << "No more primary vars: " << _iVariableCount << endl; // No more primary variables left to label. bFavorPrimary = false; fBest = -2.0; for (i=0; i<_pGoodList->iCount(); i++) { eID = _pGoodList->iVariable(i); if (_aAssignment[eID] == NON_VALUE) { if (_aScore[eID] >= fBest) { fBest = _aScore[eID]; } } } goto try_with_non_primary; } VariableID eReturn = _pUnitList->iVariable(xRandom.iRandom(_pUnitList->iCount())); _pUnitList->vClear(); bZeroFirst = xRandom.iRandom(2); /*bZeroFirst = _aBinaryCount1[eReturn] > _aBinaryCount0[eReturn] ? 0 : 1;*/ memcpy(_aScore0, _aBinaryCount0, _iVariableCount * sizeof(*_aScore1)); memcpy(_aScore1, _aBinaryCount1, _iVariableCount * sizeof(*_aScore0)); //cout << "Returning branch: " << (eReturn+1) << " for loc. " << _iCurrentVariable << endl; return eReturn; } void SATSolver::_vComputeNoBinaryScores(double& fBest, boolean bFavorPrimary) { // Scoring function for when there are no binary clauses. fBest = -2.0; int i; VariableID eID; int iScore0, iScore1; for (i=0; i<_pGoodList->iCount(); i++) { eID = _pGoodList->iVariable(i); if (_aAssignment[eID] == NON_VALUE) { iScore0 = _iScoreClauseList(_aVariableStruct[eID].xPositiveClauses.pEntry(0), _aVariableStruct[eID].xPositiveClauses.pLastEntry()); iScore1 = _iScoreClauseList(_aVariableStruct[eID].xNegativeClauses.pEntry(0), _aVariableStruct[eID].xNegativeClauses.pLastEntry()); _aScore[eID] = _iCombineScores(iScore0, iScore1); if (bFavorPrimary && !_pPrimaryVariables->bHasVariable(eID)) { continue; } if (_aScore[eID] >= fBest) { fBest = _aScore[eID]; } } } } boolean SATSolver::_bInitialize() { // temp stuff _bReverse = 0; // Return 0 if problem is UNSAT due to unary clauses (node-consistency) _iRelevantClauses = 0; _xLearnedClauses.vDestroy(); _iSolutionCount = 0; _eCurrentID = -1; _iCurrentVariable = 0; _xSolutionCount.vSet(1); _xKnownSolutions.vSet(0); _iVariableCount = _pInstance->iVariableCount; _aBinaryCount0 = new long int[_iVariableCount]; _aBinaryCount1 = new long int[_iVariableCount]; _aAssignment = new DomainValue[_pInstance->iVariableCount]; _aVariableStruct = new VariableStruct[_pInstance->iVariableCount]; _aPositionToID = new VariableID[_pInstance->iVariableCount]; _aIDToPosition = new long int[_pInstance->iVariableCount]; _aScore0 = new int[_pInstance->iVariableCount]; _aScore = new double[_pInstance->iVariableCount]; _aScore1 = new int[_pInstance->iVariableCount]; _pUnitVariables0 = new VariableSet(_pInstance->iVariableCount); _pUnitVariables1 = new VariableSet(_pInstance->iVariableCount); _pUnitList = new VariableList(_pInstance->iVariableCount); _pPositiveBackup = new VariableSet(_pInstance->iVariableCount); _pNegativeBackup = new VariableSet(_pInstance->iVariableCount); _pGoodList = new VariableSet(_pInstance->iVariableCount); _pGoodReason = new VariableList(_pInstance->iVariableCount); int i; for (i=0; i< _iVariableCount; i++) { _aAssignment[i] = NON_VALUE; _pGoodList->vAddVariableNoCheck(i); _aBinaryCount0[i] = _aBinaryCount1[i] = _aScore0[i] = _aScore1[i] = 0; } for (i=0; i<_pInstance->iClauseCount(); i++) { Clause* pClause = _pInstance->pClause(i); pClause->vReset(); if (_bInitializeClause(pClause)) { return 0; } } for (i=0; i<_iVariableCount; i++) { _aVariableStruct[i].xPositiveClauses.vSortClausesByLength(); _aVariableStruct[i].xNegativeClauses.vSortClausesByLength(); } return 1; } boolean SATSolver::_bInitializeClause(Clause* pClause_) { // returns 1 if instance is UNSAT if (pClause_->iVariableCount() == 1) { if (_bInitializeUnaryClause(pClause_)) { return 1; } } boolean bIsBinary = (pClause_->iVariableCount() == 2); for (int j=0; j<pClause_->iVariableCount(); j++) { if (pClause_->iIsNegated(j)) { _aVariableStruct[pClause_->eConstrainedVariable(j)].xNegativeClauses.vAddClause(pClause_); if (bIsBinary) { _aBinaryCount0[pClause_->eConstrainedVariable(j)]++; } } else { _aVariableStruct[pClause_->eConstrainedVariable(j)].xPositiveClauses.vAddClause(pClause_); if (bIsBinary) { _aBinaryCount1[pClause_->eConstrainedVariable(j)]++; } } } return 0; } boolean SATSolver::_bInitializeLearnedClause(Clause* pClause_) { // returns 1 if instance is UNSAT // Call to initialize a clause learned during backtracking. for (int j=0; j<pClause_->iPermaCount(); j++) { if (pClause_->iIsNegated(j)) { _aVariableStruct[pClause_->eConstrainedVariable(j)].xNegativeClauses.vAddClause(pClause_); _aBinaryCount0[pClause_->eConstrainedVariable(j)]++; } else { _aVariableStruct[pClause_->eConstrainedVariable(j)].xPositiveClauses.vAddClause(pClause_); _aBinaryCount1[pClause_->eConstrainedVariable(j)]++; } } return 0; } boolean SATSolver::_bInitializeUnaryClause(Clause* pClause_) { // returns 0 if problem is determined to be UNSAT assert(pClause_->iVariableCount() == 1); VariableID eConstrainedVariable = pClause_->eConstrainedVariable(0); if (pClause_->iIsNegated(0)) { if (_pUnitVariables1->bHasVariable(eConstrainedVariable)) { return 1; // problem is UNSAT } if (_aVariableStruct[eConstrainedVariable].pReason == 0) { _pUnitVariables0->vAddVariable(eConstrainedVariable); _aVariableStruct[eConstrainedVariable].pReason = pClause_; } } else { if (_pUnitVariables0->bHasVariable(eConstrainedVariable)) { return 1; // problem is UNSAT } if (_aVariableStruct[eConstrainedVariable].pReason == 0) { _pUnitVariables1->vAddVariable(eConstrainedVariable); _aVariableStruct[eConstrainedVariable].pReason = pClause_; } } return 0; } int SATSolver::_iScoreClauseList(register Clause** pStart_, Clause** const pEnd_) { // Score the clause list based on clause lengths. assumes no clauses are binary. int iCount = 0; for (; pStart_ < pEnd_; pStart_++) { if (!(*pStart_)->bIsSatisfied()) { switch ((*pStart_)->iWorkingLength()) { case 3: iCount += 256; break; case 4: iCount += 16; break; case 5: iCount += 4; break; default: iCount += 1; } } } return iCount; } void SATSolver::_vFastBackupScore() { register Clause** pStart; Clause** pEnd; int i; const int iCount = _pUnitList->iCount(); for (i=0; i<iCount; i++) { VariableID eUndo = _pUnitList->iVariable(i); if (_aAssignment[eUndo]) { pStart = _aVariableStruct[eUndo].xNegativeClauses.pEntry(0); pEnd = _aVariableStruct[eUndo].xNegativeClauses.pLastEntry(); _aScore0[eUndo] = -1; // indicate no dead end } else { pStart = _aVariableStruct[eUndo].xPositiveClauses.pEntry(0); pEnd = _aVariableStruct[eUndo].xPositiveClauses.pLastEntry(); _aScore1[eUndo] = -1; // indicate no dead end } for (; pStart < pEnd; pStart++) { (*pStart)->iExpand(); } _aAssignment[eUndo] = NON_VALUE; } _pUnitList->vClear(); } void SATSolver::_vFastBackup(const int iToIndex_) { register Clause** pStart; Clause** pEnd; int i; for (i=0; i<iToIndex_; i++) { VariableID eUndo = _pUnitList->iVariable(i); if (_aAssignment[eUndo]) { pStart = _aVariableStruct[eUndo].xNegativeClauses.pEntry(0); pEnd = _aVariableStruct[eUndo].xNegativeClauses.pLastEntry(); } else { pStart = _aVariableStruct[eUndo].xPositiveClauses.pEntry(0); pEnd = _aVariableStruct[eUndo].xPositiveClauses.pLastEntry(); } for (; pStart < pEnd; pStart++) { (*pStart)->iExpand(); } _aAssignment[eUndo] = NON_VALUE; } for (; i<_pUnitList->iCount(); i++) { _aAssignment[_pUnitList->iVariable(i)] = NON_VALUE; } _pUnitList->vClear(); } boolean SATSolver::_bFastUnitPropagate(VariableID eWhich_, DomainValue iAssignment_, int& iScore_) { // Return 1 if unit propagation leads to a contradiction. int i,j; Clause **pStart, **pEnd; Clause *pReduceMe; VariableID eID; assert(_pUnitList->iCount() == 0); _pUnitList->vAdd(eWhich_); _aAssignment[eWhich_] = iAssignment_; for (i=0; i<_pUnitList->iCount(); i++) { eID = _pUnitList->iVariable(i); if (_aAssignment[eID] == 0) { pStart = _aVariableStruct[eID].xPositiveClauses.pEntry(0); pEnd = _aVariableStruct[eID].xPositiveClauses.pLastEntry(); } else { pStart = _aVariableStruct[eID].xNegativeClauses.pEntry(0); pEnd = _aVariableStruct[eID].xNegativeClauses.pLastEntry(); } Clause **const pBegin = pStart; for (;pStart < pEnd; pStart++) { pReduceMe = *pStart; if (!pReduceMe->bIsSatisfied()) { switch(pReduceMe->iReduce()) { case 0: // Contradiction! for (; pStart >= pBegin; pStart--) { (*pStart)->iExpand(); } _vFastBackup(i); return 1; case 1: for (j = 0; j < pReduceMe->iPermaCount(); j++) { eID = pReduceMe->eConstrainedVariable(j); if (_aAssignment[eID] == NON_VALUE) { _pUnitList->vAdd(eID); if (pReduceMe->iIsNegated(j)) { _aAssignment[eID] = 0; } else { _aAssignment[eID] = 1; } break; } } } } } // for (;pStart... } // for (i=.n. iScore_ = _pUnitList->iCount(); _vFastBackupScore(); return 0; } boolean SATSolver::_bUnitPropagate() { // Return 1 if unit propagation leads to a contradiction. // Does not back up, does not learn. // Simply leaves the list of contradicting variables intact. VariableStruct* pWork; while(1) { if (_pUnitVariables1->iCount()) { int iWhich = xRandom.iRandom(_pUnitVariables1->iCount()); _vLabelVariable(_pUnitVariables1->iVariable(iWhich), 1); _pUnitVariables1->vRemoveVariable(_eCurrentID); assert(_pGoodList->bHasVariable(_eCurrentID)); pWork = &_aVariableStruct[_eCurrentID]; _vSatisfyWithClauseList(pWork->xPositiveClauses.pEntry(0), pWork->xPositiveClauses.pLastEntry()); if (_bFilterWithClauseList(pWork->xNegativeClauses.pEntry(0), pWork->xNegativeClauses.pLastEntry())) { return 1; } } else if (_pUnitVariables0->iCount()) { int iWhich = xRandom.iRandom(_pUnitVariables0->iCount()); _vLabelVariable(_pUnitVariables0->iVariable(iWhich), 0); _pUnitVariables0->vRemoveVariable(_eCurrentID); assert(_pGoodList->bHasVariable(_eCurrentID)); pWork = &_aVariableStruct[_eCurrentID]; _vSatisfyWithClauseList(pWork->xNegativeClauses.pEntry(0), pWork->xNegativeClauses.pLastEntry()); if (_bFilterWithClauseList(pWork->xPositiveClauses.pEntry(0), pWork->xPositiveClauses.pLastEntry())) { return 1; } } else { return 0; } } // while(1); } boolean SATSolver::_bFilterWithClauseList(Clause** pStart_, Clause** pEnd_) { // return 1 if contradiction encountered. boolean bReturn = 0; Clause* pWorkClause; VariableID eContradictionID; Clause* pContradictionReason; int j; for (; pStart_ < pEnd_; pStart_++) { pWorkClause = *pStart_; if (!pWorkClause->bIsSatisfied()) { switch (pWorkClause->iReduce()) { case 2: for (j=0; j<pWorkClause->iPermaCount(); j++) { if (pWorkClause->iIsNegated(j)) { _aBinaryCount0[pWorkClause->eConstrainedVariable(j)]++; } else { _aBinaryCount1[pWorkClause->eConstrainedVariable(j)]++; } } break; case 1: // Find the variable it filters. for (int j = 0; ; j++) { assert(j < pWorkClause->iPermaCount()); VariableID eID = pWorkClause->eConstrainedVariable(j); if (_aAssignment[eID] == NON_VALUE) { if (!_pGoodList->bHasVariable(eID)) { // it's outside the goodlist break; } // we've found the filtering variable if (pWorkClause->iIsNegated(j)) { if (_aVariableStruct[eID].pReason) { if (_pUnitVariables1->bHasVariable(eID)) { // Contradiction! // Can't return immediately because it will confuse the state undoing code eContradictionID = eID; pContradictionReason = pWorkClause; bReturn = 1; } else { assert(_pUnitVariables0->bHasVariable(eID)); _vDecideFilterClause(eID, pWorkClause); } } // if (_...pReason) else { assert(!_pUnitVariables1->bHasVariable(eID)); assert(_pGoodList->bHasVariable(eID)); _pUnitVariables0->vAddVariableNoCheck(eID); _aVariableStruct[eID].pReason = pWorkClause; } } // if (pWorkClause->iIsNegated(j)... else { if (_aVariableStruct[eID].pReason) { if (_pUnitVariables0->bHasVariable(eID)) { // Contradiction! // Can't return immediately because it will confuse the state undoing code eContradictionID = eID; pContradictionReason = pWorkClause; bReturn = 1; } else { assert(_pUnitVariables1->bHasVariable(eID)); _vDecideFilterClause(eID, pWorkClause); } } // if (...pReason... else { assert(!_pUnitVariables0->bHasVariable(eID)); assert(_pGoodList->bHasVariable(eID)); _pUnitVariables1->vAddVariableNoCheck(eID); _aVariableStruct[eID].pReason = pWorkClause; } } break; } } // for (int j= } } } if (bReturn) { _vSetContradiction(eContradictionID, pContradictionReason); } return bReturn; } inline void SATSolver::_vSetContradiction(VariableID eContradictionID_, Clause* pReason_) { _eContradictionID = eContradictionID_; _pContradictionClause1 = pReason_; _pContradictionClause2 = _aVariableStruct[eContradictionID_].pReason; int i; for (i=0; i<_pUnitVariables0->iCount(); i++) { _aVariableStruct[_pUnitVariables0->iVariable(i)].pReason = 0; } _pUnitVariables0->vClear(); for (i=0; i<_pUnitVariables1->iCount(); i++) { _aVariableStruct[_pUnitVariables1->iVariable(i)].pReason = 0; } _pUnitVariables1->vClear(); } void SATSolver::_vSatisfyWithClauseList(register Clause** pStart_, Clause** pEnd_) { Clause* pWorkClause; for (; pStart_ < pEnd_; pStart_++) { pWorkClause = *pStart_; if (!pWorkClause->bIsSatisfied()) { if (pWorkClause->iWorkingLength() == 2 ) { for (int j=0; j<pWorkClause->iPermaCount(); j++) { if (pWorkClause->iIsNegated(j)) { _aBinaryCount0[pWorkClause->eConstrainedVariable(j)]--; assert(_aBinaryCount0[pWorkClause->eConstrainedVariable(j)] >= 0); } else { _aBinaryCount1[pWorkClause->eConstrainedVariable(j)]--; assert(_aBinaryCount1[pWorkClause->eConstrainedVariable(j)] >= 0); } } } } pWorkClause->vMakeSatisfied(); } } boolean SATSolver::_bCreateBackupClauseFromContradiction() { // Create a new clause representing the nogood derived from the // current contradiction on _eContradictionID. _iContradictions++; _pPositiveBackup->vClear(); _pNegativeBackup->vClear(); int i; for (i=0; i<_pContradictionClause1->iVariableCount(); i++) { if (_pContradictionClause1->iIsNegated(i)) { _pNegativeBackup->vAddVariableNoCheck(_pContradictionClause1->eConstrainedVariable(i)); } else { _pPositiveBackup->vAddVariableNoCheck(_pContradictionClause1->eConstrainedVariable(i)); } } for (i=0; i<_pContradictionClause2->iVariableCount(); i++) { if (_pContradictionClause2->iIsNegated(i)) { _pNegativeBackup->vAddVariable(_pContradictionClause2->eConstrainedVariable(i)); } else { _pPositiveBackup->vAddVariable(_pContradictionClause2->eConstrainedVariable(i)); } } _pPositiveBackup->vRemoveVariable(_eContradictionID); _pNegativeBackup->vRemoveVariable(_eContradictionID); if (!_pContradictionClause1->bIsTemporary() && !_pContradictionClause2->bIsTemporary() && _pPositiveBackup->iCount() + _pNegativeBackup->iCount() >= (_pContradictionClause1->iVariableCount() + _pContradictionClause2->iVariableCount() - 2)) { return 0; } else { return 1; } } inline boolean SATSolver::_bCreateNewBackupClause(boolean bLastReasonTransient_) { Clause* pFailClause2; pFailClause2 = _aVariableStruct[_eCurrentID].pReason; int iOriginalCount = _pNegativeBackup->iCount() + _pPositiveBackup->iCount(); for (int i=0; i<pFailClause2->iVariableCount(); i++) { VariableID eWorkID = pFailClause2->eConstrainedVariable(i); if (pFailClause2->iIsNegated(i)) { _pNegativeBackup->vAddVariable(eWorkID); } else { _pPositiveBackup->vAddVariable(eWorkID); } } _pPositiveBackup->vRemoveVariableCheck(_eCurrentID); _pNegativeBackup->vRemoveVariableCheck(_eCurrentID); if (!bLastReasonTransient_ && !pFailClause2->bIsTemporary() && _pPositiveBackup->iCount() + _pNegativeBackup->iCount() >= (pFailClause2->iVariableCount() + iOriginalCount - 2)) { return 0; } else { return 1; } } inline Clause* SATSolver::_pLearn() { if (_pPositiveBackup->iCount() + _pNegativeBackup->iCount() <= _iLearnOrder) { Clause* pLearn = new Clause(*_pPositiveBackup, *_pNegativeBackup); _xLearnedClauses.vAddClause(pLearn); int i = _iCurrentVariable-1; boolean bFoundFirst = 0; while(i >= 0) { VariableID eID = _aPositionToID[i]; if (_pPositiveBackup->bHasVariable(eID) || _pNegativeBackup->bHasVariable(eID)) { if (!bFoundFirst) { bFoundFirst = 1; } else break; } else if (bFoundFirst && _aVariableStruct[eID].bBranch) { _aVariableStruct[eID].xUnitClause.vAddClause(pLearn); } i--; } _bInitializeLearnedClause(pLearn); return pLearn; } else if (_bRelevanceBounding && _iLearnOrder) { // Learn a temporary clause int i = _iCurrentVariable-1; int iBranches = 0; int iPermaCount = 0; VariableID eResetID; assert(_pUnitVariables0->iCount() == 0); // reusing this VariableSet assert(_pUnitVariables1->iCount() == 0); // reusing this VariableSet for PermaVars while (1) { VariableID eID = _aPositionToID[i]; assert(_aAssignment[eID] != NON_VALUE); if (_pPositiveBackup->bHasVariable(eID) || _pNegativeBackup->bHasVariable(eID)) { if (iPermaCount == _iLearnOrder) { eResetID = eID; break; } if (_aVariableStruct[eID].bBranch) { iBranches++; } _pUnitVariables1->vAddVariableNoCheck(eID); iPermaCount++; } else if (_aVariableStruct[eID].bBranch) { if (iPermaCount > 0) { iBranches++; } if (iPermaCount == 1) { _pUnitVariables0->vAddVariableNoCheck(eID); } } i--; assert(i>=0); } // while //assert(_pUnitVariables1->iCount() == _iLearnOrder); if (iBranches > 0) { Clause* pLearn = new Clause(*_pPositiveBackup, *_pNegativeBackup, *_pUnitVariables1); _bInitializeLearnedClause(pLearn); _aVariableStruct[eResetID].xDeleteList.vAddClause(pLearn); for (int k=0; k<_pUnitVariables0->iCount(); k++) { _aVariableStruct[_pUnitVariables0->iVariable(k)].xUnitClause.vAddClause(pLearn); } _pUnitVariables0->vClear(); _pUnitVariables1->vClear(); _iRelevantClauses++; return pLearn; } _pUnitVariables0->vClear(); _pUnitVariables1->vClear(); } // else return 0; } inline void SATSolver::_vDeleteClauses(ClauseList& rClauseList_) { // Delete these learned clauses since they are no longer relevant VariableStruct* pWork; Clause** pStart = rClauseList_.pEntry(0); Clause** pEnd = rClauseList_.pLastEntry(); for (; pStart < pEnd; pStart++) { Clause* pDeleteMe = *pStart; for (int j=0; j<pDeleteMe->iPermaCount(); j++) { pWork = &(_aVariableStruct[pDeleteMe->eConstrainedVariable(j)]); if (pDeleteMe->iPermaCount() < 3) { if (pDeleteMe->iIsNegated(j)) { pWork->xNegativeClauses.vDeleteClause(pDeleteMe); _aBinaryCount0[pDeleteMe->eConstrainedVariable(j)]--; } else { pWork->xPositiveClauses.vDeleteClause(pDeleteMe); _aBinaryCount1[pDeleteMe->eConstrainedVariable(j)]--; } } else { if (pDeleteMe->iIsNegated(j)) { pWork->xNegativeClauses.vDeleteClause(pDeleteMe); } else { pWork->xPositiveClauses.vDeleteClause(pDeleteMe); } } assert(_aAssignment[pDeleteMe->eConstrainedVariable(j)] == NON_VALUE); } _iRelevantClauses--; delete pDeleteMe; } rClauseList_.vClear(); } inline void SATSolver::_vLabelVariable(VariableID eID_, DomainValue lWhich_) { // Label a variable and make it current. //xOutputStream << "Labeling: " << eID_ << " to " << (int)lWhich_ << endl; assert(_aAssignment[eID_] == NON_VALUE); assert(_iCurrentVariable < _iVariableCount); _aAssignment[eID_] = lWhich_; _aIDToPosition[eID_] = _iCurrentVariable; _aPositionToID[_iCurrentVariable++] = eID_; _eCurrentID = eID_; _iVariablesLabeled++; } boolean SATSolver::_bBackup() { // Returns 1 if the search is complete. start: //^^ We goto start instead of call bBackup() recursively since some compilers don't // properly support tail recursion optimization. //_vLearnBranchClauseFromContradiction(); boolean bLearn = _bCreateBackupClauseFromContradiction(); boolean bLastReasonTransient; if (_pPositiveBackup->iCount() == 0 && _pNegativeBackup->iCount() == 0) { return 1; } Clause* pJustLearned; if (bLearn) { pJustLearned = _pLearn(); if (pJustLearned && !pJustLearned->bIsTemporary()) { bLastReasonTransient = 0; } else { bLastReasonTransient = 1; } } else { bLastReasonTransient = 0; pJustLearned = 0; } VariableStruct* pWork; do { // while (1) pWork = &(_aVariableStruct[_eCurrentID]); if (pWork->pSolutionInfo) { pWork->pSolutionInfo->xSolutionCount.vSet(0); pWork->pReason = new Clause(*_pPositiveBackup, *_pNegativeBackup); delete pWork->pDeleteReason; pWork->pDeleteReason = pWork->pReason; // NASTY UGLY HACK // This hack is needed so that _vCreateGoodReason properly computes the reason. _bReverse = 1; // END NASTY UGLY HACK return _bSpecialBackup(); } _vUndoClauseModifications(); if (_pPositiveBackup->bHasVariable(_eCurrentID) || _pNegativeBackup->bHasVariable(_eCurrentID)) { if (pWork->bBranch) { pWork->bBranch = 0; if (pJustLearned) { pWork->pReason = pJustLearned; } else { // No reason was created by the learning mechanism, so we need to create one. pWork->pReason = new Clause(*_pPositiveBackup, *_pNegativeBackup); delete pWork->pDeleteReason; // we lazily delete any old one if it exists pWork->pDeleteReason = pWork->pReason; } if (_aAssignment[_eCurrentID] == 0) { // try the opposite assignment _pUnitVariables1->vAddVariable(_eCurrentID); } else { _pUnitVariables0->vAddVariable(_eCurrentID); } _aAssignment[_eCurrentID] = NON_VALUE; _iCurrentVariable--; if (_bNonTrivialUnitPropagate(pWork->xUnitClause)) { _eCurrentID = _aPositionToID[_iCurrentVariable-1]; goto start; } VariableID eRemember = _eCurrentID; if (_bUnitPropagate()) { goto start; } return 0; } else { bLearn = _bCreateNewBackupClause(bLastReasonTransient); if (_pPositiveBackup->iCount() == 0 && _pNegativeBackup->iCount() == 0) { return 1; } if (bLearn) { pJustLearned = _pLearn(); if (pJustLearned && !pJustLearned->bIsTemporary()) { bLastReasonTransient = 0; } else { bLastReasonTransient = 1; } } else { bLastReasonTransient = 0; pJustLearned = 0; } } } // if (_pBackupSet->bHasVariable pWork->bBranch = 0; _aAssignment[_eCurrentID] = NON_VALUE; pWork->pReason = 0; pWork->xUnitClause.vClear(); _iCurrentVariable--; assert(_iCurrentVariable != 0); _eCurrentID = _aPositionToID[_iCurrentVariable-1]; } while(1); } void SATSolver::_vCreateGoodReason() { // Create a reason that explains the solution count of the current subproblem. VariableStruct* pWork = &(_aVariableStruct[_eCurrentID]); int i; assert(_aAssignment[_eCurrentID] != NON_VALUE); Clause** pStart; Clause** pEnd; pStart = pWork->xNegativeClauses.pEntry(0); pEnd = pWork->xNegativeClauses.pLastEntry(); _vUpdateGoodReason(pStart, pEnd, pWork->pSolutionInfo->xGoodReason); pStart = pWork->xPositiveClauses.pEntry(0); pEnd = pWork->xPositiveClauses.pLastEntry(); _vUpdateGoodReason(pStart, pEnd, pWork->pSolutionInfo->xGoodReason); /* if (_aVariableStruct[_eCurrentID].pReason) { Clause* pReason = _aVariableStruct[_eCurrentID].pReason; for (int i=0; i<pReason->iVariableCount(); i++) { VariableID eID = pReason->eConstrainedVariable(i); if (eID != _eCurrentID && _aAssignment[eID] != NON_VALUE) { pWork->pSolutionInfo->xGoodReason.vAddVariable(pReason->eConstrainedVariable(i)); } } }*/ if (_pGoodReason->eTop() != -1) { assert(_aAssignment[_pGoodReason->eTop()] != NON_VALUE); pWork->pSolutionInfo->xGoodReason.vAddVariable(_pGoodReason->eTop()); } pWork->pSolutionInfo->xGoodReason.vRemoveVariableCheck(_eCurrentID); } void SATSolver::_vUpdateGoodReason(Clause** pStart, Clause** pEnd, VariableSet& xGoodReason_) { VariableStruct* pWork = &(_aVariableStruct[_eCurrentID]); int i; VariableID eID, eBest; Clause* pBestUnsatisfied = 0; for (; pStart < pEnd; pStart++) { if ((*pStart)->bLearned()) { // Learned clauses are redundant, so they need not contribute to the reason. continue; } if ((*pStart)->bIsSatisfied()) { // Unlike reasons for contradiction, reasons for a positive solution count must consider // satisfied clauses, since if they were not satisfied, this might reduce the solution // count. int iEarliest = 9999999; for (i=0; i<(*pStart)->iPermaCount(); i++) { eID = (*pStart)->eConstrainedVariable(i); if (eID != _eCurrentID && _aAssignment[eID] != NON_VALUE) { if ((_aAssignment[eID] && !(*pStart)->iIsNegated(i)) || (!_aAssignment[eID] && (*pStart)->iIsNegated(i))) { // found a satisfying var. if (_aIDToPosition[eID] < iEarliest) { iEarliest = _aIDToPosition[eID]; eBest = eID; } } } } // for assert(iEarliest != 9999999); xGoodReason_.vAddVariable(eBest); } else { Clause* pReason = *pStart; //cout << "pReason: "; pReason->vOutput(xOutputStream); cout << endl; for (i=0; i<pReason->iVariableCount(); i++) { VariableID eID = pReason->eConstrainedVariable(i); if (eID != _eCurrentID && _aAssignment[eID] != NON_VALUE) { //cout << "." << (_eCurrentID+1) << "."; xGoodReason_.vAddVariable(pReason->eConstrainedVariable(i)); } } } } } boolean SATSolver::_bSpecialBackup() { // Back up from a state where solutions exist. Returns 1 if there are no more solutions. // WARNING: Convoluted code. There's a bunch of weird stuff going on here which I just // haven't had time to clean up or properly document. VariableStruct* pWork; VariableStruct* pParentWork; VariableID eParentID; do { // while (1) pWork = &(_aVariableStruct[_eCurrentID]); _vUndoClauseModifications(); if (!pWork->pSolutionInfo) { pWork->pSolutionInfo = new SolutionInfo(_iVariableCount); } SolutionInfo* pSolutionInfo = pWork->pSolutionInfo; if (pWork->bBranch && (!_pPrimaryVariables || _pPrimaryVariables->bHasVariable(_eCurrentID))) { // we have backed up to a branch //xOutputStream << "Branch: " << _eCurrentID << endl; assert(!pWork->pReason); pWork->bBranch = 0; _iCurrentVariable--; if (!_bFindAll) { _pGoodReason->vAdd(_eCurrentID); pSolutionInfo->pOldSolutionCount = new BigNum(pSolutionInfo->xSolutionCount); pSolutionInfo->xSolutionCount.vSet(1); _pGoodList->vClear(); _pGoodList->vAppendNoCheck(pSolutionInfo->xGoodList); _pGoodList->vAddVariableNoCheck(_eCurrentID); } assert(_pUnitVariables0->iCount() == 0); assert(_pUnitVariables1->iCount() == 0); if (_aAssignment[_eCurrentID] == 0) { // try the opposite assignment _aAssignment[_eCurrentID] = NON_VALUE; _vLabelVariable(_eCurrentID,1); _vSatisfyWithClauseList(pWork->xPositiveClauses.pEntry(0), pWork->xPositiveClauses.pLastEntry()); if (_bFilterWithClauseList(pWork->xNegativeClauses.pEntry(0), pWork->xNegativeClauses.pLastEntry())) { return _bBackup(); } } else { _aAssignment[_eCurrentID] = NON_VALUE; _vLabelVariable(_eCurrentID,0); _vSatisfyWithClauseList(pWork->xNegativeClauses.pEntry(0), pWork->xNegativeClauses.pLastEntry()); if (_bFilterWithClauseList(pWork->xPositiveClauses.pEntry(0), pWork->xPositiveClauses.pLastEntry())) { return _bBackup(); } } if (_bNonTrivialUnitPropagate(pWork->xUnitClause)) { return _bBackup(); } if (_bUnitPropagate()) { return _bBackup(); } return 0; } if (_pGoodReason->eTop() == _eCurrentID) { _pGoodReason->ePop(); } if (!_bFindAll) { _vCreateGoodReason(); eParentID = _eFindDeepestID(pWork->pSolutionInfo->xGoodReason); assert(eParentID != _eCurrentID); // Add branch counts together if (pSolutionInfo->pOldSolutionCount) { pSolutionInfo->xSolutionCount += *(pSolutionInfo->pOldSolutionCount); if (pSolutionInfo->xSolutionCount > _xKnownSolutions) { _xKnownSolutions.vSet(pSolutionInfo->xSolutionCount); } delete pSolutionInfo->pOldSolutionCount; pSolutionInfo->pOldSolutionCount = 0; } if (eParentID != -1) { pParentWork = &(_aVariableStruct[eParentID]); if (!pParentWork->pSolutionInfo) { pParentWork->pSolutionInfo = pWork->pSolutionInfo; pParentWork->pSolutionInfo->xGoodList.vAdd(_eCurrentID); } else { pParentWork->pSolutionInfo->xGoodReason.vAppendVariables(pSolutionInfo->xGoodReason); if (!pParentWork->pSolutionInfo->pOldSolutionCount) { pParentWork->pSolutionInfo->xGoodList.vAppend(pSolutionInfo->xGoodList); pParentWork->pSolutionInfo->xGoodList.vAdd(_eCurrentID); } pParentWork->pSolutionInfo->xSolutionCount *= pSolutionInfo->xSolutionCount; if (pParentWork->pSolutionInfo->xSolutionCount > _xKnownSolutions) { _xKnownSolutions.vSet(pParentWork->pSolutionInfo->xSolutionCount); } delete pSolutionInfo; } } else { _xSolutionCount *= pSolutionInfo->xSolutionCount; if (_xSolutionCount > _xKnownSolutions) { _xKnownSolutions.vSet(_xSolutionCount); } delete pSolutionInfo; _eCurrentID = _aPositionToID[_iCurrentVariable-1]; } } else { // Finding all solutions instead of counting pWork->bBranch = 0; if (_iCurrentVariable) { eParentID = _aPositionToID[_iCurrentVariable-1]; pParentWork = &(_aVariableStruct[eParentID]); if (!pParentWork->pSolutionInfo) { pParentWork->pSolutionInfo = pWork->pSolutionInfo; } else { delete pSolutionInfo; } } else { eParentID = -1; delete pSolutionInfo; } } pWork->pSolutionInfo = 0; pWork->bBranch = 0; _aAssignment[_eCurrentID] = NON_VALUE; pWork->pReason = 0; pWork->xUnitClause.vClear(); _iCurrentVariable--; if (_iCurrentVariable == 0) { // the search is complete. assert(_pGoodReason->iCount() == 0); return 1; } _eCurrentID = _aPositionToID[_iCurrentVariable-1]; } while(1); } VariableID SATSolver::_eFindDeepestID(VariableList& xList_) { int iDeepestIndex = -1; VariableID eBest = -1; for (int i=0; i<xList_.iCount(); i++) { VariableID eID = xList_.iVariable(i); if (_aIDToPosition[eID] > iDeepestIndex) { iDeepestIndex = _aIDToPosition[eID]; eBest = eID; } } return eBest; } void SATSolver::_vPrintStack() { int k; int iBranchDepth = 0; for (k=0; k<_iCurrentVariable; k++) { VariableID eWorkID = _aPositionToID[k]; if (_aVariableStruct[eWorkID].bBranch) { iBranchDepth++; } } xOutputStream << "c Stats: BD=" << iBranchDepth << ", BP=" << _iBranchSelections << ", CD=" << _iContradictions << ", LC=" << _xLearnedClauses.iClauseCount() << ", RLC=" << _iRelevantClauses << endl; if (_iSolutionCount && !_bFindAll) { xOutputStream << "c Solutions: "; char* aBuffer = _xKnownSolutions.aToString(); xOutputStream << aBuffer << endl; delete [] aBuffer; } xOutputStream << "c Stack: "; int iNoBranch = 0; for (k=0; k<_iCurrentVariable; k++) { VariableID eWorkID = _aPositionToID[k]; if (_aVariableStruct[eWorkID].bBranch) { xOutputStream << iNoBranch << ' '; //xOutputStream << iNoBranch << " (" << eWorkID+1 << ") "; iNoBranch = 0; } else { iNoBranch++; } } if (iNoBranch) xOutputStream << iNoBranch; xOutputStream << endl; } void SATSolver::_vCleanup() { delete [] _aAssignment; delete [] _aVariableStruct; delete [] _aPositionToID; delete [] _aIDToPosition; delete [] _aScore0; delete [] _aScore1; delete [] _aScore; delete [] _aBinaryCount0; delete [] _aBinaryCount1; delete _pUnitVariables0; delete _pUnitVariables1; delete _pUnitList; delete _pPositiveBackup; delete _pNegativeBackup; delete _pGoodList; delete _pGoodReason; } inline void SATSolver::_vDecideFilterClause(VariableID eID, Clause* pWorkClause) { if (_bFavorSmallClauses && _aVariableStruct[eID].pReason->iVariableCount() > pWorkClause->iVariableCount()) { _aVariableStruct[eID].pReason = pWorkClause; } else { if (xRandom.bRandom()) { _aVariableStruct[eID].pReason = pWorkClause; } } } boolean SATSolver::_bNonTrivialUnitPropagate(ClauseList& xUnitClauses_) { // Returns 1 if contradiction is reached Clause** pStart = xUnitClauses_.pEntry(0); Clause** pEnd = xUnitClauses_.pLastEntry(); for (; pStart < pEnd; pStart++) { Clause* pClause = *pStart; VariableID eUnitVar; int x; for (x=0; ; x++) { assert(x<pClause->iPermaCount()); if (_aAssignment[pClause->eConstrainedVariable(x)] == NON_VALUE) { eUnitVar = pClause->eConstrainedVariable(x); break; } } if (!_pGoodList->bHasVariable(eUnitVar)) { continue; } if (pClause->iIsNegated(x)) { if (!_aVariableStruct[eUnitVar].pReason) { assert(!_pUnitVariables1->bHasVariable(eUnitVar)); _pUnitVariables0->vAddVariableNoCheck(eUnitVar); _aVariableStruct[eUnitVar].pReason = pClause; } else if (_pUnitVariables1->bHasVariable(eUnitVar)) { _vSetContradiction(eUnitVar, pClause); xUnitClauses_.vClear(); return 1; } else { assert(_pUnitVariables0->bHasVariable(eUnitVar)); _vDecideFilterClause(eUnitVar, pClause); } } else { if (!_aVariableStruct[eUnitVar].pReason) { assert(!_pUnitVariables0->bHasVariable(eUnitVar)); _pUnitVariables1->vAddVariableNoCheck(eUnitVar); _aVariableStruct[eUnitVar].pReason = pClause; } else if (_pUnitVariables0->bHasVariable(eUnitVar)) { _vSetContradiction(eUnitVar, pClause); xUnitClauses_.vClear(); return 1; } else { assert(_pUnitVariables1->bHasVariable(eUnitVar)); _vDecideFilterClause(eUnitVar, pClause); } } } xUnitClauses_.vClear(); return 0; } void SATSolver::_vUndoClauseModifications() { Clause** pStart1; Clause** pEnd1; Clause** pStart2; Clause** pEnd2; VariableStruct* pWork = &(_aVariableStruct[_eCurrentID]); if (_aAssignment[_eCurrentID] == 1) { pStart1 = pWork->xNegativeClauses.pEntry(0); pEnd1 = pWork->xNegativeClauses.pLastEntry(); pStart2 = pWork->xPositiveClauses.pEntry(0); pEnd2 = pWork->xPositiveClauses.pLastEntry(); } else { pStart2 = pWork->xNegativeClauses.pEntry(0); pEnd2 = pWork->xNegativeClauses.pLastEntry(); pStart1 = pWork->xPositiveClauses.pEntry(0); pEnd1 = pWork->xPositiveClauses.pLastEntry(); } Clause* pWorkClause; int j; for (;pStart1 < pEnd1; pStart1++) { pWorkClause = *pStart1; if (pWorkClause->iExpand() == 3) { for (j=0; j<pWorkClause->iPermaCount(); j++) { if (pWorkClause->iIsNegated(j)) { _aBinaryCount0[pWorkClause->eConstrainedVariable(j)]--; assert(_aBinaryCount0[pWorkClause->eConstrainedVariable(j)] >= 0); } else { _aBinaryCount1[pWorkClause->eConstrainedVariable(j)]--; assert(_aBinaryCount1[pWorkClause->eConstrainedVariable(j)] >= 0); } } } } for (;pStart2 < pEnd2; pStart2++) { pWorkClause = *pStart2; pWorkClause->vMakeUnsatisfied(); if (!pWorkClause->bIsSatisfied()) { if (pWorkClause->iWorkingLength() == 2) { for (j=0; j<pWorkClause->iPermaCount(); j++) { if (pWorkClause->iIsNegated(j)) { _aBinaryCount0[pWorkClause->eConstrainedVariable(j)]++; } else { _aBinaryCount1[pWorkClause->eConstrainedVariable(j)]++; } } } } } _vDeleteClauses(pWork->xDeleteList); } boolean SATSolver::_bTimeLimitExpired() { time_t iCheckTime; if (!_bNoTimeLimit) { time(&iCheckTime); if (iCheckTime - _iElapsedTime >= _iMaxTime) { return 1; } } return 0; } boolean SATSolver::_bPrintStackCheck() { time_t iCheckTime; if (_bPrintStack) { time(&iCheckTime); if (iCheckTime - _iLastCheckTime >= _iPrintStackPeriod) { _iLastCheckTime = iCheckTime; return true; } } return false; }
28.97475
104
0.658398
problem-frames
b4305e2c7fb22789d7587e77e7fe3c18933a591b
1,088
cpp
C++
src/mt/fs/file.cpp
nfagan/mtype
a745271d366df64e1b4692cc90f0685ea4084ba6
[ "MIT" ]
null
null
null
src/mt/fs/file.cpp
nfagan/mtype
a745271d366df64e1b4692cc90f0685ea4084ba6
[ "MIT" ]
null
null
null
src/mt/fs/file.cpp
nfagan/mtype
a745271d366df64e1b4692cc90f0685ea4084ba6
[ "MIT" ]
null
null
null
#include "file.hpp" #include "path.hpp" #include "../Optional.hpp" #include "../config.hpp" #include <fstream> #if defined(MT_UNIX) #include <sys/stat.h> #endif #if MT_IS_MSVC #include <windows.h> #endif namespace mt::fs { Optional<std::unique_ptr<std::string>> read_file(const FilePath& path) { std::ifstream ifs(path.str()); if (!ifs) { return NullOpt{}; } auto contents = std::make_unique<std::string>((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); return Optional<std::unique_ptr<std::string>>(std::move(contents)); } #if defined(MT_UNIX) bool file_exists(const FilePath& path) { struct stat sb; const int status = stat(path.c_str(), &sb); if (status != 0) { return false; } return (sb.st_mode & S_IFMT) == S_IFREG; } #elif defined(MT_WIN) bool file_exists(const FilePath& path) { return !(INVALID_FILE_ATTRIBUTES == GetFileAttributes(path.c_str()) && GetLastError() == ERROR_FILE_NOT_FOUND); } #else #error "Expected one of Unix or Windows for OS." #endif }
22.666667
86
0.653493
nfagan
b4309cac4069973b4739419e4d2ff81cb2b2b07a
1,855
cpp
C++
src/zimg/depth/x86/f16c_ivb.cpp
marxin/zimg
b6334acf4112877afc400cd9a0ace54e171e3f11
[ "WTFPL" ]
287
2015-01-02T13:59:32.000Z
2022-03-29T22:47:54.000Z
src/zimg/depth/x86/f16c_ivb.cpp
marxin/zimg
b6334acf4112877afc400cd9a0ace54e171e3f11
[ "WTFPL" ]
143
2015-04-17T06:20:17.000Z
2022-03-29T09:13:45.000Z
src/zimg/depth/x86/f16c_ivb.cpp
marxin/zimg
b6334acf4112877afc400cd9a0ace54e171e3f11
[ "WTFPL" ]
64
2015-01-02T13:59:35.000Z
2022-03-30T17:20:55.000Z
#ifdef ZIMG_X86 #include "common/ccdep.h" #include <immintrin.h> #include "common/align.h" #include "f16c_x86.h" #include "common/x86/sse2_util.h" #include "common/x86/avx_util.h" namespace zimg { namespace depth { void f16c_half_to_float_ivb(const void *src, void *dst, unsigned left, unsigned right) { const uint16_t *src_p = static_cast<const uint16_t *>(src); float *dst_p = static_cast<float *>(dst); unsigned vec_left = ceil_n(left, 8); unsigned vec_right = floor_n(right, 8); if (left != vec_left) { __m256 x = _mm256_cvtph_ps(_mm_load_si128((const __m128i *)(src_p + vec_left - 8))); mm256_store_idxhi_ps(dst_p + vec_left - 8, x, left % 8); } for (unsigned j = vec_left; j < vec_right; j += 8) { __m256 x = _mm256_cvtph_ps(_mm_load_si128((const __m128i *)(src_p + j))); _mm256_store_ps(dst_p + j, x); } if (right != vec_right) { __m256 x = _mm256_cvtph_ps(_mm_load_si128((const __m128i *)(src_p + vec_right))); mm256_store_idxlo_ps(dst_p + vec_right, x, right % 8); } } void f16c_float_to_half_ivb(const void *src, void *dst, unsigned left, unsigned right) { const float *src_p = static_cast<const float *>(src); uint16_t *dst_p = static_cast<uint16_t *>(dst); unsigned vec_left = ceil_n(left, 8); unsigned vec_right = floor_n(right, 8); if (left != vec_left) { __m128i x = _mm256_cvtps_ph(_mm256_load_ps(src_p + vec_left - 8), 0); mm_store_idxhi_epi16((__m128i *)(dst_p + vec_left - 8), x, left % 8); } for (unsigned j = vec_left; j < vec_right; j += 8) { __m128i x = _mm256_cvtps_ph(_mm256_load_ps(src_p + j), 0); _mm_store_si128((__m128i *)(dst_p + j), x); } if (right != vec_right) { __m128i x = _mm256_cvtps_ph(_mm256_load_ps(src_p + vec_right), 0); mm_store_idxlo_epi16((__m128i *)(dst_p + vec_right), x, right % 8); } } } // namespace depth } // namespace zimg #endif // ZIMG_X86
27.686567
86
0.690566
marxin
b432a808c1a85e543d9a6468bc3760adb46b7810
112,969
cpp
C++
flow/stacktrace.amalgamation.cpp
atn34/foundationdb
bd52f8cbd6596671d19af394ec8077c6298cc6aa
[ "Apache-2.0" ]
4
2018-10-28T22:44:58.000Z
2021-07-13T07:06:47.000Z
flow/stacktrace.amalgamation.cpp
atn34/foundationdb
bd52f8cbd6596671d19af394ec8077c6298cc6aa
[ "Apache-2.0" ]
5
2018-04-27T21:59:53.000Z
2018-07-27T02:54:53.000Z
flow/stacktrace.amalgamation.cpp
atn34/foundationdb
bd52f8cbd6596671d19af394ec8077c6298cc6aa
[ "Apache-2.0" ]
1
2020-11-18T17:40:46.000Z
2020-11-18T17:40:46.000Z
// Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef ABSL_DEBUGGING_INTERNAL_ADDRESS_IS_READABLE_H_ #define ABSL_DEBUGGING_INTERNAL_ADDRESS_IS_READABLE_H_ namespace absl { namespace debug_internal { // Return whether the byte at *addr is readable, without faulting. // Save and restores errno. bool AddressIsReadable(const void *addr); } // namespace debug_internal } // namespace absl #endif // ABSL_DEBUGGING_INTERNAL_ADDRESS_IS_READABLE_H_ /* * Copyright 2017 The Abseil Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Allow dynamic symbol lookup for in-memory Elf images. #ifndef ABSL_DEBUGGING_INTERNAL_ELF_MEM_IMAGE_H_ #define ABSL_DEBUGGING_INTERNAL_ELF_MEM_IMAGE_H_ // Including this will define the __GLIBC__ macro if glibc is being // used. #include <climits> // Maybe one day we can rewrite this file not to require the elf // symbol extensions in glibc, but for right now we need them. #ifdef ABSL_HAVE_ELF_MEM_IMAGE #error ABSL_HAVE_ELF_MEM_IMAGE cannot be directly set #endif #if defined(__ELF__) && defined(__GLIBC__) && !defined(__native_client__) && \ !defined(__asmjs__) #define ABSL_HAVE_ELF_MEM_IMAGE 1 #endif #if ABSL_HAVE_ELF_MEM_IMAGE #include <link.h> // for ElfW namespace absl { namespace debug_internal { // An in-memory ELF image (may not exist on disk). class ElfMemImage { public: // Sentinel: there could never be an elf image at this address. static const void *const kInvalidBase; // Information about a single vdso symbol. // All pointers are into .dynsym, .dynstr, or .text of the VDSO. // Do not free() them or modify through them. struct SymbolInfo { const char *name; // E.g. "__vdso_getcpu" const char *version; // E.g. "LINUX_2.6", could be "" // for unversioned symbol. const void *address; // Relocated symbol address. const ElfW(Sym) *symbol; // Symbol in the dynamic symbol table. }; // Supports iteration over all dynamic symbols. class SymbolIterator { public: friend class ElfMemImage; const SymbolInfo *operator->() const; const SymbolInfo &operator*() const; SymbolIterator& operator++(); bool operator!=(const SymbolIterator &rhs) const; bool operator==(const SymbolIterator &rhs) const; private: SymbolIterator(const void *const image, int index); void Update(int incr); SymbolInfo info_; int index_; const void *const image_; }; explicit ElfMemImage(const void *base); void Init(const void *base); bool IsPresent() const { return ehdr_ != nullptr; } const ElfW(Phdr)* GetPhdr(int index) const; const ElfW(Sym)* GetDynsym(int index) const; const ElfW(Versym)* GetVersym(int index) const; const ElfW(Verdef)* GetVerdef(int index) const; const ElfW(Verdaux)* GetVerdefAux(const ElfW(Verdef) *verdef) const; const char* GetDynstr(ElfW(Word) offset) const; const void* GetSymAddr(const ElfW(Sym) *sym) const; const char* GetVerstr(ElfW(Word) offset) const; int GetNumSymbols() const; SymbolIterator begin() const; SymbolIterator end() const; // Look up versioned dynamic symbol in the image. // Returns false if image is not present, or doesn't contain given // symbol/version/type combination. // If info_out is non-null, additional details are filled in. bool LookupSymbol(const char *name, const char *version, int symbol_type, SymbolInfo *info_out) const; // Find info about symbol (if any) which overlaps given address. // Returns true if symbol was found; false if image isn't present // or doesn't have a symbol overlapping given address. // If info_out is non-null, additional details are filled in. bool LookupSymbolByAddress(const void *address, SymbolInfo *info_out) const; private: const ElfW(Ehdr) *ehdr_; const ElfW(Sym) *dynsym_; const ElfW(Versym) *versym_; const ElfW(Verdef) *verdef_; const ElfW(Word) *hash_; const char *dynstr_; size_t strsize_; size_t verdefnum_; ElfW(Addr) link_base_; // Link-time base (p_vaddr of first PT_LOAD). }; } // namespace debug_internal } // namespace absl #endif // ABSL_HAVE_ELF_MEM_IMAGE #endif // ABSL_DEBUGGING_INTERNAL_ELF_MEM_IMAGE_H_ /* * Copyright 2017 The Abseil Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * Defines ABSL_STACKTRACE_INL_HEADER to the *-inl.h containing * actual unwinder implementation. * This header is "private" to stacktrace.cc. * DO NOT include it into any other files. */ #ifndef ABSL_DEBUGGING_INTERNAL_STACKTRACE_CONFIG_H_ #define ABSL_DEBUGGING_INTERNAL_STACKTRACE_CONFIG_H_ // First, test platforms which only support a stub. #if ABSL_STACKTRACE_INL_HEADER #error ABSL_STACKTRACE_INL_HEADER cannot be directly set #elif defined(__native_client__) || defined(__APPLE__) || \ defined(__ANDROID__) || defined(__myriad2__) || defined(asmjs__) || \ defined(__Fuchsia__) #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_unimplemented-inl.inc" // Next, test for Mips and Windows. // TODO(marmstrong): Mips case, remove the check for ABSL_STACKTRACE_INL_HEADER #elif defined(__mips__) && !defined(ABSL_STACKTRACE_INL_HEADER) #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_unimplemented-inl.inc" #elif defined(_WIN32) // windows #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_win32-inl.inc" // Finally, test NO_FRAME_POINTER. #elif !defined(NO_FRAME_POINTER) # if defined(__i386__) || defined(__x86_64__) #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_x86-inl.inc" # elif defined(__ppc__) || defined(__PPC__) #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_powerpc-inl.inc" # elif defined(__aarch64__) #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_aarch64-inl.inc" # elif defined(__arm__) #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_arm-inl.inc" # endif #else // defined(NO_FRAME_POINTER) # if defined(__i386__) || defined(__x86_64__) || defined(__aarch64__) #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_unimplemented-inl.inc" # elif defined(__ppc__) || defined(__PPC__) // Use glibc's backtrace. #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_generic-inl.inc" # elif defined(__arm__) # error stacktrace without frame pointer is not supported on ARM # endif #endif // NO_FRAME_POINTER #if !defined(ABSL_STACKTRACE_INL_HEADER) #error Not supported yet #endif #endif // ABSL_DEBUGGING_INTERNAL_STACKTRACE_CONFIG_H_ // // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Allow dynamic symbol lookup in the kernel VDSO page. // // VDSO stands for "Virtual Dynamic Shared Object" -- a page of // executable code, which looks like a shared library, but doesn't // necessarily exist anywhere on disk, and which gets mmap()ed into // every process by kernels which support VDSO, such as 2.6.x for 32-bit // executables, and 2.6.24 and above for 64-bit executables. // // More details could be found here: // http://www.trilithium.com/johan/2005/08/linux-gate/ // // VDSOSupport -- a class representing kernel VDSO (if present). // // Example usage: // VDSOSupport vdso; // VDSOSupport::SymbolInfo info; // typedef (*FN)(unsigned *, void *, void *); // FN fn = nullptr; // if (vdso.LookupSymbol("__vdso_getcpu", "LINUX_2.6", STT_FUNC, &info)) { // fn = reinterpret_cast<FN>(info.address); // } #ifndef ABSL_DEBUGGING_INTERNAL_VDSO_SUPPORT_H_ #define ABSL_DEBUGGING_INTERNAL_VDSO_SUPPORT_H_ #include <atomic> #ifdef ABSL_HAVE_ELF_MEM_IMAGE #ifdef ABSL_HAVE_VDSO_SUPPORT #error ABSL_HAVE_VDSO_SUPPORT cannot be directly set #else #define ABSL_HAVE_VDSO_SUPPORT 1 #endif namespace absl { namespace debug_internal { // NOTE: this class may be used from within tcmalloc, and can not // use any memory allocation routines. class VDSOSupport { public: VDSOSupport(); typedef ElfMemImage::SymbolInfo SymbolInfo; typedef ElfMemImage::SymbolIterator SymbolIterator; // On PowerPC64 VDSO symbols can either be of type STT_FUNC or STT_NOTYPE // depending on how the kernel is built. The kernel is normally built with // STT_NOTYPE type VDSO symbols. Let's make things simpler first by using a // compile-time constant. #ifdef __powerpc64__ enum { kVDSOSymbolType = STT_NOTYPE }; #else enum { kVDSOSymbolType = STT_FUNC }; #endif // Answers whether we have a vdso at all. bool IsPresent() const { return image_.IsPresent(); } // Allow to iterate over all VDSO symbols. SymbolIterator begin() const { return image_.begin(); } SymbolIterator end() const { return image_.end(); } // Look up versioned dynamic symbol in the kernel VDSO. // Returns false if VDSO is not present, or doesn't contain given // symbol/version/type combination. // If info_out != nullptr, additional details are filled in. bool LookupSymbol(const char *name, const char *version, int symbol_type, SymbolInfo *info_out) const; // Find info about symbol (if any) which overlaps given address. // Returns true if symbol was found; false if VDSO isn't present // or doesn't have a symbol overlapping given address. // If info_out != nullptr, additional details are filled in. bool LookupSymbolByAddress(const void *address, SymbolInfo *info_out) const; // Used only for testing. Replace real VDSO base with a mock. // Returns previous value of vdso_base_. After you are done testing, // you are expected to call SetBase() with previous value, in order to // reset state to the way it was. const void *SetBase(const void *s); // Computes vdso_base_ and returns it. Should be called as early as // possible; before any thread creation, chroot or setuid. static const void *Init(); private: // image_ represents VDSO ELF image in memory. // image_.ehdr_ == nullptr implies there is no VDSO. ElfMemImage image_; // Cached value of auxv AT_SYSINFO_EHDR, computed once. // This is a tri-state: // kInvalidBase => value hasn't been determined yet. // 0 => there is no VDSO. // else => vma of VDSO Elf{32,64}_Ehdr. // // When testing with mock VDSO, low bit is set. // The low bit is always available because vdso_base_ is // page-aligned. static std::atomic<const void *> vdso_base_; // NOLINT on 'long' because these routines mimic kernel api. // The 'cache' parameter may be used by some versions of the kernel, // and should be nullptr or point to a static buffer containing at // least two 'long's. static long InitAndGetCPU(unsigned *cpu, void *cache, // NOLINT 'long'. void *unused); static long GetCPUViaSyscall(unsigned *cpu, void *cache, // NOLINT 'long'. void *unused); typedef long (*GetCpuFn)(unsigned *cpu, void *cache, // NOLINT 'long'. void *unused); // This function pointer may point to InitAndGetCPU, // GetCPUViaSyscall, or __vdso_getcpu at different stages of initialization. static std::atomic<GetCpuFn> getcpu_fn_; friend int GetCPU(void); // Needs access to getcpu_fn_. VDSOSupport(const VDSOSupport&) = delete; VDSOSupport& operator=(const VDSOSupport&) = delete; }; // Same as sched_getcpu() on later glibc versions. // Return current CPU, using (fast) __vdso_getcpu@LINUX_2.6 if present, // otherwise use syscall(SYS_getcpu,...). // May return -1 with errno == ENOSYS if the kernel doesn't // support SYS_getcpu. int GetCPU(); } // namespace debug_internal } // namespace absl #endif // ABSL_HAVE_ELF_MEM_IMAGE #endif // ABSL_DEBUGGING_INTERNAL_VDSO_SUPPORT_H_ // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // This header file defines macros for declaring attributes for functions, // types, and variables. // // These macros are used within Abseil and allow the compiler to optimize, where // applicable, certain function calls. // // This file is used for both C and C++! // // Most macros here are exposing GCC or Clang features, and are stubbed out for // other compilers. // // GCC attributes documentation: // https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Function-Attributes.html // https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Variable-Attributes.html // https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Type-Attributes.html // // Most attributes in this file are already supported by GCC 4.7. However, some // of them are not supported in older version of Clang. Thus, we check // `__has_attribute()` first. If the check fails, we check if we are on GCC and // assume the attribute exists on GCC (which is verified on GCC 4.7). // // ----------------------------------------------------------------------------- // Sanitizer Attributes // ----------------------------------------------------------------------------- // // Sanitizer-related attributes are not "defined" in this file (and indeed // are not defined as such in any file). To utilize the following // sanitizer-related attributes within your builds, define the following macros // within your build using a `-D` flag, along with the given value for // `-fsanitize`: // // * `ADDRESS_SANITIZER` + `-fsanitize=address` (Clang, GCC 4.8) // * `MEMORY_SANITIZER` + `-fsanitize=memory` (Clang-only) // * `THREAD_SANITIZER + `-fsanitize=thread` (Clang, GCC 4.8+) // * `UNDEFINED_BEHAVIOR_SANITIZER` + `-fsanitize=undefined` (Clang, GCC 4.9+) // * `CONTROL_FLOW_INTEGRITY` + -fsanitize=cfi (Clang-only) // // Example: // // // Enable branches in the Abseil code that are tagged for ASan: // $ bazel -D ADDRESS_SANITIZER -fsanitize=address *target* // // Since these macro names are only supported by GCC and Clang, we only check // for `__GNUC__` (GCC or Clang) and the above macros. #ifndef ABSL_BASE_ATTRIBUTES_H_ #define ABSL_BASE_ATTRIBUTES_H_ // ABSL_HAVE_ATTRIBUTE // // A function-like feature checking macro that is a wrapper around // `__has_attribute`, which is defined by GCC 5+ and Clang and evaluates to a // nonzero constant integer if the attribute is supported or 0 if not. // // It evaluates to zero if `__has_attribute` is not defined by the compiler. // // GCC: https://gcc.gnu.org/gcc-5/changes.html // Clang: https://clang.llvm.org/docs/LanguageExtensions.html #ifdef __has_attribute #define ABSL_HAVE_ATTRIBUTE(x) __has_attribute(x) #else #define ABSL_HAVE_ATTRIBUTE(x) 0 #endif // ABSL_HAVE_CPP_ATTRIBUTE // // A function-like feature checking macro that accepts C++11 style attributes. // It's a wrapper around `__has_cpp_attribute`, defined by ISO C++ SD-6 // (http://en.cppreference.com/w/cpp/experimental/feature_test). If we don't // find `__has_cpp_attribute`, will evaluate to 0. #if defined(__cplusplus) && defined(__has_cpp_attribute) // NOTE: requiring __cplusplus above should not be necessary, but // works around https://bugs.llvm.org/show_bug.cgi?id=23435. #define ABSL_HAVE_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) #else #define ABSL_HAVE_CPP_ATTRIBUTE(x) 0 #endif // ----------------------------------------------------------------------------- // Function Attributes // ----------------------------------------------------------------------------- // // GCC: https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html // Clang: https://clang.llvm.org/docs/AttributeReference.html // ABSL_PRINTF_ATTRIBUTE // ABSL_SCANF_ATTRIBUTE // // Tells the compiler to perform `printf` format std::string checking if the // compiler supports it; see the 'format' attribute in // <http://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Function-Attributes.html>. // // Note: As the GCC manual states, "[s]ince non-static C++ methods // have an implicit 'this' argument, the arguments of such methods // should be counted from two, not one." #if ABSL_HAVE_ATTRIBUTE(format) || (defined(__GNUC__) && !defined(__clang__)) #define ABSL_PRINTF_ATTRIBUTE(string_index, first_to_check) \ __attribute__((__format__(__printf__, string_index, first_to_check))) #define ABSL_SCANF_ATTRIBUTE(string_index, first_to_check) \ __attribute__((__format__(__scanf__, string_index, first_to_check))) #else #define ABSL_PRINTF_ATTRIBUTE(string_index, first_to_check) #define ABSL_SCANF_ATTRIBUTE(string_index, first_to_check) #endif // ABSL_ATTRIBUTE_ALWAYS_INLINE // ABSL_ATTRIBUTE_NOINLINE // // Forces functions to either inline or not inline. Introduced in gcc 3.1. #if ABSL_HAVE_ATTRIBUTE(always_inline) || \ (defined(__GNUC__) && !defined(__clang__)) #define ABSL_ATTRIBUTE_ALWAYS_INLINE __attribute__((always_inline)) #define ABSL_HAVE_ATTRIBUTE_ALWAYS_INLINE 1 #else #define ABSL_ATTRIBUTE_ALWAYS_INLINE #endif #if ABSL_HAVE_ATTRIBUTE(noinline) || (defined(__GNUC__) && !defined(__clang__)) #define ABSL_ATTRIBUTE_NOINLINE __attribute__((noinline)) #define ABSL_HAVE_ATTRIBUTE_NOINLINE 1 #else #define ABSL_ATTRIBUTE_NOINLINE #endif // ABSL_ATTRIBUTE_NO_TAIL_CALL // // Prevents the compiler from optimizing away stack frames for functions which // end in a call to another function. #if ABSL_HAVE_ATTRIBUTE(disable_tail_calls) #define ABSL_HAVE_ATTRIBUTE_NO_TAIL_CALL 1 #define ABSL_ATTRIBUTE_NO_TAIL_CALL __attribute__((disable_tail_calls)) #elif defined(__GNUC__) && !defined(__clang__) #define ABSL_HAVE_ATTRIBUTE_NO_TAIL_CALL 1 #define ABSL_ATTRIBUTE_NO_TAIL_CALL \ __attribute__((optimize("no-optimize-sibling-calls"))) #else #define ABSL_ATTRIBUTE_NO_TAIL_CALL #define ABSL_HAVE_ATTRIBUTE_NO_TAIL_CALL 0 #endif // ABSL_ATTRIBUTE_WEAK // // Tags a function as weak for the purposes of compilation and linking. #if ABSL_HAVE_ATTRIBUTE(weak) || (defined(__GNUC__) && !defined(__clang__)) #undef ABSL_ATTRIBUTE_WEAK #define ABSL_ATTRIBUTE_WEAK __attribute__((weak)) #define ABSL_HAVE_ATTRIBUTE_WEAK 1 #else #define ABSL_ATTRIBUTE_WEAK #define ABSL_HAVE_ATTRIBUTE_WEAK 0 #endif // ABSL_ATTRIBUTE_NONNULL // // Tells the compiler either (a) that a particular function parameter // should be a non-null pointer, or (b) that all pointer arguments should // be non-null. // // Note: As the GCC manual states, "[s]ince non-static C++ methods // have an implicit 'this' argument, the arguments of such methods // should be counted from two, not one." // // Args are indexed starting at 1. // // For non-static class member functions, the implicit `this` argument // is arg 1, and the first explicit argument is arg 2. For static class member // functions, there is no implicit `this`, and the first explicit argument is // arg 1. // // Example: // // /* arg_a cannot be null, but arg_b can */ // void Function(void* arg_a, void* arg_b) ABSL_ATTRIBUTE_NONNULL(1); // // class C { // /* arg_a cannot be null, but arg_b can */ // void Method(void* arg_a, void* arg_b) ABSL_ATTRIBUTE_NONNULL(2); // // /* arg_a cannot be null, but arg_b can */ // static void StaticMethod(void* arg_a, void* arg_b) // ABSL_ATTRIBUTE_NONNULL(1); // }; // // If no arguments are provided, then all pointer arguments should be non-null. // // /* No pointer arguments may be null. */ // void Function(void* arg_a, void* arg_b, int arg_c) ABSL_ATTRIBUTE_NONNULL(); // // NOTE: The GCC nonnull attribute actually accepts a list of arguments, but // ABSL_ATTRIBUTE_NONNULL does not. #if ABSL_HAVE_ATTRIBUTE(nonnull) || (defined(__GNUC__) && !defined(__clang__)) #define ABSL_ATTRIBUTE_NONNULL(arg_index) __attribute__((nonnull(arg_index))) #else #define ABSL_ATTRIBUTE_NONNULL(...) #endif // ABSL_ATTRIBUTE_NORETURN // // Tells the compiler that a given function never returns. #if ABSL_HAVE_ATTRIBUTE(noreturn) || (defined(__GNUC__) && !defined(__clang__)) #define ABSL_ATTRIBUTE_NORETURN __attribute__((noreturn)) #elif defined(_MSC_VER) #define ABSL_ATTRIBUTE_NORETURN __declspec(noreturn) #else #define ABSL_ATTRIBUTE_NORETURN #endif // ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS // // Tells the AddressSanitizer (or other memory testing tools) to ignore a given // function. Useful for cases when a function reads random locations on stack, // calls _exit from a cloned subprocess, deliberately accesses buffer // out of bounds or does other scary things with memory. // NOTE: GCC supports AddressSanitizer(asan) since 4.8. // https://gcc.gnu.org/gcc-4.8/changes.html #if defined(__GNUC__) && defined(ADDRESS_SANITIZER) #define ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS __attribute__((no_sanitize_address)) #else #define ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS #endif // ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY // // Tells the MemorySanitizer to relax the handling of a given function. All // "Use of uninitialized value" warnings from such functions will be suppressed, // and all values loaded from memory will be considered fully initialized. // This attribute is similar to the ADDRESS_SANITIZER attribute above, but deals // with initialized-ness rather than addressability issues. // NOTE: MemorySanitizer(msan) is supported by Clang but not GCC. #if defined(__GNUC__) && defined(MEMORY_SANITIZER) #define ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory)) #else #define ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY #endif // ABSL_ATTRIBUTE_NO_SANITIZE_THREAD // // Tells the ThreadSanitizer to not instrument a given function. // NOTE: GCC supports ThreadSanitizer(tsan) since 4.8. // https://gcc.gnu.org/gcc-4.8/changes.html #if defined(__GNUC__) && defined(THREAD_SANITIZER) #define ABSL_ATTRIBUTE_NO_SANITIZE_THREAD __attribute__((no_sanitize_thread)) #else #define ABSL_ATTRIBUTE_NO_SANITIZE_THREAD #endif // ABSL_ATTRIBUTE_NO_SANITIZE_UNDEFINED // // Tells the UndefinedSanitizer to ignore a given function. Useful for cases // where certain behavior (eg. devision by zero) is being used intentionally. // NOTE: GCC supports UndefinedBehaviorSanitizer(ubsan) since 4.9. // https://gcc.gnu.org/gcc-4.9/changes.html #if defined(__GNUC__) && \ (defined(UNDEFINED_BEHAVIOR_SANITIZER) || defined(ADDRESS_SANITIZER)) #define ABSL_ATTRIBUTE_NO_SANITIZE_UNDEFINED \ __attribute__((no_sanitize("undefined"))) #else #define ABSL_ATTRIBUTE_NO_SANITIZE_UNDEFINED #endif // ABSL_ATTRIBUTE_NO_SANITIZE_CFI // // Tells the ControlFlowIntegrity sanitizer to not instrument a given function. // See https://clang.llvm.org/docs/ControlFlowIntegrity.html for details. #if defined(__GNUC__) && defined(CONTROL_FLOW_INTEGRITY) #define ABSL_ATTRIBUTE_NO_SANITIZE_CFI __attribute__((no_sanitize("cfi"))) #else #define ABSL_ATTRIBUTE_NO_SANITIZE_CFI #endif // ABSL_HAVE_ATTRIBUTE_SECTION // // Indicates whether labeled sections are supported. Labeled sections are not // supported on Darwin/iOS. #ifdef ABSL_HAVE_ATTRIBUTE_SECTION #error ABSL_HAVE_ATTRIBUTE_SECTION cannot be directly set #elif (ABSL_HAVE_ATTRIBUTE(section) || \ (defined(__GNUC__) && !defined(__clang__))) && \ !defined(__APPLE__) #define ABSL_HAVE_ATTRIBUTE_SECTION 1 // ABSL_ATTRIBUTE_SECTION // // Tells the compiler/linker to put a given function into a section and define // `__start_ ## name` and `__stop_ ## name` symbols to bracket the section. // This functionality is supported by GNU linker. Any function annotated with // `ABSL_ATTRIBUTE_SECTION` must not be inlined, or it will be placed into // whatever section its caller is placed into. // #ifndef ABSL_ATTRIBUTE_SECTION #define ABSL_ATTRIBUTE_SECTION(name) \ __attribute__((section(#name))) __attribute__((noinline)) #endif // ABSL_ATTRIBUTE_SECTION_VARIABLE // // Tells the compiler/linker to put a given variable into a section and define // `__start_ ## name` and `__stop_ ## name` symbols to bracket the section. // This functionality is supported by GNU linker. #ifndef ABSL_ATTRIBUTE_SECTION_VARIABLE #define ABSL_ATTRIBUTE_SECTION_VARIABLE(name) __attribute__((section(#name))) #endif // ABSL_DECLARE_ATTRIBUTE_SECTION_VARS // // A weak section declaration to be used as a global declaration // for ABSL_ATTRIBUTE_SECTION_START|STOP(name) to compile and link // even without functions with ABSL_ATTRIBUTE_SECTION(name). // ABSL_DEFINE_ATTRIBUTE_SECTION should be in the exactly one file; it's // a no-op on ELF but not on Mach-O. // #ifndef ABSL_DECLARE_ATTRIBUTE_SECTION_VARS #define ABSL_DECLARE_ATTRIBUTE_SECTION_VARS(name) \ extern char __start_##name[] ABSL_ATTRIBUTE_WEAK; \ extern char __stop_##name[] ABSL_ATTRIBUTE_WEAK #endif #ifndef ABSL_DEFINE_ATTRIBUTE_SECTION_VARS #define ABSL_INIT_ATTRIBUTE_SECTION_VARS(name) #define ABSL_DEFINE_ATTRIBUTE_SECTION_VARS(name) #endif // ABSL_ATTRIBUTE_SECTION_START // // Returns `void*` pointers to start/end of a section of code with // functions having ABSL_ATTRIBUTE_SECTION(name). // Returns 0 if no such functions exist. // One must ABSL_DECLARE_ATTRIBUTE_SECTION_VARS(name) for this to compile and // link. // #define ABSL_ATTRIBUTE_SECTION_START(name) \ (reinterpret_cast<void *>(__start_##name)) #define ABSL_ATTRIBUTE_SECTION_STOP(name) \ (reinterpret_cast<void *>(__stop_##name)) #else // !ABSL_HAVE_ATTRIBUTE_SECTION #define ABSL_HAVE_ATTRIBUTE_SECTION 0 // provide dummy definitions #define ABSL_ATTRIBUTE_SECTION(name) #define ABSL_ATTRIBUTE_SECTION_VARIABLE(name) #define ABSL_INIT_ATTRIBUTE_SECTION_VARS(name) #define ABSL_DEFINE_ATTRIBUTE_SECTION_VARS(name) #define ABSL_DECLARE_ATTRIBUTE_SECTION_VARS(name) #define ABSL_ATTRIBUTE_SECTION_START(name) (reinterpret_cast<void *>(0)) #define ABSL_ATTRIBUTE_SECTION_STOP(name) (reinterpret_cast<void *>(0)) #endif // ABSL_ATTRIBUTE_SECTION // ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC // // Support for aligning the stack on 32-bit x86. #if ABSL_HAVE_ATTRIBUTE(force_align_arg_pointer) || \ (defined(__GNUC__) && !defined(__clang__)) #if defined(__i386__) #define ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC \ __attribute__((force_align_arg_pointer)) #define ABSL_REQUIRE_STACK_ALIGN_TRAMPOLINE (0) #elif defined(__x86_64__) #define ABSL_REQUIRE_STACK_ALIGN_TRAMPOLINE (1) #define ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC #else // !__i386__ && !__x86_64 #define ABSL_REQUIRE_STACK_ALIGN_TRAMPOLINE (0) #define ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC #endif // __i386__ #else #define ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC #define ABSL_REQUIRE_STACK_ALIGN_TRAMPOLINE (0) #endif // ABSL_MUST_USE_RESULT // // Tells the compiler to warn about unused return values for functions declared // with this macro. The macro must appear as the very first part of a function // declaration or definition: // // Example: // // ABSL_MUST_USE_RESULT Sprocket* AllocateSprocket(); // // This placement has the broadest compatibility with GCC, Clang, and MSVC, with // both defs and decls, and with GCC-style attributes, MSVC declspec, C++11 // and C++17 attributes. // // ABSL_MUST_USE_RESULT allows using cast-to-void to suppress the unused result // warning. For that, warn_unused_result is used only for clang but not for gcc. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66425 // // Note: past advice was to place the macro after the argument list. #if ABSL_HAVE_ATTRIBUTE(nodiscard) #define ABSL_MUST_USE_RESULT [[nodiscard]] #elif defined(__clang__) && ABSL_HAVE_ATTRIBUTE(warn_unused_result) #define ABSL_MUST_USE_RESULT __attribute__((warn_unused_result)) #else #define ABSL_MUST_USE_RESULT #endif // ABSL_ATTRIBUTE_HOT, ABSL_ATTRIBUTE_COLD // // Tells GCC that a function is hot or cold. GCC can use this information to // improve static analysis, i.e. a conditional branch to a cold function // is likely to be not-taken. // This annotation is used for function declarations. // // Example: // // int foo() ABSL_ATTRIBUTE_HOT; #if ABSL_HAVE_ATTRIBUTE(hot) || (defined(__GNUC__) && !defined(__clang__)) #define ABSL_ATTRIBUTE_HOT __attribute__((hot)) #else #define ABSL_ATTRIBUTE_HOT #endif #if ABSL_HAVE_ATTRIBUTE(cold) || (defined(__GNUC__) && !defined(__clang__)) #define ABSL_ATTRIBUTE_COLD __attribute__((cold)) #else #define ABSL_ATTRIBUTE_COLD #endif // ABSL_XRAY_ALWAYS_INSTRUMENT, ABSL_XRAY_NEVER_INSTRUMENT, ABSL_XRAY_LOG_ARGS // // We define the ABSL_XRAY_ALWAYS_INSTRUMENT and ABSL_XRAY_NEVER_INSTRUMENT // macro used as an attribute to mark functions that must always or never be // instrumented by XRay. Currently, this is only supported in Clang/LLVM. // // For reference on the LLVM XRay instrumentation, see // http://llvm.org/docs/XRay.html. // // A function with the XRAY_ALWAYS_INSTRUMENT macro attribute in its declaration // will always get the XRay instrumentation sleds. These sleds may introduce // some binary size and runtime overhead and must be used sparingly. // // These attributes only take effect when the following conditions are met: // // * The file/target is built in at least C++11 mode, with a Clang compiler // that supports XRay attributes. // * The file/target is built with the -fxray-instrument flag set for the // Clang/LLVM compiler. // * The function is defined in the translation unit (the compiler honors the // attribute in either the definition or the declaration, and must match). // // There are cases when, even when building with XRay instrumentation, users // might want to control specifically which functions are instrumented for a // particular build using special-case lists provided to the compiler. These // special case lists are provided to Clang via the // -fxray-always-instrument=... and -fxray-never-instrument=... flags. The // attributes in source take precedence over these special-case lists. // // To disable the XRay attributes at build-time, users may define // ABSL_NO_XRAY_ATTRIBUTES. Do NOT define ABSL_NO_XRAY_ATTRIBUTES on specific // packages/targets, as this may lead to conflicting definitions of functions at // link-time. // #if ABSL_HAVE_CPP_ATTRIBUTE(clang::xray_always_instrument) && \ !defined(ABSL_NO_XRAY_ATTRIBUTES) #define ABSL_XRAY_ALWAYS_INSTRUMENT [[clang::xray_always_instrument]] #define ABSL_XRAY_NEVER_INSTRUMENT [[clang::xray_never_instrument]] #if ABSL_HAVE_CPP_ATTRIBUTE(clang::xray_log_args) #define ABSL_XRAY_LOG_ARGS(N) \ [[clang::xray_always_instrument, clang::xray_log_args(N)]] #else #define ABSL_XRAY_LOG_ARGS(N) [[clang::xray_always_instrument]] #endif #else #define ABSL_XRAY_ALWAYS_INSTRUMENT #define ABSL_XRAY_NEVER_INSTRUMENT #define ABSL_XRAY_LOG_ARGS(N) #endif // ----------------------------------------------------------------------------- // Variable Attributes // ----------------------------------------------------------------------------- // ABSL_ATTRIBUTE_UNUSED // // Prevents the compiler from complaining about or optimizing away variables // that appear unused. #if ABSL_HAVE_ATTRIBUTE(unused) || (defined(__GNUC__) && !defined(__clang__)) #undef ABSL_ATTRIBUTE_UNUSED #define ABSL_ATTRIBUTE_UNUSED __attribute__((__unused__)) #else #define ABSL_ATTRIBUTE_UNUSED #endif // ABSL_ATTRIBUTE_INITIAL_EXEC // // Tells the compiler to use "initial-exec" mode for a thread-local variable. // See http://people.redhat.com/drepper/tls.pdf for the gory details. #if ABSL_HAVE_ATTRIBUTE(tls_model) || (defined(__GNUC__) && !defined(__clang__)) #define ABSL_ATTRIBUTE_INITIAL_EXEC __attribute__((tls_model("initial-exec"))) #else #define ABSL_ATTRIBUTE_INITIAL_EXEC #endif // ABSL_ATTRIBUTE_PACKED // // Prevents the compiler from padding a structure to natural alignment #if ABSL_HAVE_ATTRIBUTE(packed) || (defined(__GNUC__) && !defined(__clang__)) #define ABSL_ATTRIBUTE_PACKED __attribute__((__packed__)) #else #define ABSL_ATTRIBUTE_PACKED #endif // ABSL_CONST_INIT // // A variable declaration annotated with the `ABSL_CONST_INIT` attribute will // not compile (on supported platforms) unless the variable has a constant // initializer. This is useful for variables with static and thread storage // duration, because it guarantees that they will not suffer from the so-called // "static init order fiasco". // // Example: // // ABSL_CONST_INIT static MyType my_var = MakeMyType(...); // // Note that this attribute is redundant if the variable is declared constexpr. #if ABSL_HAVE_CPP_ATTRIBUTE(clang::require_constant_initialization) // NOLINTNEXTLINE(whitespace/braces) #define ABSL_CONST_INIT [[clang::require_constant_initialization]] #else #define ABSL_CONST_INIT #endif // ABSL_HAVE_CPP_ATTRIBUTE(clang::require_constant_initialization) #endif // ABSL_BASE_ATTRIBUTES_H_ // // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ----------------------------------------------------------------------------- // File: config.h // ----------------------------------------------------------------------------- // // This header file defines a set of macros for checking the presence of // important compiler and platform features. Such macros can be used to // produce portable code by parameterizing compilation based on the presence or // lack of a given feature. // // We define a "feature" as some interface we wish to program to: for example, // a library function or system call. A value of `1` indicates support for // that feature; any other value indicates the feature support is undefined. // // Example: // // Suppose a programmer wants to write a program that uses the 'mmap()' system // call. The Abseil macro for that feature (`ABSL_HAVE_MMAP`) allows you to // selectively include the `mmap.h` header and bracket code using that feature // in the macro: // // // #ifdef ABSL_HAVE_MMAP // #include "sys/mman.h" // #endif //ABSL_HAVE_MMAP // // ... // #ifdef ABSL_HAVE_MMAP // void *ptr = mmap(...); // ... // #endif // ABSL_HAVE_MMAP #ifndef ABSL_BASE_CONFIG_H_ #define ABSL_BASE_CONFIG_H_ // Included for the __GLIBC__ macro (or similar macros on other systems). #include <limits.h> #ifdef __cplusplus // Included for __GLIBCXX__, _LIBCPP_VERSION #include <cstddef> #endif // __cplusplus #if defined(__APPLE__) // Included for TARGET_OS_IPHONE, __IPHONE_OS_VERSION_MIN_REQUIRED, // __IPHONE_8_0. #include <Availability.h> #include <TargetConditionals.h> #endif // ----------------------------------------------------------------------------- // Compiler Feature Checks // ----------------------------------------------------------------------------- // ABSL_HAVE_BUILTIN() // // Checks whether the compiler supports a Clang Feature Checking Macro, and if // so, checks whether it supports the provided builtin function "x" where x // is one of the functions noted in // https://clang.llvm.org/docs/LanguageExtensions.html // // Note: Use this macro to avoid an extra level of #ifdef __has_builtin check. // http://releases.llvm.org/3.3/tools/clang/docs/LanguageExtensions.html #ifdef __has_builtin #define ABSL_HAVE_BUILTIN(x) __has_builtin(x) #else #define ABSL_HAVE_BUILTIN(x) 0 #endif // ABSL_HAVE_TLS is defined to 1 when __thread should be supported. // We assume __thread is supported on Linux when compiled with Clang or compiled // against libstdc++ with _GLIBCXX_HAVE_TLS defined. #ifdef ABSL_HAVE_TLS #error ABSL_HAVE_TLS cannot be directly set #elif defined(__linux__) && (defined(__clang__) || defined(_GLIBCXX_HAVE_TLS)) #define ABSL_HAVE_TLS 1 #endif // There are platforms for which TLS should not be used even though the compiler // makes it seem like it's supported (Android NDK < r12b for example). // This is primarily because of linker problems and toolchain misconfiguration: // Abseil does not intend to support this indefinitely. Currently, the newest // toolchain that we intend to support that requires this behavior is the // r11 NDK - allowing for a 5 year support window on that means this option // is likely to be removed around June of 2021. #if defined(__ANDROID__) && defined(__clang__) #if __has_include(<android/ndk-version.h>) #include <android/ndk-version.h> #endif // TLS isn't supported until NDK r12b per // https://developer.android.com/ndk/downloads/revision_history.html // Since NDK r16, `__NDK_MAJOR__` and `__NDK_MINOR__` are defined in // <android/ndk-version.h>. For NDK < r16, users should define these macros, // e.g. `-D__NDK_MAJOR__=11 -D__NKD_MINOR__=0` for NDK r11. #if defined(__NDK_MAJOR__) && defined(__NDK_MINOR__) && \ ((__NDK_MAJOR__ < 12) || ((__NDK_MAJOR__ == 12) && (__NDK_MINOR__ < 1))) #undef ABSL_HAVE_TLS #endif #endif // defined(__ANDROID__) && defined(__clang__) // ABSL_HAVE_STD_IS_TRIVIALLY_DESTRUCTIBLE // // Checks whether `std::is_trivially_destructible<T>` is supported. // // Notes: All supported compilers using libc++ support this feature, as does // gcc >= 4.8.1 using libstdc++, and Visual Studio. #ifdef ABSL_HAVE_STD_IS_TRIVIALLY_DESTRUCTIBLE #error ABSL_HAVE_STD_IS_TRIVIALLY_DESTRUCTIBLE cannot be directly set #elif defined(_LIBCPP_VERSION) || \ (!defined(__clang__) && defined(__GNUC__) && defined(__GLIBCXX__) && \ (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))) || \ defined(_MSC_VER) #define ABSL_HAVE_STD_IS_TRIVIALLY_DESTRUCTIBLE 1 #endif // ABSL_HAVE_STD_IS_TRIVIALLY_CONSTRUCTIBLE // // Checks whether `std::is_trivially_default_constructible<T>` and // `std::is_trivially_copy_constructible<T>` are supported. // ABSL_HAVE_STD_IS_TRIVIALLY_ASSIGNABLE // // Checks whether `std::is_trivially_copy_assignable<T>` is supported. // Notes: Clang with libc++ supports these features, as does gcc >= 5.1 with // either libc++ or libstdc++, and Visual Studio. #if defined(ABSL_HAVE_STD_IS_TRIVIALLY_CONSTRUCTIBLE) #error ABSL_HAVE_STD_IS_TRIVIALLY_CONSTRUCTIBLE cannot be directly set #elif defined(ABSL_HAVE_STD_IS_TRIVIALLY_ASSIGNABLE) #error ABSL_HAVE_STD_IS_TRIVIALLY_ASSIGNABLE cannot directly set #elif (defined(__clang__) && defined(_LIBCPP_VERSION)) || \ (!defined(__clang__) && defined(__GNUC__) && \ (__GNUC__ > 5 || (__GNUC__ == 5 && __GNUC_MINOR__ >= 1)) && \ (defined(_LIBCPP_VERSION) || defined(__GLIBCXX__))) || \ defined(_MSC_VER) #define ABSL_HAVE_STD_IS_TRIVIALLY_CONSTRUCTIBLE 1 #define ABSL_HAVE_STD_IS_TRIVIALLY_ASSIGNABLE 1 #endif // ABSL_HAVE_THREAD_LOCAL // // Checks whether C++11's `thread_local` storage duration specifier is // supported. #ifdef ABSL_HAVE_THREAD_LOCAL #error ABSL_HAVE_THREAD_LOCAL cannot be directly set #elif !defined(__apple_build_version__) || \ ((__apple_build_version__ >= 8000042) && \ !(TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_9_0)) // Notes: Xcode's clang did not support `thread_local` until version // 8, and even then not for all iOS < 9.0. #define ABSL_HAVE_THREAD_LOCAL 1 #endif // ABSL_HAVE_INTRINSIC_INT128 // // Checks whether the __int128 compiler extension for a 128-bit integral type is // supported. // // Notes: __SIZEOF_INT128__ is defined by Clang and GCC when __int128 is // supported, except on ppc64 and aarch64 where __int128 exists but has exhibits // a sporadic compiler crashing bug. Nvidia's nvcc also defines __GNUC__ and // __SIZEOF_INT128__ but not all versions actually support __int128. #ifdef ABSL_HAVE_INTRINSIC_INT128 #error ABSL_HAVE_INTRINSIC_INT128 cannot be directly set #elif (defined(__clang__) && defined(__SIZEOF_INT128__) && \ !defined(__ppc64__) && !defined(__aarch64__)) || \ (defined(__CUDACC__) && defined(__SIZEOF_INT128__) && \ __CUDACC_VER__ >= 70000) || \ (!defined(__clang__) && !defined(__CUDACC__) && defined(__GNUC__) && \ defined(__SIZEOF_INT128__)) #define ABSL_HAVE_INTRINSIC_INT128 1 #endif // ABSL_HAVE_EXCEPTIONS // // Checks whether the compiler both supports and enables exceptions. Many // compilers support a "no exceptions" mode that disables exceptions. // // Generally, when ABSL_HAVE_EXCEPTIONS is not defined: // // * Code using `throw` and `try` may not compile. // * The `noexcept` specifier will still compile and behave as normal. // * The `noexcept` operator may still return `false`. // // For further details, consult the compiler's documentation. #ifdef ABSL_HAVE_EXCEPTIONS #error ABSL_HAVE_EXCEPTIONS cannot be directly set. #elif defined(__clang__) // TODO(calabrese) // Switch to using __cpp_exceptions when we no longer support versions < 3.6. // For details on this check, see: // http://releases.llvm.org/3.6.0/tools/clang/docs/ReleaseNotes.html#the-exceptions-macro #if defined(__EXCEPTIONS) && __has_feature(cxx_exceptions) #define ABSL_HAVE_EXCEPTIONS 1 #endif // defined(__EXCEPTIONS) && __has_feature(cxx_exceptions) // Handle remaining special cases and default to exceptions being supported. #elif !(defined(__GNUC__) && (__GNUC__ < 5) && !defined(__EXCEPTIONS)) && \ !(defined(__GNUC__) && (__GNUC__ >= 5) && !defined(__cpp_exceptions)) && \ !(defined(_MSC_VER) && !defined(_CPPUNWIND)) #define ABSL_HAVE_EXCEPTIONS 1 #endif // ----------------------------------------------------------------------------- // Platform Feature Checks // ----------------------------------------------------------------------------- // Currently supported operating systems and associated preprocessor // symbols: // // Linux and Linux-derived __linux__ // Android __ANDROID__ (implies __linux__) // Linux (non-Android) __linux__ && !__ANDROID__ // Darwin (Mac OS X and iOS) __APPLE__ // Akaros (http://akaros.org) __ros__ // Windows _WIN32 // NaCL __native_client__ // AsmJS __asmjs__ // Fuschia __Fuchsia__ // // Note that since Android defines both __ANDROID__ and __linux__, one // may probe for either Linux or Android by simply testing for __linux__. // ABSL_HAVE_MMAP // // Checks whether the platform has an mmap(2) implementation as defined in // POSIX.1-2001. #ifdef ABSL_HAVE_MMAP #error ABSL_HAVE_MMAP cannot be directly set #elif defined(__linux__) || defined(__APPLE__) || defined(__ros__) || \ defined(__native_client__) || defined(__asmjs__) || defined(__Fuchsia__) #define ABSL_HAVE_MMAP 1 #endif // ABSL_HAVE_PTHREAD_GETSCHEDPARAM // // Checks whether the platform implements the pthread_(get|set)schedparam(3) // functions as defined in POSIX.1-2001. #ifdef ABSL_HAVE_PTHREAD_GETSCHEDPARAM #error ABSL_HAVE_PTHREAD_GETSCHEDPARAM cannot be directly set #elif defined(__linux__) || defined(__APPLE__) || defined(__ros__) #define ABSL_HAVE_PTHREAD_GETSCHEDPARAM 1 #endif // ABSL_HAVE_SCHED_YIELD // // Checks whether the platform implements sched_yield(2) as defined in // POSIX.1-2001. #ifdef ABSL_HAVE_SCHED_YIELD #error ABSL_HAVE_SCHED_YIELD cannot be directly set #elif defined(__linux__) || defined(__ros__) || defined(__native_client__) #define ABSL_HAVE_SCHED_YIELD 1 #endif // ABSL_HAVE_SEMAPHORE_H // // Checks whether the platform supports the <semaphore.h> header and sem_open(3) // family of functions as standardized in POSIX.1-2001. // // Note: While Apple provides <semaphore.h> for both iOS and macOS, it is // explicitly deprecated and will cause build failures if enabled for those // platforms. We side-step the issue by not defining it here for Apple // platforms. #ifdef ABSL_HAVE_SEMAPHORE_H #error ABSL_HAVE_SEMAPHORE_H cannot be directly set #elif defined(__linux__) || defined(__ros__) #define ABSL_HAVE_SEMAPHORE_H 1 #endif // ABSL_HAVE_ALARM // // Checks whether the platform supports the <signal.h> header and alarm(2) // function as standardized in POSIX.1-2001. #ifdef ABSL_HAVE_ALARM #error ABSL_HAVE_ALARM cannot be directly set #elif defined(__GOOGLE_GRTE_VERSION__) // feature tests for Google's GRTE #define ABSL_HAVE_ALARM 1 #elif defined(__GLIBC__) // feature test for glibc #define ABSL_HAVE_ALARM 1 #elif defined(_MSC_VER) // feature tests for Microsoft's library #elif defined(__native_client__) #else // other standard libraries #define ABSL_HAVE_ALARM 1 #endif // ABSL_IS_LITTLE_ENDIAN // ABSL_IS_BIG_ENDIAN // // Checks the endianness of the platform. // // Notes: uses the built in endian macros provided by GCC (since 4.6) and // Clang (since 3.2); see // https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html. // Otherwise, if _WIN32, assume little endian. Otherwise, bail with an error. #if defined(ABSL_IS_BIG_ENDIAN) #error "ABSL_IS_BIG_ENDIAN cannot be directly set." #endif #if defined(ABSL_IS_LITTLE_ENDIAN) #error "ABSL_IS_LITTLE_ENDIAN cannot be directly set." #endif #if (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \ __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) #define ABSL_IS_LITTLE_ENDIAN 1 #elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && \ __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ #define ABSL_IS_BIG_ENDIAN 1 #elif defined(_WIN32) #define ABSL_IS_LITTLE_ENDIAN 1 #else #error "absl endian detection needs to be set up for your compiler" #endif // ABSL_HAVE_STD_ANY // // Checks whether C++17 std::any is available by checking whether <any> exists. #ifdef ABSL_HAVE_STD_ANY #error "ABSL_HAVE_STD_ANY cannot be directly set." #endif #ifdef __has_include #if __has_include(<any>) && __cplusplus >= 201703L #define ABSL_HAVE_STD_ANY 1 #endif #endif // ABSL_HAVE_STD_OPTIONAL // // Checks whether C++17 std::optional is available. #ifdef ABSL_HAVE_STD_OPTIONAL #error "ABSL_HAVE_STD_OPTIONAL cannot be directly set." #endif #ifdef __has_include #if __has_include(<optional>) && __cplusplus >= 201703L #define ABSL_HAVE_STD_OPTIONAL 1 #endif #endif // ABSL_HAVE_STD_STRING_VIEW // // Checks whether C++17 std::string_view is available. #ifdef ABSL_HAVE_STD_STRING_VIEW #error "ABSL_HAVE_STD_STRING_VIEW cannot be directly set." #endif #ifdef __has_include #if __has_include(<string_view>) && __cplusplus >= 201703L #define ABSL_HAVE_STD_STRING_VIEW 1 #endif #endif #endif // ABSL_BASE_CONFIG_H_ // // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ----------------------------------------------------------------------------- // File: optimization.h // ----------------------------------------------------------------------------- // // This header file defines portable macros for performance optimization. #ifndef ABSL_BASE_OPTIMIZATION_H_ #define ABSL_BASE_OPTIMIZATION_H_ // ABSL_BLOCK_TAIL_CALL_OPTIMIZATION // // Instructs the compiler to avoid optimizing tail-call recursion. Use of this // macro is useful when you wish to preserve the existing function order within // a stack trace for logging, debugging, or profiling purposes. // // Example: // // int f() { // int result = g(); // ABSL_BLOCK_TAIL_CALL_OPTIMIZATION(); // return result; // } #if defined(__pnacl__) #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() if (volatile int x = 0) { (void)x; } #elif defined(__clang__) // Clang will not tail call given inline volatile assembly. #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() __asm__ __volatile__("") #elif defined(__GNUC__) // GCC will not tail call given inline volatile assembly. #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() __asm__ __volatile__("") #elif defined(_MSC_VER) #include <intrin.h> // The __nop() intrinsic blocks the optimisation. #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() __nop() #else #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() if (volatile int x = 0) { (void)x; } #endif // ABSL_CACHELINE_SIZE // // Explicitly defines the size of the L1 cache for purposes of alignment. // Setting the cacheline size allows you to specify that certain objects be // aligned on a cacheline boundary with `ABSL_CACHELINE_ALIGNED` declarations. // (See below.) // // NOTE: this macro should be replaced with the following C++17 features, when // those are generally available: // // * `std::hardware_constructive_interference_size` // * `std::hardware_destructive_interference_size` // // See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0154r1.html // for more information. #if defined(__GNUC__) // Cache line alignment #if defined(__i386__) || defined(__x86_64__) #define ABSL_CACHELINE_SIZE 64 #elif defined(__powerpc64__) #define ABSL_CACHELINE_SIZE 128 #elif defined(__aarch64__) // We would need to read special register ctr_el0 to find out L1 dcache size. // This value is a good estimate based on a real aarch64 machine. #define ABSL_CACHELINE_SIZE 64 #elif defined(__arm__) // Cache line sizes for ARM: These values are not strictly correct since // cache line sizes depend on implementations, not architectures. There // are even implementations with cache line sizes configurable at boot // time. #if defined(__ARM_ARCH_5T__) #define ABSL_CACHELINE_SIZE 32 #elif defined(__ARM_ARCH_7A__) #define ABSL_CACHELINE_SIZE 64 #endif #endif #ifndef ABSL_CACHELINE_SIZE // A reasonable default guess. Note that overestimates tend to waste more // space, while underestimates tend to waste more time. #define ABSL_CACHELINE_SIZE 64 #endif // ABSL_CACHELINE_ALIGNED // // Indicates that the declared object be cache aligned using // `ABSL_CACHELINE_SIZE` (see above). Cacheline aligning objects allows you to // load a set of related objects in the L1 cache for performance improvements. // Cacheline aligning objects properly allows constructive memory sharing and // prevents destructive (or "false") memory sharing. // // NOTE: this macro should be replaced with usage of `alignas()` using // `std::hardware_constructive_interference_size` and/or // `std::hardware_destructive_interference_size` when available within C++17. // // See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0154r1.html // for more information. // // On some compilers, `ABSL_CACHELINE_ALIGNED` expands to // `__attribute__((aligned(ABSL_CACHELINE_SIZE)))`. For compilers where this is // not known to work, the macro expands to nothing. // // No further guarantees are made here. The result of applying the macro // to variables and types is always implementation-defined. // // WARNING: It is easy to use this attribute incorrectly, even to the point // of causing bugs that are difficult to diagnose, crash, etc. It does not // of itself guarantee that objects are aligned to a cache line. // // Recommendations: // // 1) Consult compiler documentation; this comment is not kept in sync as // toolchains evolve. // 2) Verify your use has the intended effect. This often requires inspecting // the generated machine code. // 3) Prefer applying this attribute to individual variables. Avoid // applying it to types. This tends to localize the effect. #define ABSL_CACHELINE_ALIGNED __attribute__((aligned(ABSL_CACHELINE_SIZE))) #else // not GCC #define ABSL_CACHELINE_SIZE 64 #define ABSL_CACHELINE_ALIGNED #endif // ABSL_PREDICT_TRUE, ABSL_PREDICT_FALSE // // Enables the compiler to prioritize compilation using static analysis for // likely paths within a boolean branch. // // Example: // // if (ABSL_PREDICT_TRUE(expression)) { // return result; // Faster if more likely // } else { // return 0; // } // // Compilers can use the information that a certain branch is not likely to be // taken (for instance, a CHECK failure) to optimize for the common case in // the absence of better information (ie. compiling gcc with `-fprofile-arcs`). #if ABSL_HAVE_BUILTIN(__builtin_expect) || \ (defined(__GNUC__) && !defined(__clang__)) #define ABSL_PREDICT_FALSE(x) (__builtin_expect(x, 0)) #define ABSL_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1)) #else #define ABSL_PREDICT_FALSE(x) x #define ABSL_PREDICT_TRUE(x) x #endif #endif // ABSL_BASE_OPTIMIZATION_H_ // // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ----------------------------------------------------------------------------- // File: macros.h // ----------------------------------------------------------------------------- // // This header file defines the set of language macros used within Abseil code. // For the set of macros used to determine supported compilers and platforms, // see absl/base/config.h instead. // // This code is compiled directly on many platforms, including client // platforms like Windows, Mac, and embedded systems. Before making // any changes here, make sure that you're not breaking any platforms. // #ifndef ABSL_BASE_MACROS_H_ #define ABSL_BASE_MACROS_H_ #include <cstddef> // ABSL_ARRAYSIZE() // // Returns the # of elements in an array as a compile-time constant, which can // be used in defining new arrays. If you use this macro on a pointer by // mistake, you will get a compile-time error. // // Note: this template function declaration is used in defining arraysize. // Note that the function doesn't need an implementation, as we only // use its type. namespace absl { namespace macros_internal { template <typename T, size_t N> char (&ArraySizeHelper(T (&array)[N]))[N]; } // namespace macros_internal } // namespace absl #define ABSL_ARRAYSIZE(array) \ (sizeof(::absl::macros_internal::ArraySizeHelper(array))) // kLinkerInitialized // // An enum used only as a constructor argument to indicate that a variable has // static storage duration, and that the constructor should do nothing to its // state. Use of this macro indicates to the reader that it is legal to // declare a static instance of the class, provided the constructor is given // the absl::base_internal::kLinkerInitialized argument. // // Normally, it is unsafe to declare a static variable that has a constructor or // a destructor because invocation order is undefined. However, if the type can // be zero-initialized (which the loader does for static variables) into a valid // state and the type's destructor does not affect storage, then a constructor // for static initialization can be declared. // // Example: // // Declaration // explicit MyClass(absl::base_internal:LinkerInitialized x) {} // // // Invocation // static MyClass my_global(absl::base_internal::kLinkerInitialized); namespace absl { namespace base_internal { enum LinkerInitialized { kLinkerInitialized = 0, }; } // namespace base_internal } // namespace absl // ABSL_FALLTHROUGH_INTENDED // // Annotates implicit fall-through between switch labels, allowing a case to // indicate intentional fallthrough and turn off warnings about any lack of a // `break` statement. The ABSL_FALLTHROUGH_INTENDED macro should be followed by // a semicolon and can be used in most places where `break` can, provided that // no statements exist between it and the next switch label. // // Example: // // switch (x) { // case 40: // case 41: // if (truth_is_out_there) { // ++x; // ABSL_FALLTHROUGH_INTENDED; // Use instead of/along with annotations // // in comments // } else { // return x; // } // case 42: // ... // // Notes: when compiled with clang in C++11 mode, the ABSL_FALLTHROUGH_INTENDED // macro is expanded to the [[clang::fallthrough]] attribute, which is analysed // when performing switch labels fall-through diagnostic // (`-Wimplicit-fallthrough`). See clang documentation on language extensions // for details: // http://clang.llvm.org/docs/AttributeReference.html#fallthrough-clang-fallthrough // // When used with unsupported compilers, the ABSL_FALLTHROUGH_INTENDED macro // has no effect on diagnostics. In any case this macro has no effect on runtime // behavior and performance of code. #ifdef ABSL_FALLTHROUGH_INTENDED #error "ABSL_FALLTHROUGH_INTENDED should not be defined." #endif // TODO(zhangxy): Use c++17 standard [[fallthrough]] macro, when supported. #if defined(__clang__) && defined(__has_warning) #if __has_feature(cxx_attributes) && __has_warning("-Wimplicit-fallthrough") #define ABSL_FALLTHROUGH_INTENDED [[clang::fallthrough]] #endif #elif defined(__GNUC__) && __GNUC__ >= 7 #define ABSL_FALLTHROUGH_INTENDED [[gnu::fallthrough]] #endif #ifndef ABSL_FALLTHROUGH_INTENDED #define ABSL_FALLTHROUGH_INTENDED \ do { \ } while (0) #endif // ABSL_DEPRECATED() // // Marks a deprecated class, struct, enum, function, method and variable // declarations. The macro argument is used as a custom diagnostic message (e.g. // suggestion of a better alternative). // // Example: // // class ABSL_DEPRECATED("Use Bar instead") Foo {...}; // ABSL_DEPRECATED("Use Baz instead") void Bar() {...} // // Every usage of a deprecated entity will trigger a warning when compiled with // clang's `-Wdeprecated-declarations` option. This option is turned off by // default, but the warnings will be reported by clang-tidy. #if defined(__clang__) && __cplusplus >= 201103L && defined(__has_warning) #define ABSL_DEPRECATED(message) __attribute__((deprecated(message))) #endif #ifndef ABSL_DEPRECATED #define ABSL_DEPRECATED(message) #endif // ABSL_BAD_CALL_IF() // // Used on a function overload to trap bad calls: any call that matches the // overload will cause a compile-time error. This macro uses a clang-specific // "enable_if" attribute, as described at // http://clang.llvm.org/docs/AttributeReference.html#enable-if // // Overloads which use this macro should be bracketed by // `#ifdef ABSL_BAD_CALL_IF`. // // Example: // // int isdigit(int c); // #ifdef ABSL_BAD_CALL_IF // int isdigit(int c) // ABSL_BAD_CALL_IF(c <= -1 || c > 255, // "'c' must have the value of an unsigned char or EOF"); // #endif // ABSL_BAD_CALL_IF #if defined(__clang__) # if __has_attribute(enable_if) # define ABSL_BAD_CALL_IF(expr, msg) \ __attribute__((enable_if(expr, "Bad call trap"), unavailable(msg))) # endif #endif // ABSL_ASSERT() // // In C++11, `assert` can't be used portably within constexpr functions. // ABSL_ASSERT functions as a runtime assert but works in C++11 constexpr // functions. Example: // // constexpr double Divide(double a, double b) { // return ABSL_ASSERT(b != 0), a / b; // } // // This macro is inspired by // https://akrzemi1.wordpress.com/2017/05/18/asserts-in-constexpr-functions/ #if defined(NDEBUG) #define ABSL_ASSERT(expr) (false ? (void)(expr) : (void)0) #else #define ABSL_ASSERT(expr) \ (ABSL_PREDICT_TRUE((expr)) ? (void)0 : [] { assert(false && #expr); }()) #endif #endif // ABSL_BASE_MACROS_H_ /* * Copyright 2017 The Abseil Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* This file defines dynamic annotations for use with dynamic analysis tool such as valgrind, PIN, etc. Dynamic annotation is a source code annotation that affects the generated code (that is, the annotation is not a comment). Each such annotation is attached to a particular instruction and/or to a particular object (address) in the program. The annotations that should be used by users are macros in all upper-case (e.g., ANNOTATE_THREAD_NAME). Actual implementation of these macros may differ depending on the dynamic analysis tool being used. This file supports the following configurations: - Dynamic Annotations enabled (with static thread-safety warnings disabled). In this case, macros expand to functions implemented by Thread Sanitizer, when building with TSan. When not provided an external implementation, dynamic_annotations.cc provides no-op implementations. - Static Clang thread-safety warnings enabled. When building with a Clang compiler that supports thread-safety warnings, a subset of annotations can be statically-checked at compile-time. We expand these macros to static-inline functions that can be analyzed for thread-safety, but afterwards elided when building the final binary. - All annotations are disabled. If neither Dynamic Annotations nor Clang thread-safety warnings are enabled, then all annotation-macros expand to empty. */ #ifndef ABSL_BASE_DYNAMIC_ANNOTATIONS_H_ #define ABSL_BASE_DYNAMIC_ANNOTATIONS_H_ #ifndef DYNAMIC_ANNOTATIONS_ENABLED # define DYNAMIC_ANNOTATIONS_ENABLED 0 #endif #if defined(__native_client__) #include "nacl/dynamic_annotations.h" // Stub out the macros missing from the NaCl version. #ifndef ANNOTATE_CONTIGUOUS_CONTAINER #define ANNOTATE_CONTIGUOUS_CONTAINER(beg, end, old_mid, new_mid) #endif #ifndef ANNOTATE_RWLOCK_CREATE_STATIC #define ANNOTATE_RWLOCK_CREATE_STATIC(lock) #endif #ifndef ADDRESS_SANITIZER_REDZONE #define ADDRESS_SANITIZER_REDZONE(name) #endif #ifndef ANNOTATE_MEMORY_IS_UNINITIALIZED #define ANNOTATE_MEMORY_IS_UNINITIALIZED(address, size) #endif #else /* !__native_client__ */ #if DYNAMIC_ANNOTATIONS_ENABLED != 0 /* ------------------------------------------------------------- Annotations that suppress errors. It is usually better to express the program's synchronization using the other annotations, but these can be used when all else fails. */ /* Report that we may have a benign race at "pointer", with size "sizeof(*(pointer))". "pointer" must be a non-void* pointer. Insert at the point where "pointer" has been allocated, preferably close to the point where the race happens. See also ANNOTATE_BENIGN_RACE_STATIC. */ #define ANNOTATE_BENIGN_RACE(pointer, description) \ AnnotateBenignRaceSized(__FILE__, __LINE__, pointer, \ sizeof(*(pointer)), description) /* Same as ANNOTATE_BENIGN_RACE(address, description), but applies to the memory range [address, address+size). */ #define ANNOTATE_BENIGN_RACE_SIZED(address, size, description) \ AnnotateBenignRaceSized(__FILE__, __LINE__, address, size, description) /* Enable (enable!=0) or disable (enable==0) race detection for all threads. This annotation could be useful if you want to skip expensive race analysis during some period of program execution, e.g. during initialization. */ #define ANNOTATE_ENABLE_RACE_DETECTION(enable) \ AnnotateEnableRaceDetection(__FILE__, __LINE__, enable) /* ------------------------------------------------------------- Annotations useful for debugging. */ /* Report the current thread name to a race detector. */ #define ANNOTATE_THREAD_NAME(name) \ AnnotateThreadName(__FILE__, __LINE__, name) /* ------------------------------------------------------------- Annotations useful when implementing locks. They are not normally needed by modules that merely use locks. The "lock" argument is a pointer to the lock object. */ /* Report that a lock has been created at address "lock". */ #define ANNOTATE_RWLOCK_CREATE(lock) \ AnnotateRWLockCreate(__FILE__, __LINE__, lock) /* Report that a linker initialized lock has been created at address "lock". */ #ifdef THREAD_SANITIZER #define ANNOTATE_RWLOCK_CREATE_STATIC(lock) \ AnnotateRWLockCreateStatic(__FILE__, __LINE__, lock) #else #define ANNOTATE_RWLOCK_CREATE_STATIC(lock) ANNOTATE_RWLOCK_CREATE(lock) #endif /* Report that the lock at address "lock" is about to be destroyed. */ #define ANNOTATE_RWLOCK_DESTROY(lock) \ AnnotateRWLockDestroy(__FILE__, __LINE__, lock) /* Report that the lock at address "lock" has been acquired. is_w=1 for writer lock, is_w=0 for reader lock. */ #define ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) \ AnnotateRWLockAcquired(__FILE__, __LINE__, lock, is_w) /* Report that the lock at address "lock" is about to be released. */ #define ANNOTATE_RWLOCK_RELEASED(lock, is_w) \ AnnotateRWLockReleased(__FILE__, __LINE__, lock, is_w) #else /* DYNAMIC_ANNOTATIONS_ENABLED == 0 */ #define ANNOTATE_RWLOCK_CREATE(lock) /* empty */ #define ANNOTATE_RWLOCK_CREATE_STATIC(lock) /* empty */ #define ANNOTATE_RWLOCK_DESTROY(lock) /* empty */ #define ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) /* empty */ #define ANNOTATE_RWLOCK_RELEASED(lock, is_w) /* empty */ #define ANNOTATE_BENIGN_RACE(address, description) /* empty */ #define ANNOTATE_BENIGN_RACE_SIZED(address, size, description) /* empty */ #define ANNOTATE_THREAD_NAME(name) /* empty */ #define ANNOTATE_ENABLE_RACE_DETECTION(enable) /* empty */ #endif /* DYNAMIC_ANNOTATIONS_ENABLED */ /* These annotations are also made available to LLVM's Memory Sanitizer */ #if DYNAMIC_ANNOTATIONS_ENABLED == 1 || defined(MEMORY_SANITIZER) #define ANNOTATE_MEMORY_IS_INITIALIZED(address, size) \ AnnotateMemoryIsInitialized(__FILE__, __LINE__, address, size) #define ANNOTATE_MEMORY_IS_UNINITIALIZED(address, size) \ AnnotateMemoryIsUninitialized(__FILE__, __LINE__, address, size) #else #define ANNOTATE_MEMORY_IS_INITIALIZED(address, size) /* empty */ #define ANNOTATE_MEMORY_IS_UNINITIALIZED(address, size) /* empty */ #endif /* DYNAMIC_ANNOTATIONS_ENABLED || MEMORY_SANITIZER */ /* TODO(delesley) -- Replace __CLANG_SUPPORT_DYN_ANNOTATION__ with the appropriate feature ID. */ #if defined(__clang__) && (!defined(SWIG)) \ && defined(__CLANG_SUPPORT_DYN_ANNOTATION__) #if DYNAMIC_ANNOTATIONS_ENABLED == 0 #define ANNOTALYSIS_ENABLED #endif /* When running in opt-mode, GCC will issue a warning, if these attributes are compiled. Only include them when compiling using Clang. */ #define ATTRIBUTE_IGNORE_READS_BEGIN \ __attribute((exclusive_lock_function("*"))) #define ATTRIBUTE_IGNORE_READS_END \ __attribute((unlock_function("*"))) #else #define ATTRIBUTE_IGNORE_READS_BEGIN /* empty */ #define ATTRIBUTE_IGNORE_READS_END /* empty */ #endif /* defined(__clang__) && ... */ #if (DYNAMIC_ANNOTATIONS_ENABLED != 0) || defined(ANNOTALYSIS_ENABLED) #define ANNOTATIONS_ENABLED #endif #if (DYNAMIC_ANNOTATIONS_ENABLED != 0) /* Request the analysis tool to ignore all reads in the current thread until ANNOTATE_IGNORE_READS_END is called. Useful to ignore intentional racey reads, while still checking other reads and all writes. See also ANNOTATE_UNPROTECTED_READ. */ #define ANNOTATE_IGNORE_READS_BEGIN() \ AnnotateIgnoreReadsBegin(__FILE__, __LINE__) /* Stop ignoring reads. */ #define ANNOTATE_IGNORE_READS_END() \ AnnotateIgnoreReadsEnd(__FILE__, __LINE__) /* Similar to ANNOTATE_IGNORE_READS_BEGIN, but ignore writes instead. */ #define ANNOTATE_IGNORE_WRITES_BEGIN() \ AnnotateIgnoreWritesBegin(__FILE__, __LINE__) /* Stop ignoring writes. */ #define ANNOTATE_IGNORE_WRITES_END() \ AnnotateIgnoreWritesEnd(__FILE__, __LINE__) /* Clang provides limited support for static thread-safety analysis through a feature called Annotalysis. We configure macro-definitions according to whether Annotalysis support is available. */ #elif defined(ANNOTALYSIS_ENABLED) #define ANNOTATE_IGNORE_READS_BEGIN() \ StaticAnnotateIgnoreReadsBegin(__FILE__, __LINE__) #define ANNOTATE_IGNORE_READS_END() \ StaticAnnotateIgnoreReadsEnd(__FILE__, __LINE__) #define ANNOTATE_IGNORE_WRITES_BEGIN() \ StaticAnnotateIgnoreWritesBegin(__FILE__, __LINE__) #define ANNOTATE_IGNORE_WRITES_END() \ StaticAnnotateIgnoreWritesEnd(__FILE__, __LINE__) #else #define ANNOTATE_IGNORE_READS_BEGIN() /* empty */ #define ANNOTATE_IGNORE_READS_END() /* empty */ #define ANNOTATE_IGNORE_WRITES_BEGIN() /* empty */ #define ANNOTATE_IGNORE_WRITES_END() /* empty */ #endif /* Implement the ANNOTATE_IGNORE_READS_AND_WRITES_* annotations using the more primitive annotations defined above. */ #if defined(ANNOTATIONS_ENABLED) /* Start ignoring all memory accesses (both reads and writes). */ #define ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() \ do { \ ANNOTATE_IGNORE_READS_BEGIN(); \ ANNOTATE_IGNORE_WRITES_BEGIN(); \ }while (0) /* Stop ignoring both reads and writes. */ #define ANNOTATE_IGNORE_READS_AND_WRITES_END() \ do { \ ANNOTATE_IGNORE_WRITES_END(); \ ANNOTATE_IGNORE_READS_END(); \ }while (0) #else #define ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() /* empty */ #define ANNOTATE_IGNORE_READS_AND_WRITES_END() /* empty */ #endif /* Use the macros above rather than using these functions directly. */ #include <stddef.h> #ifdef __cplusplus extern "C" { #endif void AnnotateRWLockCreate(const char *file, int line, const volatile void *lock); void AnnotateRWLockCreateStatic(const char *file, int line, const volatile void *lock); void AnnotateRWLockDestroy(const char *file, int line, const volatile void *lock); void AnnotateRWLockAcquired(const char *file, int line, const volatile void *lock, long is_w); /* NOLINT */ void AnnotateRWLockReleased(const char *file, int line, const volatile void *lock, long is_w); /* NOLINT */ void AnnotateBenignRace(const char *file, int line, const volatile void *address, const char *description); void AnnotateBenignRaceSized(const char *file, int line, const volatile void *address, size_t size, const char *description); void AnnotateThreadName(const char *file, int line, const char *name); void AnnotateEnableRaceDetection(const char *file, int line, int enable); void AnnotateMemoryIsInitialized(const char *file, int line, const volatile void *mem, size_t size); void AnnotateMemoryIsUninitialized(const char *file, int line, const volatile void *mem, size_t size); /* Annotations expand to these functions, when Dynamic Annotations are enabled. These functions are either implemented as no-op calls, if no Sanitizer is attached, or provided with externally-linked implementations by a library like ThreadSanitizer. */ void AnnotateIgnoreReadsBegin(const char *file, int line) ATTRIBUTE_IGNORE_READS_BEGIN; void AnnotateIgnoreReadsEnd(const char *file, int line) ATTRIBUTE_IGNORE_READS_END; void AnnotateIgnoreWritesBegin(const char *file, int line); void AnnotateIgnoreWritesEnd(const char *file, int line); #if defined(ANNOTALYSIS_ENABLED) /* When Annotalysis is enabled without Dynamic Annotations, the use of static-inline functions allows the annotations to be read at compile-time, while still letting the compiler elide the functions from the final build. TODO(delesley) -- The exclusive lock here ignores writes as well, but allows IGNORE_READS_AND_WRITES to work properly. */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" static inline void StaticAnnotateIgnoreReadsBegin(const char *file, int line) ATTRIBUTE_IGNORE_READS_BEGIN { (void)file; (void)line; } static inline void StaticAnnotateIgnoreReadsEnd(const char *file, int line) ATTRIBUTE_IGNORE_READS_END { (void)file; (void)line; } static inline void StaticAnnotateIgnoreWritesBegin( const char *file, int line) { (void)file; (void)line; } static inline void StaticAnnotateIgnoreWritesEnd( const char *file, int line) { (void)file; (void)line; } #pragma GCC diagnostic pop #endif /* Return non-zero value if running under valgrind. If "valgrind.h" is included into dynamic_annotations.cc, the regular valgrind mechanism will be used. See http://valgrind.org/docs/manual/manual-core-adv.html about RUNNING_ON_VALGRIND and other valgrind "client requests". The file "valgrind.h" may be obtained by doing svn co svn://svn.valgrind.org/valgrind/trunk/include If for some reason you can't use "valgrind.h" or want to fake valgrind, there are two ways to make this function return non-zero: - Use environment variable: export RUNNING_ON_VALGRIND=1 - Make your tool intercept the function RunningOnValgrind() and change its return value. */ int RunningOnValgrind(void); /* ValgrindSlowdown returns: * 1.0, if (RunningOnValgrind() == 0) * 50.0, if (RunningOnValgrind() != 0 && getenv("VALGRIND_SLOWDOWN") == NULL) * atof(getenv("VALGRIND_SLOWDOWN")) otherwise This function can be used to scale timeout values: EXAMPLE: for (;;) { DoExpensiveBackgroundTask(); SleepForSeconds(5 * ValgrindSlowdown()); } */ double ValgrindSlowdown(void); #ifdef __cplusplus } #endif /* ANNOTATE_UNPROTECTED_READ is the preferred way to annotate racey reads. Instead of doing ANNOTATE_IGNORE_READS_BEGIN(); ... = x; ANNOTATE_IGNORE_READS_END(); one can use ... = ANNOTATE_UNPROTECTED_READ(x); */ #if defined(__cplusplus) && defined(ANNOTATIONS_ENABLED) template <typename T> inline T ANNOTATE_UNPROTECTED_READ(const volatile T &x) { /* NOLINT */ ANNOTATE_IGNORE_READS_BEGIN(); T res = x; ANNOTATE_IGNORE_READS_END(); return res; } #else #define ANNOTATE_UNPROTECTED_READ(x) (x) #endif #if DYNAMIC_ANNOTATIONS_ENABLED != 0 && defined(__cplusplus) /* Apply ANNOTATE_BENIGN_RACE_SIZED to a static variable. */ #define ANNOTATE_BENIGN_RACE_STATIC(static_var, description) \ namespace { \ class static_var ## _annotator { \ public: \ static_var ## _annotator() { \ ANNOTATE_BENIGN_RACE_SIZED(&static_var, \ sizeof(static_var), \ # static_var ": " description); \ } \ }; \ static static_var ## _annotator the ## static_var ## _annotator;\ } // namespace #else /* DYNAMIC_ANNOTATIONS_ENABLED == 0 */ #define ANNOTATE_BENIGN_RACE_STATIC(static_var, description) /* empty */ #endif /* DYNAMIC_ANNOTATIONS_ENABLED */ #ifdef ADDRESS_SANITIZER /* Describe the current state of a contiguous container such as e.g. * std::vector or std::string. For more details see * sanitizer/common_interface_defs.h, which is provided by the compiler. */ #include <sanitizer/common_interface_defs.h> #define ANNOTATE_CONTIGUOUS_CONTAINER(beg, end, old_mid, new_mid) \ __sanitizer_annotate_contiguous_container(beg, end, old_mid, new_mid) #define ADDRESS_SANITIZER_REDZONE(name) \ struct { char x[8] __attribute__ ((aligned (8))); } name #else #define ANNOTATE_CONTIGUOUS_CONTAINER(beg, end, old_mid, new_mid) #define ADDRESS_SANITIZER_REDZONE(name) #endif // ADDRESS_SANITIZER /* Undefine the macros intended only in this file. */ #undef ANNOTALYSIS_ENABLED #undef ANNOTATIONS_ENABLED #undef ATTRIBUTE_IGNORE_READS_BEGIN #undef ATTRIBUTE_IGNORE_READS_END #endif /* !__native_client__ */ #endif /* ABSL_BASE_DYNAMIC_ANNOTATIONS_H_ */ #define ABSL_RAW_CHECK(cond, msg) assert((cond) && (msg)) #define ABSL_RAW_LOG(sev, ...) do {} while(0) // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Produce stack trace. // // There are three different ways we can try to get the stack trace: // // 1) Our hand-coded stack-unwinder. This depends on a certain stack // layout, which is used by gcc (and those systems using a // gcc-compatible ABI) on x86 systems, at least since gcc 2.95. // It uses the frame pointer to do its work. // // 2) The libunwind library. This is still in development, and as a // separate library adds a new dependency, but doesn't need a frame // pointer. It also doesn't call malloc. // // 3) The gdb unwinder -- also the one used by the c++ exception code. // It's obviously well-tested, but has a fatal flaw: it can call // malloc() from the unwinder. This is a problem because we're // trying to use the unwinder to instrument malloc(). // // Note: if you add a new implementation here, make sure it works // correctly when absl::GetStackTrace() is called with max_depth == 0. // Some code may do that. #include <atomic> #if defined(ABSL_STACKTRACE_INL_HEADER) #include ABSL_STACKTRACE_INL_HEADER #else # error Cannot calculate stack trace: will need to write for your environment # include "stacktrace_internal/stacktrace_aarch64-inl.inc" # include "stacktrace_internal/stacktrace_arm-inl.inc" # include "stacktrace_internal/stacktrace_generic-inl.inc" # include "stacktrace_internal/stacktrace_powerpc-inl.inc" # include "stacktrace_internal/stacktrace_unimplemented-inl.inc" # include "stacktrace_internal/stacktrace_win32-inl.inc" # include "stacktrace_internal/stacktrace_x86-inl.inc" #endif namespace absl { namespace { typedef int (*Unwinder)(void**, int*, int, int, const void*, int*); std::atomic<Unwinder> custom; template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT> ABSL_ATTRIBUTE_ALWAYS_INLINE inline int Unwind(void** result, int* sizes, int max_depth, int skip_count, const void* uc, int* min_dropped_frames) { Unwinder f = &UnwindImpl<IS_STACK_FRAMES, IS_WITH_CONTEXT>; Unwinder g = custom.load(std::memory_order_acquire); if (g != nullptr) f = g; // Add 1 to skip count for the unwinder function itself int size = (*f)(result, sizes, max_depth, skip_count + 1, uc, min_dropped_frames); // To disable tail call to (*f)(...) ABSL_BLOCK_TAIL_CALL_OPTIMIZATION(); return size; } } // anonymous namespace int GetStackFrames(void** result, int* sizes, int max_depth, int skip_count) { return Unwind<true, false>(result, sizes, max_depth, skip_count, nullptr, nullptr); } int GetStackFramesWithContext(void** result, int* sizes, int max_depth, int skip_count, const void* uc, int* min_dropped_frames) { return Unwind<true, true>(result, sizes, max_depth, skip_count, uc, min_dropped_frames); } int GetStackTrace(void** result, int max_depth, int skip_count) { return Unwind<false, false>(result, nullptr, max_depth, skip_count, nullptr, nullptr); } int GetStackTraceWithContext(void** result, int max_depth, int skip_count, const void* uc, int* min_dropped_frames) { return Unwind<false, true>(result, nullptr, max_depth, skip_count, uc, min_dropped_frames); } void SetStackUnwinder(Unwinder w) { custom.store(w, std::memory_order_release); } int DefaultStackUnwinder(void** pcs, int* sizes, int depth, int skip, const void* uc, int* min_dropped_frames) { skip++; // For this function Unwinder f = nullptr; if (sizes == nullptr) { if (uc == nullptr) { f = &UnwindImpl<false, false>; } else { f = &UnwindImpl<false, true>; } } else { if (uc == nullptr) { f = &UnwindImpl<true, false>; } else { f = &UnwindImpl<true, true>; } } volatile int x = 0; int n = (*f)(pcs, sizes, depth, skip, uc, min_dropped_frames); x = 1; (void) x; // To disable tail call to (*f)(...) return n; } } // namespace absl // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // base::AddressIsReadable() probes an address to see whether it is readable, // without faulting. #if !defined(__linux__) || defined(__ANDROID__) namespace absl { namespace debug_internal { // On platforms other than Linux, just return true. bool AddressIsReadable(const void* /* addr */) { return true; } } // namespace debug_internal } // namespace absl #else #include <fcntl.h> #include <sys/syscall.h> #include <unistd.h> #include <atomic> #include <cerrno> #include <cstdint> namespace absl { namespace debug_internal { // Pack a pid and two file descriptors into a 64-bit word, // using 16, 24, and 24 bits for each respectively. static uint64_t Pack(uint64_t pid, uint64_t read_fd, uint64_t write_fd) { ABSL_RAW_CHECK((read_fd >> 24) == 0 && (write_fd >> 24) == 0, "fd out of range"); return (pid << 48) | ((read_fd & 0xffffff) << 24) | (write_fd & 0xffffff); } // Unpack x into a pid and two file descriptors, where x was created with // Pack(). static void Unpack(uint64_t x, int *pid, int *read_fd, int *write_fd) { *pid = x >> 48; *read_fd = (x >> 24) & 0xffffff; *write_fd = x & 0xffffff; } // Return whether the byte at *addr is readable, without faulting. // Save and restores errno. Returns true on systems where // unimplemented. // This is a namespace-scoped variable for correct zero-initialization. static std::atomic<uint64_t> pid_and_fds; // initially 0, an invalid pid. bool AddressIsReadable(const void *addr) { int save_errno = errno; // We test whether a byte is readable by using write(). Normally, this would // be done via a cached file descriptor to /dev/null, but linux fails to // check whether the byte is readable when the destination is /dev/null, so // we use a cached pipe. We store the pid of the process that created the // pipe to handle the case where a process forks, and the child closes all // the file descriptors and then calls this routine. This is not perfect: // the child could use the routine, then close all file descriptors and then // use this routine again. But the likely use of this routine is when // crashing, to test the validity of pages when dumping the stack. Beware // that we may leak file descriptors, but we're unlikely to leak many. int bytes_written; int current_pid = getpid() & 0xffff; // we use only the low order 16 bits do { // until we do not get EBADF trying to use file descriptors int pid; int read_fd; int write_fd; uint64_t local_pid_and_fds = pid_and_fds.load(std::memory_order_relaxed); Unpack(local_pid_and_fds, &pid, &read_fd, &write_fd); while (current_pid != pid) { int p[2]; // new pipe if (pipe(p) != 0) { ABSL_RAW_LOG(FATAL, "Failed to create pipe, errno=%d", errno); } fcntl(p[0], F_SETFD, FD_CLOEXEC); fcntl(p[1], F_SETFD, FD_CLOEXEC); uint64_t new_pid_and_fds = Pack(current_pid, p[0], p[1]); if (pid_and_fds.compare_exchange_strong( local_pid_and_fds, new_pid_and_fds, std::memory_order_relaxed, std::memory_order_relaxed)) { local_pid_and_fds = new_pid_and_fds; // fds exposed to other threads } else { // fds not exposed to other threads; we can close them. close(p[0]); close(p[1]); local_pid_and_fds = pid_and_fds.load(std::memory_order_relaxed); } Unpack(local_pid_and_fds, &pid, &read_fd, &write_fd); } errno = 0; // Use syscall(SYS_write, ...) instead of write() to prevent ASAN // and other checkers from complaining about accesses to arbitrary // memory. do { bytes_written = syscall(SYS_write, write_fd, addr, 1); } while (bytes_written == -1 && errno == EINTR); if (bytes_written == 1) { // remove the byte from the pipe char c; while (read(read_fd, &c, 1) == -1 && errno == EINTR) { } } if (errno == EBADF) { // Descriptors invalid. // If pid_and_fds contains the problematic file descriptors we just used, // this call will forget them, and the loop will try again. pid_and_fds.compare_exchange_strong(local_pid_and_fds, 0, std::memory_order_relaxed, std::memory_order_relaxed); } } while (errno == EBADF); errno = save_errno; return bytes_written == 1; } } // namespace debug_internal } // namespace absl #endif // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Allow dynamic symbol lookup in an in-memory Elf image. // #ifdef ABSL_HAVE_ELF_MEM_IMAGE // defined in elf_mem_image.h #include <string.h> #include <cassert> #include <cstddef> // From binutils/include/elf/common.h (this doesn't appear to be documented // anywhere else). // // /* This flag appears in a Versym structure. It means that the symbol // is hidden, and is only visible with an explicit version number. // This is a GNU extension. */ // #define VERSYM_HIDDEN 0x8000 // // /* This is the mask for the rest of the Versym information. */ // #define VERSYM_VERSION 0x7fff #define VERSYM_VERSION 0x7fff namespace absl { namespace debug_internal { namespace { #if __WORDSIZE == 32 const int kElfClass = ELFCLASS32; int ElfBind(const ElfW(Sym) *symbol) { return ELF32_ST_BIND(symbol->st_info); } int ElfType(const ElfW(Sym) *symbol) { return ELF32_ST_TYPE(symbol->st_info); } #elif __WORDSIZE == 64 const int kElfClass = ELFCLASS64; int ElfBind(const ElfW(Sym) *symbol) { return ELF64_ST_BIND(symbol->st_info); } int ElfType(const ElfW(Sym) *symbol) { return ELF64_ST_TYPE(symbol->st_info); } #else const int kElfClass = -1; int ElfBind(const ElfW(Sym) *) { ABSL_RAW_LOG(FATAL, "Unexpected word size"); return 0; } int ElfType(const ElfW(Sym) *) { ABSL_RAW_LOG(FATAL, "Unexpected word size"); return 0; } #endif // Extract an element from one of the ELF tables, cast it to desired type. // This is just a simple arithmetic and a glorified cast. // Callers are responsible for bounds checking. template <typename T> const T *GetTableElement(const ElfW(Ehdr) * ehdr, ElfW(Off) table_offset, ElfW(Word) element_size, size_t index) { return reinterpret_cast<const T*>(reinterpret_cast<const char *>(ehdr) + table_offset + index * element_size); } } // namespace const void *const ElfMemImage::kInvalidBase = reinterpret_cast<const void *>(~0L); ElfMemImage::ElfMemImage(const void *base) { ABSL_RAW_CHECK(base != kInvalidBase, "bad pointer"); Init(base); } int ElfMemImage::GetNumSymbols() const { if (!hash_) { return 0; } // See http://www.caldera.com/developers/gabi/latest/ch5.dynamic.html#hash return hash_[1]; } const ElfW(Sym) *ElfMemImage::GetDynsym(int index) const { ABSL_RAW_CHECK(index < GetNumSymbols(), "index out of range"); return dynsym_ + index; } const ElfW(Versym) *ElfMemImage::GetVersym(int index) const { ABSL_RAW_CHECK(index < GetNumSymbols(), "index out of range"); return versym_ + index; } const ElfW(Phdr) *ElfMemImage::GetPhdr(int index) const { ABSL_RAW_CHECK(index < ehdr_->e_phnum, "index out of range"); return GetTableElement<ElfW(Phdr)>(ehdr_, ehdr_->e_phoff, ehdr_->e_phentsize, index); } const char *ElfMemImage::GetDynstr(ElfW(Word) offset) const { ABSL_RAW_CHECK(offset < strsize_, "offset out of range"); return dynstr_ + offset; } const void *ElfMemImage::GetSymAddr(const ElfW(Sym) *sym) const { if (sym->st_shndx == SHN_UNDEF || sym->st_shndx >= SHN_LORESERVE) { // Symbol corresponds to "special" (e.g. SHN_ABS) section. return reinterpret_cast<const void *>(sym->st_value); } ABSL_RAW_CHECK(link_base_ < sym->st_value, "symbol out of range"); return GetTableElement<char>(ehdr_, 0, 1, sym->st_value) - link_base_; } const ElfW(Verdef) *ElfMemImage::GetVerdef(int index) const { ABSL_RAW_CHECK(0 <= index && static_cast<size_t>(index) <= verdefnum_, "index out of range"); const ElfW(Verdef) *version_definition = verdef_; while (version_definition->vd_ndx < index && version_definition->vd_next) { const char *const version_definition_as_char = reinterpret_cast<const char *>(version_definition); version_definition = reinterpret_cast<const ElfW(Verdef) *>(version_definition_as_char + version_definition->vd_next); } return version_definition->vd_ndx == index ? version_definition : nullptr; } const ElfW(Verdaux) *ElfMemImage::GetVerdefAux( const ElfW(Verdef) *verdef) const { return reinterpret_cast<const ElfW(Verdaux) *>(verdef+1); } const char *ElfMemImage::GetVerstr(ElfW(Word) offset) const { ABSL_RAW_CHECK(offset < strsize_, "offset out of range"); return dynstr_ + offset; } void ElfMemImage::Init(const void *base) { ehdr_ = nullptr; dynsym_ = nullptr; dynstr_ = nullptr; versym_ = nullptr; verdef_ = nullptr; hash_ = nullptr; strsize_ = 0; verdefnum_ = 0; link_base_ = ~0L; // Sentinel: PT_LOAD .p_vaddr can't possibly be this. if (!base) { return; } const intptr_t base_as_uintptr_t = reinterpret_cast<uintptr_t>(base); // Fake VDSO has low bit set. const bool fake_vdso = ((base_as_uintptr_t & 1) != 0); base = reinterpret_cast<const void *>(base_as_uintptr_t & ~1); const char *const base_as_char = reinterpret_cast<const char *>(base); if (base_as_char[EI_MAG0] != ELFMAG0 || base_as_char[EI_MAG1] != ELFMAG1 || base_as_char[EI_MAG2] != ELFMAG2 || base_as_char[EI_MAG3] != ELFMAG3) { assert(false); return; } int elf_class = base_as_char[EI_CLASS]; if (elf_class != kElfClass) { assert(false); return; } switch (base_as_char[EI_DATA]) { case ELFDATA2LSB: { if (__LITTLE_ENDIAN != __BYTE_ORDER) { assert(false); return; } break; } case ELFDATA2MSB: { if (__BIG_ENDIAN != __BYTE_ORDER) { assert(false); return; } break; } default: { assert(false); return; } } ehdr_ = reinterpret_cast<const ElfW(Ehdr) *>(base); const ElfW(Phdr) *dynamic_program_header = nullptr; for (int i = 0; i < ehdr_->e_phnum; ++i) { const ElfW(Phdr) *const program_header = GetPhdr(i); switch (program_header->p_type) { case PT_LOAD: if (!~link_base_) { link_base_ = program_header->p_vaddr; } break; case PT_DYNAMIC: dynamic_program_header = program_header; break; } } if (!~link_base_ || !dynamic_program_header) { assert(false); // Mark this image as not present. Can not recur infinitely. Init(nullptr); return; } ptrdiff_t relocation = base_as_char - reinterpret_cast<const char *>(link_base_); ElfW(Dyn) *dynamic_entry = reinterpret_cast<ElfW(Dyn) *>(dynamic_program_header->p_vaddr + relocation); for (; dynamic_entry->d_tag != DT_NULL; ++dynamic_entry) { ElfW(Xword) value = dynamic_entry->d_un.d_val; if (fake_vdso) { // A complication: in the real VDSO, dynamic entries are not relocated // (it wasn't loaded by a dynamic loader). But when testing with a // "fake" dlopen()ed vdso library, the loader relocates some (but // not all!) of them before we get here. if (dynamic_entry->d_tag == DT_VERDEF) { // The only dynamic entry (of the ones we care about) libc-2.3.6 // loader doesn't relocate. value += relocation; } } else { // Real VDSO. Everything needs to be relocated. value += relocation; } switch (dynamic_entry->d_tag) { case DT_HASH: hash_ = reinterpret_cast<ElfW(Word) *>(value); break; case DT_SYMTAB: dynsym_ = reinterpret_cast<ElfW(Sym) *>(value); break; case DT_STRTAB: dynstr_ = reinterpret_cast<const char *>(value); break; case DT_VERSYM: versym_ = reinterpret_cast<ElfW(Versym) *>(value); break; case DT_VERDEF: verdef_ = reinterpret_cast<ElfW(Verdef) *>(value); break; case DT_VERDEFNUM: verdefnum_ = dynamic_entry->d_un.d_val; break; case DT_STRSZ: strsize_ = dynamic_entry->d_un.d_val; break; default: // Unrecognized entries explicitly ignored. break; } } if (!hash_ || !dynsym_ || !dynstr_ || !versym_ || !verdef_ || !verdefnum_ || !strsize_) { assert(false); // invalid VDSO // Mark this image as not present. Can not recur infinitely. Init(nullptr); return; } } bool ElfMemImage::LookupSymbol(const char *name, const char *version, int type, SymbolInfo *info_out) const { for (const SymbolInfo& info : *this) { if (strcmp(info.name, name) == 0 && strcmp(info.version, version) == 0 && ElfType(info.symbol) == type) { if (info_out) { *info_out = info; } return true; } } return false; } bool ElfMemImage::LookupSymbolByAddress(const void *address, SymbolInfo *info_out) const { for (const SymbolInfo& info : *this) { const char *const symbol_start = reinterpret_cast<const char *>(info.address); const char *const symbol_end = symbol_start + info.symbol->st_size; if (symbol_start <= address && address < symbol_end) { if (info_out) { // Client wants to know details for that symbol (the usual case). if (ElfBind(info.symbol) == STB_GLOBAL) { // Strong symbol; just return it. *info_out = info; return true; } else { // Weak or local. Record it, but keep looking for a strong one. *info_out = info; } } else { // Client only cares if there is an overlapping symbol. return true; } } } return false; } ElfMemImage::SymbolIterator::SymbolIterator(const void *const image, int index) : index_(index), image_(image) { } const ElfMemImage::SymbolInfo *ElfMemImage::SymbolIterator::operator->() const { return &info_; } const ElfMemImage::SymbolInfo& ElfMemImage::SymbolIterator::operator*() const { return info_; } bool ElfMemImage::SymbolIterator::operator==(const SymbolIterator &rhs) const { return this->image_ == rhs.image_ && this->index_ == rhs.index_; } bool ElfMemImage::SymbolIterator::operator!=(const SymbolIterator &rhs) const { return !(*this == rhs); } ElfMemImage::SymbolIterator &ElfMemImage::SymbolIterator::operator++() { this->Update(1); return *this; } ElfMemImage::SymbolIterator ElfMemImage::begin() const { SymbolIterator it(this, 0); it.Update(0); return it; } ElfMemImage::SymbolIterator ElfMemImage::end() const { return SymbolIterator(this, GetNumSymbols()); } void ElfMemImage::SymbolIterator::Update(int increment) { const ElfMemImage *image = reinterpret_cast<const ElfMemImage *>(image_); ABSL_RAW_CHECK(image->IsPresent() || increment == 0, ""); if (!image->IsPresent()) { return; } index_ += increment; if (index_ >= image->GetNumSymbols()) { index_ = image->GetNumSymbols(); return; } const ElfW(Sym) *symbol = image->GetDynsym(index_); const ElfW(Versym) *version_symbol = image->GetVersym(index_); ABSL_RAW_CHECK(symbol && version_symbol, ""); const char *const symbol_name = image->GetDynstr(symbol->st_name); const ElfW(Versym) version_index = version_symbol[0] & VERSYM_VERSION; const ElfW(Verdef) *version_definition = nullptr; const char *version_name = ""; if (symbol->st_shndx == SHN_UNDEF) { // Undefined symbols reference DT_VERNEED, not DT_VERDEF, and // version_index could well be greater than verdefnum_, so calling // GetVerdef(version_index) may trigger assertion. } else { version_definition = image->GetVerdef(version_index); } if (version_definition) { // I am expecting 1 or 2 auxiliary entries: 1 for the version itself, // optional 2nd if the version has a parent. ABSL_RAW_CHECK( version_definition->vd_cnt == 1 || version_definition->vd_cnt == 2, "wrong number of entries"); const ElfW(Verdaux) *version_aux = image->GetVerdefAux(version_definition); version_name = image->GetVerstr(version_aux->vda_name); } info_.name = symbol_name; info_.version = version_name; info_.address = image->GetSymAddr(symbol); info_.symbol = symbol; } } // namespace debug_internal } // namespace absl #endif // ABSL_HAVE_ELF_MEM_IMAGE // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Allow dynamic symbol lookup in the kernel VDSO page. // // VDSOSupport -- a class representing kernel VDSO (if present). #ifdef ABSL_HAVE_VDSO_SUPPORT // defined in vdso_support.h #include <fcntl.h> #include <sys/syscall.h> #include <unistd.h> #ifndef AT_SYSINFO_EHDR #define AT_SYSINFO_EHDR 33 // for crosstoolv10 #endif namespace absl { namespace debug_internal { std::atomic<const void *> VDSOSupport::vdso_base_( debug_internal::ElfMemImage::kInvalidBase); std::atomic<VDSOSupport::GetCpuFn> VDSOSupport::getcpu_fn_(&InitAndGetCPU); VDSOSupport::VDSOSupport() // If vdso_base_ is still set to kInvalidBase, we got here // before VDSOSupport::Init has been called. Call it now. : image_(vdso_base_.load(std::memory_order_relaxed) == debug_internal::ElfMemImage::kInvalidBase ? Init() : vdso_base_.load(std::memory_order_relaxed)) {} // NOTE: we can't use GoogleOnceInit() below, because we can be // called by tcmalloc, and none of the *once* stuff may be functional yet. // // In addition, we hope that the VDSOSupportHelper constructor // causes this code to run before there are any threads, and before // InitGoogle() has executed any chroot or setuid calls. // // Finally, even if there is a race here, it is harmless, because // the operation should be idempotent. const void *VDSOSupport::Init() { if (vdso_base_.load(std::memory_order_relaxed) == debug_internal::ElfMemImage::kInvalidBase) { { // Valgrind zaps AT_SYSINFO_EHDR and friends from the auxv[] // on stack, and so glibc works as if VDSO was not present. // But going directly to kernel via /proc/self/auxv below bypasses // Valgrind zapping. So we check for Valgrind separately. if (RunningOnValgrind()) { vdso_base_.store(nullptr, std::memory_order_relaxed); getcpu_fn_.store(&GetCPUViaSyscall, std::memory_order_relaxed); return nullptr; } int fd = open("/proc/self/auxv", O_RDONLY); if (fd == -1) { // Kernel too old to have a VDSO. vdso_base_.store(nullptr, std::memory_order_relaxed); getcpu_fn_.store(&GetCPUViaSyscall, std::memory_order_relaxed); return nullptr; } ElfW(auxv_t) aux; while (read(fd, &aux, sizeof(aux)) == sizeof(aux)) { if (aux.a_type == AT_SYSINFO_EHDR) { vdso_base_.store(reinterpret_cast<void *>(aux.a_un.a_val), std::memory_order_relaxed); break; } } close(fd); } if (vdso_base_.load(std::memory_order_relaxed) == debug_internal::ElfMemImage::kInvalidBase) { // Didn't find AT_SYSINFO_EHDR in auxv[]. vdso_base_.store(nullptr, std::memory_order_relaxed); } } GetCpuFn fn = &GetCPUViaSyscall; // default if VDSO not present. if (vdso_base_.load(std::memory_order_relaxed)) { VDSOSupport vdso; SymbolInfo info; if (vdso.LookupSymbol("__vdso_getcpu", "LINUX_2.6", STT_FUNC, &info)) { fn = reinterpret_cast<GetCpuFn>(const_cast<void *>(info.address)); } } // Subtle: this code runs outside of any locks; prevent compiler // from assigning to getcpu_fn_ more than once. getcpu_fn_.store(fn, std::memory_order_relaxed); return vdso_base_.load(std::memory_order_relaxed); } const void *VDSOSupport::SetBase(const void *base) { ABSL_RAW_CHECK(base != debug_internal::ElfMemImage::kInvalidBase, "internal error"); const void *old_base = vdso_base_.load(std::memory_order_relaxed); vdso_base_.store(base, std::memory_order_relaxed); image_.Init(base); // Also reset getcpu_fn_, so GetCPU could be tested with simulated VDSO. getcpu_fn_.store(&InitAndGetCPU, std::memory_order_relaxed); return old_base; } bool VDSOSupport::LookupSymbol(const char *name, const char *version, int type, SymbolInfo *info) const { return image_.LookupSymbol(name, version, type, info); } bool VDSOSupport::LookupSymbolByAddress(const void *address, SymbolInfo *info_out) const { return image_.LookupSymbolByAddress(address, info_out); } // NOLINT on 'long' because this routine mimics kernel api. long VDSOSupport::GetCPUViaSyscall(unsigned *cpu, // NOLINT(runtime/int) void *, void *) { #ifdef SYS_getcpu return syscall(SYS_getcpu, cpu, nullptr, nullptr); #else // x86_64 never implemented sys_getcpu(), except as a VDSO call. errno = ENOSYS; return -1; #endif } // Use fast __vdso_getcpu if available. long VDSOSupport::InitAndGetCPU(unsigned *cpu, // NOLINT(runtime/int) void *x, void *y) { Init(); GetCpuFn fn = getcpu_fn_.load(std::memory_order_relaxed); ABSL_RAW_CHECK(fn != &InitAndGetCPU, "Init() did not set getcpu_fn_"); return (*fn)(cpu, x, y); } // This function must be very fast, and may be called from very // low level (e.g. tcmalloc). Hence I avoid things like // GoogleOnceInit() and ::operator new. ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY int GetCPU() { unsigned cpu; int ret_code = (*VDSOSupport::getcpu_fn_)(&cpu, nullptr, nullptr); return ret_code == 0 ? cpu : ret_code; } // We need to make sure VDSOSupport::Init() is called before // InitGoogle() does any setuid or chroot calls. If VDSOSupport // is used in any global constructor, this will happen, since // VDSOSupport's constructor calls Init. But if not, we need to // ensure it here, with a global constructor of our own. This // is an allowed exception to the normal rule against non-trivial // global constructors. static class VDSOInitHelper { public: VDSOInitHelper() { VDSOSupport::Init(); } } vdso_init_helper; } // namespace debug_internal } // namespace absl #endif // ABSL_HAVE_VDSO_SUPPORT // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdlib.h> #include <string.h> #ifndef __has_feature #define __has_feature(x) 0 #endif /* Compiler-based ThreadSanitizer defines DYNAMIC_ANNOTATIONS_EXTERNAL_IMPL = 1 and provides its own definitions of the functions. */ #ifndef DYNAMIC_ANNOTATIONS_EXTERNAL_IMPL # define DYNAMIC_ANNOTATIONS_EXTERNAL_IMPL 0 #endif /* Each function is empty and called (via a macro) only in debug mode. The arguments are captured by dynamic tools at runtime. */ #if DYNAMIC_ANNOTATIONS_EXTERNAL_IMPL == 0 && !defined(__native_client__) #if __has_feature(memory_sanitizer) #include <sanitizer/msan_interface.h> #endif #ifdef __cplusplus extern "C" { #endif void AnnotateRWLockCreate(const char *, int, const volatile void *){} void AnnotateRWLockDestroy(const char *, int, const volatile void *){} void AnnotateRWLockAcquired(const char *, int, const volatile void *, long){} void AnnotateRWLockReleased(const char *, int, const volatile void *, long){} void AnnotateBenignRace(const char *, int, const volatile void *, const char *){} void AnnotateBenignRaceSized(const char *, int, const volatile void *, size_t, const char *) {} void AnnotateThreadName(const char *, int, const char *){} void AnnotateIgnoreReadsBegin(const char *, int){} void AnnotateIgnoreReadsEnd(const char *, int){} void AnnotateIgnoreWritesBegin(const char *, int){} void AnnotateIgnoreWritesEnd(const char *, int){} void AnnotateEnableRaceDetection(const char *, int, int){} void AnnotateMemoryIsInitialized(const char *, int, const volatile void *mem, size_t size) { #if __has_feature(memory_sanitizer) __msan_unpoison(mem, size); #else (void)mem; (void)size; #endif } void AnnotateMemoryIsUninitialized(const char *, int, const volatile void *mem, size_t size) { #if __has_feature(memory_sanitizer) __msan_allocated_memory(mem, size); #else (void)mem; (void)size; #endif } static int GetRunningOnValgrind(void) { #ifdef RUNNING_ON_VALGRIND if (RUNNING_ON_VALGRIND) return 1; #endif char *running_on_valgrind_str = getenv("RUNNING_ON_VALGRIND"); if (running_on_valgrind_str) { return strcmp(running_on_valgrind_str, "0") != 0; } return 0; } /* See the comments in dynamic_annotations.h */ int RunningOnValgrind(void) { static volatile int running_on_valgrind = -1; int local_running_on_valgrind = running_on_valgrind; /* C doesn't have thread-safe initialization of statics, and we don't want to depend on pthread_once here, so hack it. */ ANNOTATE_BENIGN_RACE(&running_on_valgrind, "safe hack"); if (local_running_on_valgrind == -1) running_on_valgrind = local_running_on_valgrind = GetRunningOnValgrind(); return local_running_on_valgrind; } /* See the comments in dynamic_annotations.h */ double ValgrindSlowdown(void) { /* Same initialization hack as in RunningOnValgrind(). */ static volatile double slowdown = 0.0; double local_slowdown = slowdown; ANNOTATE_BENIGN_RACE(&slowdown, "safe hack"); if (RunningOnValgrind() == 0) { return 1.0; } if (local_slowdown == 0.0) { char *env = getenv("VALGRIND_SLOWDOWN"); slowdown = local_slowdown = env ? atof(env) : 50.0; } return local_slowdown; } #ifdef __cplusplus } // extern "C" #endif #endif /* DYNAMIC_ANNOTATIONS_EXTERNAL_IMPL == 0 */
37.357474
91
0.709717
atn34
b4331f2c941c359559c6e89cd72977ca322af596
901
hpp
C++
src/stan/language/ast/node/array_expr.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
src/stan/language/ast/node/array_expr.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
src/stan/language/ast/node/array_expr.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_LANG_AST_NODE_ARRAY_EXPR_HPP #define STAN_LANG_AST_NODE_ARRAY_EXPR_HPP #include "expression.hpp" #include "stan/language/ast/scope.hpp" #include "stan/language/ast/type/bare_expr_type.hpp" #include <cstddef> #include <vector> namespace stan { namespace lang { struct expresssion; /** * Structure to hold an array expression. */ struct array_expr { /** * Sequence of expressions for array values. */ std::vector<expression> args_; /** * Type of array. */ bare_expr_type type_; /** * True if there is a variable within any of the expressions * that is a parameter, transformed parameter, or non-integer * local variable. */ bool has_var_; /** * Scope of this array expression. * */ scope array_expr_scope_; /** * Construct a default array expression. */ array_expr(); }; } // namespace lang } // namespace stan #endif
17.666667
63
0.687014
alashworth
b4342462aa98b494a6652dd589c634e20f9b9b4d
16,530
cpp
C++
libsrc/hyperion/Hyperion.cpp
juanesf/hyperion_openwrt_mt7620
a29624e1ca03c37517b043956b55064b6021c7b4
[ "MIT" ]
null
null
null
libsrc/hyperion/Hyperion.cpp
juanesf/hyperion_openwrt_mt7620
a29624e1ca03c37517b043956b55064b6021c7b4
[ "MIT" ]
null
null
null
libsrc/hyperion/Hyperion.cpp
juanesf/hyperion_openwrt_mt7620
a29624e1ca03c37517b043956b55064b6021c7b4
[ "MIT" ]
null
null
null
#include <cassert> #include "HyperionConfig.h" #include "Poco/RegularExpression.h" #include "Poco/StringTokenizer.h" #include "Poco/Timestamp.h" #include "Poco/Delegate.h" #include "Poco/NumberParser.h" #include "hyperion/Hyperion.h" #include "hyperion/ImageProcessorFactory.h" #include "leddevice/LedDevice.h" #include "leddevice/LedDeviceFactory.h" #include "MultiColorTransform.h" #include "LinearColorSmoothing.h" // effect engine includes #ifdef ENABLE_EFFECT_ENGINE #include "effectengine/EffectEngine.h" #endif ColorOrder Hyperion::createColorOrder(const Poco::DynamicStruct &deviceConfig) { std::string order = deviceConfig["colorOrder"]; if (order == "rgb") { return ORDER_RGB; } else if (order == "bgr") { return ORDER_BGR; } else if (order == "rbg") { return ORDER_RBG; } else if (order == "brg") { return ORDER_BRG; } else if (order == "gbr") { return ORDER_GBR; } else if (order == "grb") { return ORDER_GRB; } else { std::cout << "Unknown color order defined (" << order << "). Using RGB." << std::endl; } return ORDER_RGB; } ColorTransform *Hyperion::createColorTransform(const Poco::DynamicStruct &transformConfig) { std::string id = "default"; id = transformConfig["id"].toString(); RgbChannelTransform *redTransform = createRgbChannelTransform(transformConfig["red"].extract<Poco::DynamicStruct>()); RgbChannelTransform *greenTransform = createRgbChannelTransform(transformConfig["green"].extract<Poco::DynamicStruct>()); RgbChannelTransform *blueTransform = createRgbChannelTransform(transformConfig["blue"].extract<Poco::DynamicStruct>()); HsvTransform *hsvTransform = createHsvTransform(transformConfig["hsv"].extract<Poco::DynamicStruct>()); ColorTransform *transform = new ColorTransform(); transform->_id = id; transform->_rgbRedTransform = *redTransform; transform->_rgbGreenTransform = *greenTransform; transform->_rgbBlueTransform = *blueTransform; transform->_hsvTransform = *hsvTransform; // Cleanup the allocated individual transforms delete redTransform; delete greenTransform; delete blueTransform; delete hsvTransform; return transform; } MultiColorTransform *Hyperion::createLedColorsTransform(const unsigned ledCnt, const Poco::DynamicStruct &colorConfig) { // Create the result, the transforms are added to this MultiColorTransform *transform = new MultiColorTransform(ledCnt); Poco::Dynamic::Var transformConfig = colorConfig["transform"]; if (!transformConfig.isArray()) { ColorTransform *colorTransform = createColorTransform(transformConfig.extract<Poco::DynamicStruct>()); transform->addTransform(colorTransform); transform->setTransformForLed(colorTransform->_id, 0, ledCnt - 1); } else { const Poco::RegularExpression overallExp("([0-9]+(\\-[0-9]+)?)(,[ ]*([0-9]+(\\-[0-9]+)?))*"); for (unsigned i = 0; i < transformConfig.size(); i++) { const Poco::DynamicStruct &config = transformConfig[i].extract<Poco::DynamicStruct>(); ColorTransform *colorTransform = createColorTransform(config); transform->addTransform(colorTransform); const std::string ledIndicesStr = config["leds"].toString(); if (ledIndicesStr.compare("*") == 0) { // Special case for indices '*' => all leds transform->setTransformForLed(colorTransform->_id, 0, ledCnt - 1); std::cout << "ColorTransform '" << colorTransform->_id << "' => [0; " << ledCnt - 1 << "]" << std::endl; continue; } if (!overallExp.match(ledIndicesStr)) { std::cerr << "Given led indices " << i << " not correct format: " << ledIndicesStr << std::endl; continue; } std::cout << "ColorTransform '" << colorTransform->_id << "' => ["; Poco::StringTokenizer ledIndexList(ledIndicesStr, ",", Poco::StringTokenizer::TOK_TRIM); for (unsigned j = 0; j < ledIndexList.count(); ++j) { if (j > 0) { std::cout << ", "; } if (ledIndexList[j].find("-") != std::string::npos) { Poco::StringTokenizer ledIndices(ledIndexList[j], "-", Poco::StringTokenizer::TOK_TRIM); const unsigned startInd = Poco::NumberParser::parseUnsigned(ledIndices[0]); const unsigned endInd = Poco::NumberParser::parseUnsigned(ledIndices[1]); transform->setTransformForLed(colorTransform->_id, startInd, endInd); std::cout << startInd << "-" << endInd; } else { const unsigned index = Poco::NumberParser::parseUnsigned(ledIndexList[j]); transform->setTransformForLed(colorTransform->_id, index, index); std::cout << index; } } std::cout << "]" << std::endl; } } return transform; } HsvTransform *Hyperion::createHsvTransform(const Poco::DynamicStruct &hsvConfig) { double saturationGain, valueGain; saturationGain = hsvConfig["saturationGain"].convert<double>(); valueGain = hsvConfig["valueGain"].convert<double>(); return new HsvTransform(saturationGain, valueGain); } RgbChannelTransform *Hyperion::createRgbChannelTransform(const Poco::DynamicStruct &colorConfig) { double threshold, gamma, blacklevel, whitelevel; threshold = colorConfig["threshold"].convert<double>(); gamma = colorConfig["gamma"].convert<double>(); blacklevel = colorConfig["blacklevel"].convert<double>(); whitelevel = colorConfig["whitelevel"].convert<double>(); RgbChannelTransform *transform = new RgbChannelTransform(threshold, gamma, blacklevel, whitelevel); return transform; } LedString Hyperion::createLedString(const Poco::Dynamic::Var &ledsConfig, const ColorOrder deviceOrder) { LedString ledString; if (!ledsConfig.isArray()) { throw std::runtime_error("leds config is not valid"); } const std::string deviceOrderStr = colorOrderToString(deviceOrder); Poco::DynamicStruct ledConfig; for (unsigned i = 0; i < ledsConfig.size(); i++) { ledConfig = ledsConfig[i].extract<Poco::DynamicStruct>(); Led led; led.index = ledConfig["index"]; const Poco::DynamicStruct &hscanConfig = ledConfig["hscan"].extract<Poco::DynamicStruct>(); const Poco::DynamicStruct &vscanConfig = ledConfig["vscan"].extract<Poco::DynamicStruct>(); led.minX_frac = std::max(0.0, std::min(1.0, hscanConfig["minimum"].extract<double>())); led.maxX_frac = std::max(0.0, std::min(1.0, hscanConfig["maximum"].extract<double>())); led.minY_frac = std::max(0.0, std::min(1.0, vscanConfig["minimum"].extract<double>())); led.maxY_frac = std::max(0.0, std::min(1.0, vscanConfig["maximum"].extract<double>())); // Fix if the user swapped min and max if (led.minX_frac > led.maxX_frac) { std::swap(led.minX_frac, led.maxX_frac); } if (led.minY_frac > led.maxY_frac) { std::swap(led.minY_frac, led.maxY_frac); } // Get the order of the rgb channels for this led (default is device order) std::string ledOrderStr = deviceOrderStr; if (ledConfig.contains("colorOrder")) ledOrderStr = ledConfig["colorOrder"].toString(); led.colorOrder = stringToColorOrder(ledOrderStr); ledString.leds().push_back(led); } // Make sure the leds are sorted (on their indices) std::sort(ledString.leds().begin(), ledString.leds().end(), [](const Led &lhs, const Led &rhs) { return lhs.index < rhs.index; }); return ledString; } LedDevice *Hyperion::createColorSmoothing(const Poco::DynamicStruct &smoothingConfig, LedDevice *ledDevice) { std::string type = smoothingConfig["type"].toString(); std::transform(type.begin(), type.end(), type.begin(), ::tolower); if (type == "none") { std::cout << "Not creating any smoothing" << std::endl; return ledDevice; } else if (type == "linear") { if (!smoothingConfig.contains("time_ms")) { std::cout << "Unable to create smoothing of type linear because of missing parameter 'time_ms'" << std::endl; } else if (!smoothingConfig.contains("updateFrequency")) { std::cout << "Unable to create smoothing of type linear because of missing parameter 'updateFrequency'" << std::endl; } else { unsigned updateDelay = 0; updateDelay = smoothingConfig["updateDelay"].extract<int>(); std::cout << "Creating linear smoothing" << std::endl; return new LinearColorSmoothing(ledDevice, smoothingConfig["updateFrequency"].extract<double>(), smoothingConfig["time_ms"].extract<int>(), updateDelay); } } else { std::cout << "Unable to create smoothing of type " << type << std::endl; } return ledDevice; } Hyperion::Hyperion(const Poco::DynamicStruct &config) : _ledString( createLedString(config["leds"], createColorOrder(config["device"].extract<Poco::DynamicStruct>()))), _muxer(_ledString.count()), _raw2ledTransform( createLedColorsTransform(_ledString.count(), config["color"].extract<Poco::DynamicStruct>())), _device(LedDeviceFactory::construct(config["device"].extract<Poco::DynamicStruct>())), _timer(0, 0), _timerRunning() { if (_device == nullptr) { throw std::runtime_error("[ERROR] LED device could not be created"); } if (!_raw2ledTransform->verifyTransforms()) { throw std::runtime_error("Color transformation incorrectly set"); } // initialize the image processor factory ImageProcessorFactory::getInstance().init( _ledString, config["blackborderdetector"]["enable"].extract<bool>(), // TODO default true config["blackborderdetector"]["threshold"].extract<double>()); // TODO default 0.01 // initialize the color smoothing filter _device = createColorSmoothing(config["color"]["smoothing"].extract<Poco::DynamicStruct>(), _device); #ifdef ENABLE_EFFECT_ENGINE // create the effect engine _effectEngine = new EffectEngine(this, config["effects"].extract<Poco::DynamicStruct>()); #endif stopTimerEvent += Poco::delegate(this, &Hyperion::stopTimer); // initialize the leds update(); } Hyperion::~Hyperion() { // switch off all leds clearall(); _device->switchOff(); stopTimerEvent -= Poco::delegate(this, &Hyperion::stopTimer); #ifdef ENABLE_EFFECT_ENGINE // delete the effect engine delete _effectEngine; #endif // Delete the Led-Device object delete _device; // delete the color transform delete _raw2ledTransform; } unsigned Hyperion::getLedCount() const { return _ledString.count(); } void Hyperion::setColor(int priority, const ColorRgb &color, const int timeout_ms, bool clearEffects) { // create led output std::vector<ColorRgb> ledColors(_ledString.count(), color); // set colors setColors(priority, ledColors, timeout_ms, clearEffects); } void Hyperion::setColors(int priority, const std::vector<ColorRgb> &ledColors, const int timeout_ms, bool clearEffects) { #ifdef ENABLE_EFFECT_ENGINE // clear effects if this call does not come from an effect if (clearEffects) { _effectEngine->clearChannel(priority); } #endif if (timeout_ms > 0) { long timeoutTime = (Poco::Timestamp().epochMicroseconds() / 1000) + timeout_ms; _muxer.setInput(priority, ledColors, timeoutTime); } else { _muxer.setInput(priority, ledColors); } if (priority == _muxer.getCurrentPriority()) { update(); } } const std::vector<std::string> &Hyperion::getTransformIds() const { return _raw2ledTransform->getTransformIds(); } ColorTransform *Hyperion::getTransform(const std::string &id) { return _raw2ledTransform->getTransform(id); } void Hyperion::transformsUpdated() { update(); } void Hyperion::clear(int priority) { if (_muxer.hasPriority(priority)) { _muxer.clearInput(priority); // update leds if necessary if (priority < _muxer.getCurrentPriority()) { update(); } } #ifdef ENABLE_EFFECT_ENGINE // send clear signal to the effect engine // (outside the check so the effect gets cleared even when the effect is not sending colors) _effectEngine->clearChannel(priority); #endif } void Hyperion::clearall() { _muxer.clearAll(); // update leds update(); #ifdef ENABLE_EFFECT_ENGINE // send clearall signal to the effect engine _effectEngine->clearAllChannels(); #endif } std::vector<int> Hyperion::getActivePriorities() const { return _muxer.getPriorities(); } const Hyperion::InputInfo &Hyperion::getPriorityInfo(const int priority) const { return _muxer.getInputInfo(priority); } #ifdef ENABLE_EFFECT_ENGINE const std::list<EffectDefinition> &Hyperion::getEffects() const { return _effectEngine->getEffects(); } int Hyperion::setEffect(const std::string &effectName, int priority, int timeout) { return _effectEngine->runEffect(effectName, priority, timeout); } int Hyperion::setEffect(const std::string &effectName, const Poco::DynamicStruct &args, int priority, int timeout) { return _effectEngine->runEffect(effectName, args, priority, timeout); } #endif void Hyperion::startTimer(long timeout) { _timerRunning++; static Poco::TimerCallback<Hyperion> timerCallback(*this, &Hyperion::onTimer); _timer.setStartInterval(timeout); _timer.start(timerCallback); } void Hyperion::stopTimer() { _timerRunning--; _timer.stop(); update(); } void Hyperion::update() { static Poco::FastMutex mutex; if (!mutex.tryLock()) { return; } // Update the muxer, cleaning obsolete priorities int64_t now = Poco::Timestamp().epochMicroseconds() / 1000; _muxer.setCurrentTime(now); // Obtain the current priority channel int priority = _muxer.getCurrentPriority(); PriorityMuxer::InputInfo priorityInfo = _muxer.getInputInfo(priority); long timeout_ms = priorityInfo.timeoutTime_ms > 0 ? (priorityInfo.timeoutTime_ms - now) : 0; //std::cout << "update() current priorityInfo: " << priorityInfo << " - TO: " << timeout_ms << std::endl; // Apply the transform to each led and color-channel std::vector<ColorRgb> ledColors = _raw2ledTransform->applyTransform(priorityInfo.ledColors); const std::vector<Led> &leds = _ledString.leds(); unsigned long i = 0; for (ColorRgb &color : ledColors) { const ColorOrder ledColorOrder = leds.at(i).colorOrder; // correct the color byte order switch (ledColorOrder) { case ORDER_RGB: // leave as it is break; case ORDER_BGR: std::swap(color.red, color.blue); break; case ORDER_RBG: std::swap(color.green, color.blue); break; case ORDER_GRB: std::swap(color.red, color.green); break; case ORDER_GBR: { uint8_t temp = color.red; color.red = color.green; color.green = color.blue; color.blue = temp; break; } case ORDER_BRG: { uint8_t temp = color.red; color.red = color.blue; color.blue = color.green; color.green = temp; break; } } i++; } // Write the data to the device _device->write(ledColors); // Start the timeout-timer if (timeout_ms > 0) { if (_timerRunning == 0) { startTimer(timeout_ms); } } else if (_timerRunning > 0) { stopTimer(); } mutex.unlock(); } void Hyperion::onTimer(Poco::Timer &timer) { stopTimerEvent.notifyAsync(nullptr); }
34.509395
128
0.631458
juanesf
b434f81bf3017f6b445839273cee1ca131946154
2,389
cpp
C++
aqualectrix/sorter/sortProcess.cpp
aqualectrix/dbpf
5bada102fddc24d9332f4de60c573ed06b722453
[ "Unlicense" ]
null
null
null
aqualectrix/sorter/sortProcess.cpp
aqualectrix/dbpf
5bada102fddc24d9332f4de60c573ed06b722453
[ "Unlicense" ]
null
null
null
aqualectrix/sorter/sortProcess.cpp
aqualectrix/dbpf
5bada102fddc24d9332f4de60c573ed06b722453
[ "Unlicense" ]
null
null
null
/* * sortProcess.cpp : * Changes all sortindexes in the file to the given index. */ #include <iostream> #include <string> #include <vector> #include "../../CatOfEvilGenius/library/DBPF.h" #include "../../CatOfEvilGenius/library/DBPF_types.h" #include "../../CatOfEvilGenius/library/DBPF_BINX.h" using namespace std; extern "C" // for exporting to shared library for use in Python bool sortProcess(const char* filename, const int index) { // extra crunchy goodness for restoring state after outputting in hex format // ios_base::fmtflags f(cout.flags()); // clog << endl << "Sorting " << filename << " into index " << hex << index << "..." << endl; // cout.flags(f); DBPFtype package; vector<DBPF_resourceType*> resources; // Types that should be decompressed and loaded when opening the file. vector<unsigned int> typesToInit; typesToInit.push_back(DBPF_BINX); // Open package file and read/populate chosen (typesToInit) resources. if(!readPackage(filename, package, typesToInit, resources)) { cerr << "Opening and reading from " << filename << " failed. Sorting aborted." << endl; return false; } // Set all sortindices int item_count = resources.size(); DBPF_resourceType* pResource = NULL; for (int i = 0; i < item_count; i++) { pResource = resources[i]; if (NULL == pResource) { continue; } if (DBPF_BINX == pResource->getType()) { if (((DBPF_BINXtype*)pResource)->setSortIndex(index)) { // clog << "\t" << "Set BINX resource " << i << "." << endl; } } } // clog << "Sorting complete!" << endl; // Write back to file // clog << endl << "Overwriting file " << filename << "..." << endl; bool write_success = writeCompressedPackage(filename, package, resources); if (!write_success) { cerr << "Writing to file " << filename << " failed. File may be corrupted... " << "or you may have the file open somewhere else (SimPE, maybe?). " << "If so, close the file elsewhere and try again." << endl; } // else { // clog << "File written!" << endl; // } // Clean up if (!resources.empty()) { size_t vec_size = resources.size(); for (size_t i = 0; i < vec_size; i++) { if (resources[i] != NULL) { delete resources[i]; resources[i] = NULL; } resources.clear(); } } return write_success; }
29.134146
95
0.621599
aqualectrix
b435c30cd63c09357757da03771f8d3f4b4853b6
335
cpp
C++
Codeforces/Translation.cpp
unobatbayar/codingbat
085c86f8f2f043cc020ba0f5fcc364d3f03de9e6
[ "MIT" ]
2
2018-10-28T16:56:20.000Z
2019-05-17T19:13:21.000Z
Codeforces/Translation.cpp
unobatbayar/CodingBat
94044b6150df8ce7a4fbe42a47b168fbf2fede61
[ "MIT" ]
null
null
null
Codeforces/Translation.cpp
unobatbayar/CodingBat
94044b6150df8ce7a4fbe42a47b168fbf2fede61
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; string correct(string s, string t){ int length = s.size(); for(int i = 0; i<length; ++i){ if(s[i] != t[length-1-i]) return "NO"; } return "YES"; } int main() { string s; string t; cin >> s >> t; cout << correct(s, t) << endl; return 0; }
15.952381
46
0.504478
unobatbayar
b435d2d553cf9ec7690bbba01324fb440654998e
6,001
cc
C++
xls/common/logging/log_flags_test.cc
felixzhuologist/xls
b6a4ec7190049002be1c0829d52b1d7767c88204
[ "Apache-2.0" ]
687
2020-08-20T21:24:09.000Z
2022-03-24T11:58:16.000Z
xls/common/logging/log_flags_test.cc
felixzhuologist/xls
b6a4ec7190049002be1c0829d52b1d7767c88204
[ "Apache-2.0" ]
472
2020-08-20T20:59:38.000Z
2022-03-31T15:25:47.000Z
xls/common/logging/log_flags_test.cc
felixzhuologist/xls
b6a4ec7190049002be1c0829d52b1d7767c88204
[ "Apache-2.0" ]
92
2020-08-24T20:32:46.000Z
2022-03-27T21:42:17.000Z
// Copyright 2020 The XLS Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "xls/common/logging/log_flags.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/statusor.h" #include "xls/common/logging/capture_stream.h" #include "xls/common/logging/logging_test_base.h" #include "xls/common/status/matchers.h" #include "xls/common/status/status_macros.h" namespace { using ::testing::HasSubstr; using ::testing::IsEmpty; using ::testing::Not; using ::testing::StartsWith; using xls::status_testing::IsOkAndHolds; template <typename T> class ScopedFlagSetter { public: ScopedFlagSetter(absl::Flag<T>* flag, const T& value) : flag_(flag), original_value_(absl::GetFlag(*flag)) { absl::SetFlag(flag, value); } ~ScopedFlagSetter() { absl::SetFlag(flag_, original_value_); } private: absl::Flag<T>* flag_; T original_value_; }; template <typename T> ScopedFlagSetter(absl::Flag<T>* b, const T& e) -> ScopedFlagSetter<T>; class LogFlagsTest : public ::xls::logging_internal::testing::LoggingTestBase { }; TEST_F(LogFlagsTest, MinloglevelSuppressesLoggingBelowSpecifiedLevel) { auto set_flag = ScopedFlagSetter( &FLAGS_minloglevel, static_cast<int>(absl::LogSeverity::kWarning)); XLS_LOG(INFO) << "test_msg"; EXPECT_THAT(entries_, IsEmpty()); } TEST_F(LogFlagsTest, MinloglevelAllowsLoggingAtSpecifiedLevel) { auto set_flag = ScopedFlagSetter( &FLAGS_minloglevel, static_cast<int>(absl::LogSeverity::kWarning)); XLS_LOG(WARNING) << "test_msg"; auto entry = GetSingleEntry(); EXPECT_THAT(entry.text_message, HasSubstr("test_msg")); } TEST_F(LogFlagsTest, MinloglevelAllowsLoggingAboveSpecifiedLevel) { auto set_flag = ScopedFlagSetter( &FLAGS_minloglevel, static_cast<int>(absl::LogSeverity::kWarning)); XLS_LOG(ERROR) << "test_msg"; auto entry = GetSingleEntry(); EXPECT_THAT(entry.text_message, HasSubstr("test_msg")); } TEST_F(LogFlagsTest, LogToStderrFalseDoesNotCauseInfoLoggingToStderr) { auto set_logtostderr = ScopedFlagSetter(&FLAGS_logtostderr, false); auto set_alsologtostderr = ScopedFlagSetter(&FLAGS_alsologtostderr, false); absl::StatusOr<std::string> output = ::xls::testing::CaptureStream( STDERR_FILENO, [] { XLS_LOG(INFO) << "test_info_log_message"; }); EXPECT_THAT(output, IsOkAndHolds(Not(HasSubstr("test_info_log_message")))); } TEST_F(LogFlagsTest, LogToStderrTrueCausesInfoLoggingToStderr) { auto set_logtostderr = ScopedFlagSetter(&FLAGS_logtostderr, true); auto set_alsologtostderr = ScopedFlagSetter(&FLAGS_alsologtostderr, false); absl::StatusOr<std::string> output = ::xls::testing::CaptureStream( STDERR_FILENO, [] { XLS_LOG(INFO) << "test_info_log_message"; }); EXPECT_THAT(output, IsOkAndHolds(HasSubstr("test_info_log_message"))); } TEST_F(LogFlagsTest, AlsoLogToStderrTrueCausesInfoLoggingToStderr) { auto set_logtostderr = ScopedFlagSetter(&FLAGS_logtostderr, false); auto set_alsologtostderr = ScopedFlagSetter(&FLAGS_alsologtostderr, true); absl::StatusOr<std::string> output = ::xls::testing::CaptureStream( STDERR_FILENO, [] { XLS_LOG(INFO) << "test_info_log_message"; }); EXPECT_THAT(output, IsOkAndHolds(HasSubstr("test_info_log_message"))); } TEST_F(LogFlagsTest, StderrThresholdSuppressesLoggingBelowSpecifiedLevel) { auto set_logtostderr = ScopedFlagSetter(&FLAGS_logtostderr, false); auto set_alsologtostderr = ScopedFlagSetter(&FLAGS_alsologtostderr, false); auto set_stderrthreshold = ScopedFlagSetter( &FLAGS_stderrthreshold, static_cast<int>(absl::LogSeverity::kWarning)); absl::StatusOr<std::string> output = ::xls::testing::CaptureStream( STDERR_FILENO, [] { XLS_LOG(INFO) << "test_info_log_message"; }); EXPECT_THAT(output, IsOkAndHolds(Not(HasSubstr("test_info_log_message")))); } TEST_F(LogFlagsTest, StderrThresholdAllowsLoggingAtSpecifiedLevel) { auto set_flag = ScopedFlagSetter( &FLAGS_stderrthreshold, static_cast<int>(absl::LogSeverity::kWarning)); absl::StatusOr<std::string> output = ::xls::testing::CaptureStream( STDERR_FILENO, [] { XLS_LOG(WARNING) << "test_info_log_message"; }); EXPECT_THAT(output, IsOkAndHolds(HasSubstr("test_info_log_message"))); } TEST_F(LogFlagsTest, StderrThresholdAllowsLoggingAboveSpecifiedLevel) { auto set_flag = ScopedFlagSetter( &FLAGS_stderrthreshold, static_cast<int>(absl::LogSeverity::kWarning)); absl::StatusOr<std::string> output = ::xls::testing::CaptureStream( STDERR_FILENO, [] { XLS_LOG(ERROR) << "test_info_log_message"; }); EXPECT_THAT(output, IsOkAndHolds(HasSubstr("test_info_log_message"))); } TEST_F(LogFlagsTest, EnabledLogPrefixCausesLoggingToBePrefixed) { auto set_flag = ScopedFlagSetter(&FLAGS_log_prefix, true); absl::StatusOr<std::string> output = ::xls::testing::CaptureStream( STDERR_FILENO, [] { XLS_LOG(ERROR) << "test_info_log_message"; }); EXPECT_THAT(output, IsOkAndHolds(HasSubstr("test_info_log_message"))); EXPECT_THAT(output, IsOkAndHolds(StartsWith("E"))); // For ERROR. } TEST_F(LogFlagsTest, DisabledLogPrefixCausesLoggingToNotBePrefixed) { auto set_flag = ScopedFlagSetter(&FLAGS_log_prefix, false); absl::StatusOr<std::string> output = ::xls::testing::CaptureStream( STDERR_FILENO, [] { XLS_LOG(ERROR) << "test_info_log_message"; }); EXPECT_THAT(output, IsOkAndHolds(HasSubstr("test_info_log_message"))); EXPECT_THAT(output, IsOkAndHolds(Not(StartsWith("E")))); // For ERROR. } } // namespace
36.369697
79
0.753374
felixzhuologist
b4379a152395d707a7f5b7d5fe3b1a5ffb55eb91
18,656
cc
C++
chrome/browser/sync_file_system/sync_file_system_service.cc
leiferikb/bitpop-private
4c967307d228e86f07f2576068a169e846c833ca
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-11-15T15:17:43.000Z
2021-11-15T15:17:43.000Z
chrome/browser/sync_file_system/sync_file_system_service.cc
houseoflifeproperty/bitpop-private
4c967307d228e86f07f2576068a169e846c833ca
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/sync_file_system/sync_file_system_service.cc
houseoflifeproperty/bitpop-private
4c967307d228e86f07f2576068a169e846c833ca
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:24:02.000Z
2020-11-04T07:24:02.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync_file_system/sync_file_system_service.h" #include "base/bind.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/stl_util.h" #include "chrome/browser/extensions/api/sync_file_system/extension_sync_event_observer.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_dependency_manager.h" #include "chrome/browser/sync_file_system/drive_file_sync_service.h" #include "chrome/browser/sync_file_system/local_file_sync_service.h" #include "chrome/browser/sync_file_system/sync_event_observer.h" #include "content/public/browser/browser_thread.h" #include "googleurl/src/gurl.h" #include "webkit/fileapi/file_system_context.h" #include "webkit/fileapi/syncable/sync_file_metadata.h" #include "webkit/fileapi/syncable/sync_status_code.h" using content::BrowserThread; using fileapi::ConflictFileInfoCallback; using fileapi::FileSystemURL; using fileapi::SyncFileMetadata; using fileapi::SyncStatusCallback; using fileapi::SyncStatusCode; namespace sync_file_system { namespace { // Run the given join_callback when all the callbacks created by this runner // are run. If any of the callbacks return non-OK state the given join_callback // will be dispatched with the non-OK state that comes first. class SharedCallbackRunner : public base::RefCountedThreadSafe<SharedCallbackRunner> { public: explicit SharedCallbackRunner(const SyncStatusCallback& join_callback) : join_callback_(join_callback), num_shared_callbacks_(0), status_(fileapi::SYNC_STATUS_OK) {} SyncStatusCallback CreateCallback() { ++num_shared_callbacks_; return base::Bind(&SharedCallbackRunner::Done, this); } template <typename R> base::Callback<void(SyncStatusCode, const R& in)> CreateAssignAndRunCallback(R* out) { ++num_shared_callbacks_; return base::Bind(&SharedCallbackRunner::AssignAndRun<R>, this, out); } private: virtual ~SharedCallbackRunner() {} friend class base::RefCountedThreadSafe<SharedCallbackRunner>; template <typename R> void AssignAndRun(R* out, SyncStatusCode status, const R& in) { DCHECK(out); DCHECK_GT(num_shared_callbacks_, 0); if (join_callback_.is_null()) return; *out = in; Done(status); } void Done(SyncStatusCode status) { if (status != fileapi::SYNC_STATUS_OK && status_ == fileapi::SYNC_STATUS_OK) { status_ = status; } if (--num_shared_callbacks_ > 0) return; join_callback_.Run(status_); join_callback_.Reset(); } SyncStatusCallback join_callback_; int num_shared_callbacks_; SyncStatusCode status_; }; void VerifyFileSystemURLSetCallback( base::WeakPtr<SyncFileSystemService> service, const GURL& app_origin, const std::string& service_name, const fileapi::SyncFileSetCallback& callback, fileapi::SyncStatusCode status, const fileapi::FileSystemURLSet& urls) { if (!service.get()) return; #ifndef NDEBUG if (status == fileapi::SYNC_STATUS_OK) { for (fileapi::FileSystemURLSet::const_iterator iter = urls.begin(); iter != urls.end(); ++iter) { DCHECK(iter->origin() == app_origin); DCHECK(iter->filesystem_id() == service_name); } } #endif callback.Run(status, urls); } SyncEventObserver::SyncServiceState RemoteStateToSyncServiceState( RemoteServiceState state) { switch (state) { case REMOTE_SERVICE_OK: return SyncEventObserver::SYNC_SERVICE_RUNNING; case REMOTE_SERVICE_TEMPORARY_UNAVAILABLE: return SyncEventObserver::SYNC_SERVICE_TEMPORARY_UNAVAILABLE; case REMOTE_SERVICE_AUTHENTICATION_REQUIRED: return SyncEventObserver::SYNC_SERVICE_AUTHENTICATION_REQUIRED; case REMOTE_SERVICE_DISABLED: return SyncEventObserver::SYNC_SERVICE_DISABLED; } NOTREACHED(); return SyncEventObserver::SYNC_SERVICE_DISABLED; } } // namespace void SyncFileSystemService::Shutdown() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); local_file_service_->Shutdown(); local_file_service_.reset(); remote_file_service_.reset(); profile_ = NULL; } SyncFileSystemService::~SyncFileSystemService() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!profile_); } void SyncFileSystemService::InitializeForApp( fileapi::FileSystemContext* file_system_context, const std::string& service_name, const GURL& app_origin, const SyncStatusCallback& callback) { DCHECK(local_file_service_); DCHECK(remote_file_service_); DCHECK(app_origin == app_origin.GetOrigin()); DVLOG(1) << "InitializeForApp: " << app_origin.spec(); if (initialized_app_origins_.find(app_origin) != initialized_app_origins_.end()) { DVLOG(1) << "The app is already initialized: " << app_origin.spec(); callback.Run(fileapi::SYNC_STATUS_OK); return; } local_file_service_->MaybeInitializeFileSystemContext( app_origin, service_name, file_system_context, base::Bind(&SyncFileSystemService::DidInitializeFileSystem, AsWeakPtr(), app_origin, callback)); } void SyncFileSystemService::GetConflictFiles( const GURL& app_origin, const std::string& service_name, const fileapi::SyncFileSetCallback& callback) { DCHECK(remote_file_service_); DCHECK(app_origin == app_origin.GetOrigin()); if (!ContainsKey(initialized_app_origins_, app_origin)) { callback.Run(fileapi::SYNC_STATUS_NOT_INITIALIZED, fileapi::FileSystemURLSet()); return; } remote_file_service_->GetConflictFiles( app_origin, base::Bind(&VerifyFileSystemURLSetCallback, AsWeakPtr(), app_origin, service_name, callback)); } void SyncFileSystemService::GetConflictFileInfo( const GURL& app_origin, const std::string& service_name, const FileSystemURL& url, const ConflictFileInfoCallback& callback) { DCHECK(local_file_service_); DCHECK(remote_file_service_); DCHECK(app_origin == app_origin.GetOrigin()); if (!ContainsKey(initialized_app_origins_, app_origin)) { callback.Run(fileapi::SYNC_STATUS_NOT_INITIALIZED, fileapi::ConflictFileInfo()); return; } // Call DidGetConflictFileInfo when both remote and local service's // GetFileMetadata calls are done. SyncFileMetadata* remote_metadata = new SyncFileMetadata; SyncFileMetadata* local_metadata = new SyncFileMetadata; SyncStatusCallback completion_callback = base::Bind(&SyncFileSystemService::DidGetConflictFileInfo, AsWeakPtr(), callback, url, base::Owned(local_metadata), base::Owned(remote_metadata)); scoped_refptr<SharedCallbackRunner> callback_runner( new SharedCallbackRunner(completion_callback)); local_file_service_->GetLocalFileMetadata( url, callback_runner->CreateAssignAndRunCallback(local_metadata)); remote_file_service_->GetRemoteFileMetadata( url, callback_runner->CreateAssignAndRunCallback(remote_metadata)); } void SyncFileSystemService::GetFileSyncStatus( const fileapi::FileSystemURL& url, const fileapi::SyncFileStatusCallback& callback) { DCHECK(local_file_service_); DCHECK(remote_file_service_); if (!ContainsKey(initialized_app_origins_, url.origin())) { base::MessageLoopProxy::current()->PostTask( FROM_HERE, base::Bind(callback, fileapi::SYNC_STATUS_NOT_INITIALIZED, fileapi::SYNC_FILE_STATUS_UNKNOWN)); return; } if (remote_file_service_->IsConflicting(url)) { base::MessageLoopProxy::current()->PostTask( FROM_HERE, base::Bind(callback, fileapi::SYNC_STATUS_OK, fileapi::SYNC_FILE_STATUS_CONFLICTING)); return; } local_file_service_->HasPendingLocalChanges( url, base::Bind(&SyncFileSystemService::DidGetLocalChangeStatus, AsWeakPtr(), callback)); } void SyncFileSystemService::AddSyncEventObserver(SyncEventObserver* observer) { observers_.AddObserver(observer); } void SyncFileSystemService::RemoveSyncEventObserver( SyncEventObserver* observer) { observers_.RemoveObserver(observer); } SyncFileSystemService::SyncFileSystemService(Profile* profile) : profile_(profile), pending_local_changes_(0), pending_remote_changes_(0), local_sync_running_(false), remote_sync_running_(false), is_waiting_remote_sync_enabled_(false), auto_sync_enabled_(true) { } void SyncFileSystemService::Initialize( scoped_ptr<LocalFileSyncService> local_file_service, scoped_ptr<RemoteFileSyncService> remote_file_service) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(local_file_service); DCHECK(remote_file_service); DCHECK(profile_); local_file_service_ = local_file_service.Pass(); remote_file_service_ = remote_file_service.Pass(); local_file_service_->AddChangeObserver(this); remote_file_service_->AddObserver(this); } void SyncFileSystemService::DidGetConflictFileInfo( const ConflictFileInfoCallback& callback, const FileSystemURL& url, const SyncFileMetadata* local_metadata, const SyncFileMetadata* remote_metadata, SyncStatusCode status) { DCHECK(local_metadata); DCHECK(remote_metadata); fileapi::ConflictFileInfo info; info.url = url; info.local_metadata = *local_metadata; info.remote_metadata = *remote_metadata; callback.Run(status, info); } void SyncFileSystemService::DidInitializeFileSystem( const GURL& app_origin, const fileapi::SyncStatusCallback& callback, fileapi::SyncStatusCode status) { DVLOG(1) << "DidInitializeFileSystem: " << app_origin.spec() << " " << status; if (status != fileapi::SYNC_STATUS_OK) { callback.Run(status); return; } // Local side of initialization for the app is done. // Continue on initializing the remote side. remote_file_service_->RegisterOriginForTrackingChanges( app_origin, base::Bind(&SyncFileSystemService::DidRegisterOrigin, AsWeakPtr(), app_origin, callback)); } void SyncFileSystemService::DidRegisterOrigin( const GURL& app_origin, const fileapi::SyncStatusCallback& callback, fileapi::SyncStatusCode status) { DVLOG(1) << "DidRegisterOrigin: " << app_origin.spec() << " " << status; if (status == fileapi::SYNC_STATUS_OK) initialized_app_origins_.insert(app_origin); callback.Run(status); } void SyncFileSystemService::MaybeStartSync() { if (!profile_ || !auto_sync_enabled_) return; DCHECK(local_file_service_); DCHECK(remote_file_service_); MaybeStartRemoteSync(); MaybeStartLocalSync(); } void SyncFileSystemService::MaybeStartRemoteSync() { if (remote_file_service_->GetCurrentState() == REMOTE_SERVICE_DISABLED) return; // See if we cannot / should not start a new remote sync. if (remote_sync_running_ || pending_remote_changes_ == 0) return; // If we have registered a URL for waiting until sync is enabled on a // file (and the registerred URL seems to be still valid) it won't be // worth trying to start another remote sync. if (is_waiting_remote_sync_enabled_) return; DVLOG(1) << "Calling ProcessRemoteChange"; remote_sync_running_ = true; remote_file_service_->ProcessRemoteChange( local_file_service_.get(), base::Bind(&SyncFileSystemService::DidProcessRemoteChange, AsWeakPtr())); } void SyncFileSystemService::MaybeStartLocalSync() { // If the remote service is not ready probably we should not start a // local sync yet. // (We should be still trying a remote sync so the state should become OK // if the remote-side attempt succeeds.) if (remote_file_service_->GetCurrentState() != REMOTE_SERVICE_OK) return; // See if we cannot / should not start a new local sync. if (local_sync_running_ || pending_local_changes_ == 0) return; DVLOG(1) << "Calling ProcessLocalChange"; local_sync_running_ = true; local_file_service_->ProcessLocalChange( remote_file_service_->GetLocalChangeProcessor(), base::Bind(&SyncFileSystemService::DidProcessLocalChange, AsWeakPtr())); } void SyncFileSystemService::DidProcessRemoteChange( fileapi::SyncStatusCode status, const FileSystemURL& url, fileapi::SyncOperationResult result) { DVLOG(1) << "DidProcessRemoteChange: " << " status=" << status << " (" << SyncStatusCodeToString(status) << ")" << " url=" << url.DebugString() << " operation_result=" << result; DCHECK(remote_sync_running_); remote_sync_running_ = false; if (status != fileapi::SYNC_STATUS_NO_CHANGE_TO_SYNC && remote_file_service_->GetCurrentState() != REMOTE_SERVICE_DISABLED) { DCHECK(url.is_valid()); local_file_service_->ClearSyncFlagForURL(url); } if (status == fileapi::SYNC_STATUS_NO_CHANGE_TO_SYNC) { // We seem to have no changes to work on for now. // TODO(kinuko): Might be better setting a timer to call MaybeStartSync. return; } if (status == fileapi::SYNC_STATUS_FILE_BUSY) { is_waiting_remote_sync_enabled_ = true; local_file_service_->RegisterURLForWaitingSync( url, base::Bind(&SyncFileSystemService::OnSyncEnabledForRemoteSync, AsWeakPtr())); return; } if ((status == fileapi::SYNC_STATUS_OK || status == fileapi::SYNC_STATUS_HAS_CONFLICT) && result != fileapi::SYNC_OPERATION_NONE) { // Notify observers of the changes made for a remote sync. FOR_EACH_OBSERVER(SyncEventObserver, observers_, OnFileSynced(url, result)); } base::MessageLoopProxy::current()->PostTask( FROM_HERE, base::Bind(&SyncFileSystemService::MaybeStartSync, AsWeakPtr())); } void SyncFileSystemService::DidProcessLocalChange( fileapi::SyncStatusCode status, const FileSystemURL& url) { DVLOG(1) << "DidProcessLocalChange:" << " status=" << status << " (" << SyncStatusCodeToString(status) << ")" << " url=" << url.DebugString(); DCHECK(local_sync_running_); local_sync_running_ = false; if (status == fileapi::SYNC_STATUS_NO_CHANGE_TO_SYNC) { // We seem to have no changes to work on for now. return; } DCHECK(url.is_valid()); local_file_service_->ClearSyncFlagForURL(url); if (status == fileapi::SYNC_STATUS_HAS_CONFLICT) { FOR_EACH_OBSERVER(SyncEventObserver, observers_, OnFileSynced(url, fileapi::SYNC_OPERATION_CONFLICTED)); } base::MessageLoopProxy::current()->PostTask( FROM_HERE, base::Bind(&SyncFileSystemService::MaybeStartSync, AsWeakPtr())); } void SyncFileSystemService::DidGetLocalChangeStatus( const fileapi::SyncFileStatusCallback& callback, bool has_pending_local_changes) { callback.Run( fileapi::SYNC_STATUS_OK, has_pending_local_changes ? fileapi::SYNC_FILE_STATUS_HAS_PENDING_CHANGES : fileapi::SYNC_FILE_STATUS_SYNCED); } void SyncFileSystemService::OnSyncEnabledForRemoteSync() { is_waiting_remote_sync_enabled_ = false; MaybeStartRemoteSync(); } void SyncFileSystemService::OnLocalChangeAvailable(int64 pending_changes) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK_GE(pending_changes, 0); DVLOG(1) << "OnLocalChangeAvailable: " << pending_changes; pending_local_changes_ = pending_changes; base::MessageLoopProxy::current()->PostTask( FROM_HERE, base::Bind(&SyncFileSystemService::MaybeStartSync, AsWeakPtr())); } void SyncFileSystemService::OnRemoteChangeQueueUpdated(int64 pending_changes) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK_GE(pending_changes, 0); DVLOG(1) << "OnRemoteChangeQueueUpdated: " << pending_changes; pending_remote_changes_ = pending_changes; if (pending_changes > 0) { // The smallest change available might have changed from the previous one. // Reset the is_waiting_remote_sync_enabled_ flag so that we can retry. is_waiting_remote_sync_enabled_ = false; } base::MessageLoopProxy::current()->PostTask( FROM_HERE, base::Bind(&SyncFileSystemService::MaybeStartSync, AsWeakPtr())); } void SyncFileSystemService::OnRemoteServiceStateUpdated( RemoteServiceState state, const std::string& description) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DVLOG(1) << "OnRemoteServiceStateUpdated: " << state << " " << description; if (state == REMOTE_SERVICE_OK) { base::MessageLoopProxy::current()->PostTask( FROM_HERE, base::Bind(&SyncFileSystemService::MaybeStartSync, AsWeakPtr())); } FOR_EACH_OBSERVER( SyncEventObserver, observers_, OnSyncStateUpdated(GURL(), RemoteStateToSyncServiceState(state), description)); } // SyncFileSystemServiceFactory ----------------------------------------------- // static SyncFileSystemService* SyncFileSystemServiceFactory::GetForProfile( Profile* profile) { return static_cast<SyncFileSystemService*>( GetInstance()->GetServiceForProfile(profile, true)); } // static SyncFileSystemServiceFactory* SyncFileSystemServiceFactory::GetInstance() { return Singleton<SyncFileSystemServiceFactory>::get(); } void SyncFileSystemServiceFactory::set_mock_remote_file_service( scoped_ptr<RemoteFileSyncService> mock_remote_service) { mock_remote_file_service_ = mock_remote_service.Pass(); } SyncFileSystemServiceFactory::SyncFileSystemServiceFactory() : ProfileKeyedServiceFactory("SyncFileSystemService", ProfileDependencyManager::GetInstance()) { } SyncFileSystemServiceFactory::~SyncFileSystemServiceFactory() {} ProfileKeyedService* SyncFileSystemServiceFactory::BuildServiceInstanceFor( Profile* profile) const { SyncFileSystemService* service = new SyncFileSystemService(profile); scoped_ptr<LocalFileSyncService> local_file_service( new LocalFileSyncService(profile)); scoped_ptr<RemoteFileSyncService> remote_file_service; if (mock_remote_file_service_) remote_file_service = mock_remote_file_service_.Pass(); else remote_file_service.reset(new DriveFileSyncService(profile)); service->Initialize(local_file_service.Pass(), remote_file_service.Pass()); return service; } } // namespace sync_file_system
34.043796
89
0.726201
leiferikb
b43b621485333f50997dbf39fbaa97849e350bc6
220,487
cpp
C++
src/game/ChatCommands/Level3.cpp
tbayart/mangostwoserver
fc26f650b9f72c1f7376207f9b9d3fdf66387a1e
[ "PostgreSQL", "Zlib", "OpenSSL" ]
null
null
null
src/game/ChatCommands/Level3.cpp
tbayart/mangostwoserver
fc26f650b9f72c1f7376207f9b9d3fdf66387a1e
[ "PostgreSQL", "Zlib", "OpenSSL" ]
null
null
null
src/game/ChatCommands/Level3.cpp
tbayart/mangostwoserver
fc26f650b9f72c1f7376207f9b9d3fdf66387a1e
[ "PostgreSQL", "Zlib", "OpenSSL" ]
null
null
null
/** * MaNGOS is a full featured server for World of Warcraft, supporting * the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8 * * Copyright (C) 2005-2017 MaNGOS project <https://getmangos.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * World of Warcraft, and all World of Warcraft or Warcraft art, images, * and lore are copyrighted by Blizzard Entertainment, Inc. */ #include "Common.h" #include "Database/DatabaseEnv.h" #include "WorldPacket.h" #include "WorldSession.h" #include "World.h" #include "ObjectMgr.h" #include "AccountMgr.h" #include "PlayerDump.h" #include "SpellMgr.h" #include "Player.h" #include "Opcodes.h" #include "GameObject.h" #include "Chat.h" #include "Log.h" #include "Guild.h" #include "GuildMgr.h" #include "ObjectAccessor.h" #include "MapManager.h" #include "MassMailMgr.h" #include "ScriptMgr.h" #include "Language.h" #include "GridNotifiersImpl.h" #include "CellImpl.h" #include "Weather.h" #include "PointMovementGenerator.h" #include "PathFinder.h" #include "TargetedMovementGenerator.h" #include "SkillDiscovery.h" #include "SkillExtraItems.h" #include "SystemConfig.h" #include "Config/Config.h" #include "Mail.h" #include "Util.h" #include "ItemEnchantmentMgr.h" #include "BattleGround/BattleGroundMgr.h" #include "MapPersistentStateMgr.h" #include "InstanceData.h" #include "CreatureEventAIMgr.h" #include "DBCEnums.h" #include "AuctionHouseBot/AuctionHouseBot.h" #include "SQLStorages.h" static uint32 ahbotQualityIds[MAX_AUCTION_QUALITY] = { LANG_AHBOT_QUALITY_GREY, LANG_AHBOT_QUALITY_WHITE, LANG_AHBOT_QUALITY_GREEN, LANG_AHBOT_QUALITY_BLUE, LANG_AHBOT_QUALITY_PURPLE, LANG_AHBOT_QUALITY_ORANGE, LANG_AHBOT_QUALITY_YELLOW }; bool ChatHandler::HandleAHBotItemsAmountCommand(char* args) { uint32 qVals[MAX_AUCTION_QUALITY]; for (int i = 0; i < MAX_AUCTION_QUALITY; ++i) if (!ExtractUInt32(&args, qVals[i])) { return false; } sAuctionBot.SetItemsAmount(qVals); for (int i = 0; i < MAX_AUCTION_QUALITY; ++i) { PSendSysMessage(LANG_AHBOT_ITEMS_AMOUNT, GetMangosString(ahbotQualityIds[i]), sAuctionBotConfig.getConfigItemQualityAmount(AuctionQuality(i))); } return true; } template<int Q> bool ChatHandler::HandleAHBotItemsAmountQualityCommand(char* args) { uint32 qVal; if (!ExtractUInt32(&args, qVal)) { return false; } sAuctionBot.SetItemsAmountForQuality(AuctionQuality(Q), qVal); PSendSysMessage(LANG_AHBOT_ITEMS_AMOUNT, GetMangosString(ahbotQualityIds[Q]), sAuctionBotConfig.getConfigItemQualityAmount(AuctionQuality(Q))); return true; } template bool ChatHandler::HandleAHBotItemsAmountQualityCommand<AUCTION_QUALITY_GREY>(char*); template bool ChatHandler::HandleAHBotItemsAmountQualityCommand<AUCTION_QUALITY_WHITE>(char*); template bool ChatHandler::HandleAHBotItemsAmountQualityCommand<AUCTION_QUALITY_GREEN>(char*); template bool ChatHandler::HandleAHBotItemsAmountQualityCommand<AUCTION_QUALITY_BLUE>(char*); template bool ChatHandler::HandleAHBotItemsAmountQualityCommand<AUCTION_QUALITY_PURPLE>(char*); template bool ChatHandler::HandleAHBotItemsAmountQualityCommand<AUCTION_QUALITY_ORANGE>(char*); template bool ChatHandler::HandleAHBotItemsAmountQualityCommand<AUCTION_QUALITY_YELLOW>(char*); bool ChatHandler::HandleAHBotItemsRatioCommand(char* args) { uint32 rVal[MAX_AUCTION_HOUSE_TYPE]; for (int i = 0; i < MAX_AUCTION_HOUSE_TYPE; ++i) if (!ExtractUInt32(&args, rVal[i])) { return false; } sAuctionBot.SetItemsRatio(rVal[0], rVal[1], rVal[2]); for (int i = 0; i < MAX_AUCTION_HOUSE_TYPE; ++i) { PSendSysMessage(LANG_AHBOT_ITEMS_RATIO, AuctionBotConfig::GetHouseTypeName(AuctionHouseType(i)), sAuctionBotConfig.getConfigItemAmountRatio(AuctionHouseType(i))); } return true; } template<int H> bool ChatHandler::HandleAHBotItemsRatioHouseCommand(char* args) { uint32 rVal; if (!ExtractUInt32(&args, rVal)) { return false; } sAuctionBot.SetItemsRatioForHouse(AuctionHouseType(H), rVal); PSendSysMessage(LANG_AHBOT_ITEMS_RATIO, AuctionBotConfig::GetHouseTypeName(AuctionHouseType(H)), sAuctionBotConfig.getConfigItemAmountRatio(AuctionHouseType(H))); return true; } template bool ChatHandler::HandleAHBotItemsRatioHouseCommand<AUCTION_HOUSE_ALLIANCE>(char*); template bool ChatHandler::HandleAHBotItemsRatioHouseCommand<AUCTION_HOUSE_HORDE>(char*); template bool ChatHandler::HandleAHBotItemsRatioHouseCommand<AUCTION_HOUSE_NEUTRAL>(char*); bool ChatHandler::HandleAHBotRebuildCommand(char* args) { bool all = false; if (*args) { if (!ExtractLiteralArg(&args, "all")) { return false; } all = true; } sAuctionBot.Rebuild(all); return true; } bool ChatHandler::HandleAHBotReloadCommand(char* /*args*/) { if (sAuctionBot.ReloadAllConfig()) { SendSysMessage(LANG_AHBOT_RELOAD_OK); return true; } else { SendSysMessage(LANG_AHBOT_RELOAD_FAIL); SetSentErrorMessage(true); return false; } } bool ChatHandler::HandleAHBotStatusCommand(char* args) { bool all = false; if (*args) { if (!ExtractLiteralArg(&args, "all")) { return false; } all = true; } AuctionHouseBotStatusInfo statusInfo; sAuctionBot.PrepareStatusInfos(statusInfo); if (!m_session) { SendSysMessage(LANG_AHBOT_STATUS_BAR_CONSOLE); SendSysMessage(LANG_AHBOT_STATUS_TITLE1_CONSOLE); SendSysMessage(LANG_AHBOT_STATUS_MIDBAR_CONSOLE); } else { SendSysMessage(LANG_AHBOT_STATUS_TITLE1_CHAT); } uint32 fmtId = m_session ? LANG_AHBOT_STATUS_FORMAT_CHAT : LANG_AHBOT_STATUS_FORMAT_CONSOLE; PSendSysMessage(fmtId, GetMangosString(LANG_AHBOT_STATUS_ITEM_COUNT), statusInfo[AUCTION_HOUSE_ALLIANCE].ItemsCount, statusInfo[AUCTION_HOUSE_HORDE].ItemsCount, statusInfo[AUCTION_HOUSE_NEUTRAL].ItemsCount, statusInfo[AUCTION_HOUSE_ALLIANCE].ItemsCount + statusInfo[AUCTION_HOUSE_HORDE].ItemsCount + statusInfo[AUCTION_HOUSE_NEUTRAL].ItemsCount); if (all) { PSendSysMessage(fmtId, GetMangosString(LANG_AHBOT_STATUS_ITEM_RATIO), sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_ALLIANCE_ITEM_AMOUNT_RATIO), sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_HORDE_ITEM_AMOUNT_RATIO), sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_NEUTRAL_ITEM_AMOUNT_RATIO), sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_ALLIANCE_ITEM_AMOUNT_RATIO) + sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_HORDE_ITEM_AMOUNT_RATIO) + sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_NEUTRAL_ITEM_AMOUNT_RATIO)); if (!m_session) { SendSysMessage(LANG_AHBOT_STATUS_BAR_CONSOLE); SendSysMessage(LANG_AHBOT_STATUS_TITLE2_CONSOLE); SendSysMessage(LANG_AHBOT_STATUS_MIDBAR_CONSOLE); } else { SendSysMessage(LANG_AHBOT_STATUS_TITLE2_CHAT); } for (int i = 0; i < MAX_AUCTION_QUALITY; ++i) PSendSysMessage(fmtId, GetMangosString(ahbotQualityIds[i]), statusInfo[AUCTION_HOUSE_ALLIANCE].QualityInfo[i], statusInfo[AUCTION_HOUSE_HORDE].QualityInfo[i], statusInfo[AUCTION_HOUSE_NEUTRAL].QualityInfo[i], sAuctionBotConfig.getConfigItemQualityAmount(AuctionQuality(i))); } if (!m_session) { SendSysMessage(LANG_AHBOT_STATUS_BAR_CONSOLE); } return true; } // reload commands bool ChatHandler::HandleReloadAllCommand(char* /*args*/) { HandleReloadSkillFishingBaseLevelCommand((char*)""); HandleReloadAllAchievementCommand((char*)""); HandleReloadAllAreaCommand((char*)""); HandleReloadAutoBroadcastCommand((char*)""); HandleReloadAllEventAICommand((char*)""); HandleReloadAllLootCommand((char*)""); HandleReloadAllNpcCommand((char*)""); HandleReloadAllQuestCommand((char*)""); HandleReloadAllSpellCommand((char*)""); HandleReloadAllItemCommand((char*)""); HandleReloadAllGossipsCommand((char*)""); HandleReloadAllLocalesCommand((char*)""); HandleReloadMailLevelRewardCommand((char*)""); HandleReloadCommandCommand((char*)""); HandleReloadReservedNameCommand((char*)""); HandleReloadMangosStringCommand((char*)""); HandleReloadGameTeleCommand((char*)""); return true; } bool ChatHandler::HandleReloadAllAchievementCommand(char* /*args*/) { HandleReloadAchievementCriteriaRequirementCommand((char*)""); HandleReloadAchievementRewardCommand((char*)""); return true; } bool ChatHandler::HandleReloadAllAreaCommand(char* /*args*/) { // HandleReloadQuestAreaTriggersCommand((char*)""); -- reloaded in HandleReloadAllQuestCommand HandleReloadAreaTriggerTeleportCommand((char*)""); HandleReloadAreaTriggerTavernCommand((char*)""); HandleReloadGameGraveyardZoneCommand((char*)""); return true; } bool ChatHandler::HandleReloadAllLootCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables..."); LoadLootTables(); SendGlobalSysMessage("DB tables `*_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadAllNpcCommand(char* args) { if (*args != 'a') // will be reloaded from all_gossips { HandleReloadNpcGossipCommand((char*)"a"); } HandleReloadNpcTrainerCommand((char*)"a"); HandleReloadNpcVendorCommand((char*)"a"); HandleReloadPointsOfInterestCommand((char*)"a"); HandleReloadSpellClickSpellsCommand((char*)"a"); return true; } bool ChatHandler::HandleReloadAllQuestCommand(char* /*args*/) { HandleReloadQuestAreaTriggersCommand((char*)"a"); HandleReloadQuestPOICommand((char*)"a"); HandleReloadQuestTemplateCommand((char*)"a"); sLog.outString("Re-Loading Quests Relations..."); sObjectMgr.LoadQuestRelations(); SendGlobalSysMessage("DB tables `*_questrelation` and `*_involvedrelation` reloaded."); return true; } bool ChatHandler::HandleReloadAllScriptsCommand(char* /*args*/) { if (sScriptMgr.IsScriptScheduled()) { PSendSysMessage("DB scripts used currently, please attempt reload later."); SetSentErrorMessage(true); return false; } sLog.outString("Re-Loading Scripts..."); HandleReloadDBScriptsOnCreatureDeathCommand((char*)"a"); HandleReloadDBScriptsOnGoUseCommand((char*)"a"); HandleReloadDBScriptsOnGossipCommand((char*)"a"); HandleReloadDBScriptsOnEventCommand((char*)"a"); HandleReloadDBScriptsOnQuestEndCommand((char*)"a"); HandleReloadDBScriptsOnQuestStartCommand((char*)"a"); HandleReloadDBScriptsOnSpellCommand((char*)"a"); SendGlobalSysMessage("DB tables `*_scripts` reloaded."); HandleReloadDbScriptStringCommand((char*)"a"); return true; } bool ChatHandler::HandleReloadAllEventAICommand(char* /*args*/) { HandleReloadEventAITextsCommand((char*)"a"); HandleReloadEventAISummonsCommand((char*)"a"); HandleReloadEventAIScriptsCommand((char*)"a"); return true; } bool ChatHandler::HandleReloadAllSpellCommand(char* /*args*/) { HandleReloadSkillDiscoveryTemplateCommand((char*)"a"); HandleReloadSkillExtraItemTemplateCommand((char*)"a"); HandleReloadSpellAreaCommand((char*)"a"); HandleReloadSpellChainCommand((char*)"a"); HandleReloadSpellElixirCommand((char*)"a"); HandleReloadSpellLearnSpellCommand((char*)"a"); HandleReloadSpellProcEventCommand((char*)"a"); HandleReloadSpellBonusesCommand((char*)"a"); HandleReloadSpellProcItemEnchantCommand((char*)"a"); HandleReloadSpellScriptTargetCommand((char*)"a"); HandleReloadSpellTargetPositionCommand((char*)"a"); HandleReloadSpellThreatsCommand((char*)"a"); HandleReloadSpellPetAurasCommand((char*)"a"); return true; } bool ChatHandler::HandleReloadAllGossipsCommand(char* args) { if (*args != 'a') // already reload from all_scripts { HandleReloadDBScriptsOnGossipCommand((char*)"a"); } HandleReloadGossipMenuCommand((char*)"a"); HandleReloadNpcGossipCommand((char*)"a"); HandleReloadPointsOfInterestCommand((char*)"a"); return true; } bool ChatHandler::HandleReloadAllItemCommand(char* /*args*/) { HandleReloadPageTextsCommand((char*)"a"); HandleReloadItemConvertCommand((char*)"a"); HandleReloadItemEnchantementsCommand((char*)"a"); HandleReloadItemRequiredTragetCommand((char*)"a"); return true; } bool ChatHandler::HandleReloadAllLocalesCommand(char* /*args*/) { HandleReloadLocalesAchievementRewardCommand((char*)"a"); HandleReloadLocalesCreatureCommand((char*)"a"); HandleReloadLocalesGameobjectCommand((char*)"a"); HandleReloadLocalesGossipMenuOptionCommand((char*)"a"); HandleReloadLocalesItemCommand((char*)"a"); HandleReloadLocalesNpcTextCommand((char*)"a"); HandleReloadLocalesPageTextCommand((char*)"a"); HandleReloadLocalesPointsOfInterestCommand((char*)"a"); HandleReloadLocalesQuestCommand((char*)"a"); return true; } bool ChatHandler::HandleReloadConfigCommand(char* /*args*/) { sLog.outString("Re-Loading config settings..."); sWorld.LoadConfigSettings(true); sMapMgr.InitializeVisibilityDistanceInfo(); SendGlobalSysMessage("World config settings reloaded."); return true; } bool ChatHandler::HandleReloadAchievementCriteriaRequirementCommand(char* /*args*/) { sLog.outString("Re-Loading Additional Achievement Criteria Requirements Data..."); sAchievementMgr.LoadAchievementCriteriaRequirements(); SendGlobalSysMessage("DB table `achievement_criteria_requirement` reloaded."); return true; } bool ChatHandler::HandleReloadAchievementRewardCommand(char* /*args*/) { sLog.outString("Re-Loading Achievement Reward Data..."); sAchievementMgr.LoadRewards(); SendGlobalSysMessage("DB table `achievement_reward` reloaded."); return true; } bool ChatHandler::HandleReloadAreaTriggerTavernCommand(char* /*args*/) { sLog.outString("Re-Loading Tavern Area Triggers..."); sObjectMgr.LoadTavernAreaTriggers(); SendGlobalSysMessage("DB table `areatrigger_tavern` reloaded."); return true; } bool ChatHandler::HandleReloadAreaTriggerTeleportCommand(char* /*args*/) { sLog.outString("Re-Loading AreaTrigger teleport definitions..."); sObjectMgr.LoadAreaTriggerTeleports(); SendGlobalSysMessage("DB table `areatrigger_teleport` reloaded."); return true; } bool ChatHandler::HandleReloadAutoBroadcastCommand(char* /*args*/) { sLog.outString("Re-Loading broadcast strings..."); sWorld.LoadBroadcastStrings(); SendGlobalSysMessage("Broadcast strings reloaded."); return true; } bool ChatHandler::HandleReloadCommandCommand(char* /*args*/) { load_command_table = true; SendGlobalSysMessage("DB table `command` will be reloaded at next chat command use."); return true; } bool ChatHandler::HandleReloadCreatureQuestRelationsCommand(char* /*args*/) { sLog.outString("Loading Quests Relations... (`creature_questrelation`)"); sObjectMgr.LoadCreatureQuestRelations(); SendGlobalSysMessage("DB table `creature_questrelation` (creature quest givers) reloaded."); return true; } bool ChatHandler::HandleReloadCreatureQuestInvRelationsCommand(char* /*args*/) { sLog.outString("Loading Quests Relations... (`creature_involvedrelation`)"); sObjectMgr.LoadCreatureInvolvedRelations(); SendGlobalSysMessage("DB table `creature_involvedrelation` (creature quest takers) reloaded."); return true; } bool ChatHandler::HandleReloadConditionsCommand(char* /*args*/) { sLog.outString("Re-Loading `conditions`... "); sObjectMgr.LoadConditions(); SendGlobalSysMessage("DB table `conditions` reloaded."); return true; } bool ChatHandler::HandleReloadGossipMenuCommand(char* /*args*/) { sObjectMgr.LoadGossipMenus(); SendGlobalSysMessage("DB tables `gossip_menu` and `gossip_menu_option` reloaded."); return true; } bool ChatHandler::HandleReloadGOQuestRelationsCommand(char* /*args*/) { sLog.outString("Loading Quests Relations... (`gameobject_questrelation`)"); sObjectMgr.LoadGameobjectQuestRelations(); SendGlobalSysMessage("DB table `gameobject_questrelation` (gameobject quest givers) reloaded."); return true; } bool ChatHandler::HandleReloadGOQuestInvRelationsCommand(char* /*args*/) { sLog.outString("Loading Quests Relations... (`gameobject_involvedrelation`)"); sObjectMgr.LoadGameobjectInvolvedRelations(); SendGlobalSysMessage("DB table `gameobject_involvedrelation` (gameobject quest takers) reloaded."); return true; } bool ChatHandler::HandleReloadQuestAreaTriggersCommand(char* /*args*/) { sLog.outString("Re-Loading Quest Area Triggers..."); sObjectMgr.LoadQuestAreaTriggers(); SendGlobalSysMessage("DB table `areatrigger_involvedrelation` (quest area triggers) reloaded."); return true; } bool ChatHandler::HandleReloadQuestTemplateCommand(char* /*args*/) { sLog.outString("Re-Loading Quest Templates..."); sObjectMgr.LoadQuests(); SendGlobalSysMessage("DB table `quest_template` (quest definitions) reloaded."); /// dependent also from `gameobject` but this table not reloaded anyway sLog.outString("Re-Loading GameObjects for quests..."); sObjectMgr.LoadGameObjectForQuests(); SendGlobalSysMessage("Data GameObjects for quests reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesCreatureCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`creature_loot_template`)"); LoadLootTemplates_Creature(); LootTemplates_Creature.CheckLootRefs(); SendGlobalSysMessage("DB table `creature_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesDisenchantCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`disenchant_loot_template`)"); LoadLootTemplates_Disenchant(); LootTemplates_Disenchant.CheckLootRefs(); SendGlobalSysMessage("DB table `disenchant_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesFishingCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`fishing_loot_template`)"); LoadLootTemplates_Fishing(); LootTemplates_Fishing.CheckLootRefs(); SendGlobalSysMessage("DB table `fishing_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesGameobjectCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`gameobject_loot_template`)"); LoadLootTemplates_Gameobject(); LootTemplates_Gameobject.CheckLootRefs(); SendGlobalSysMessage("DB table `gameobject_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesItemCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`item_loot_template`)"); LoadLootTemplates_Item(); LootTemplates_Item.CheckLootRefs(); SendGlobalSysMessage("DB table `item_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesMillingCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`milling_loot_template`)"); LoadLootTemplates_Milling(); LootTemplates_Milling.CheckLootRefs(); SendGlobalSysMessage("DB table `milling_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesPickpocketingCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`pickpocketing_loot_template`)"); LoadLootTemplates_Pickpocketing(); LootTemplates_Pickpocketing.CheckLootRefs(); SendGlobalSysMessage("DB table `pickpocketing_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesProspectingCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`prospecting_loot_template`)"); LoadLootTemplates_Prospecting(); LootTemplates_Prospecting.CheckLootRefs(); SendGlobalSysMessage("DB table `prospecting_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesMailCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`mail_loot_template`)"); LoadLootTemplates_Mail(); LootTemplates_Mail.CheckLootRefs(); SendGlobalSysMessage("DB table `mail_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesReferenceCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`reference_loot_template`)"); LoadLootTemplates_Reference(); SendGlobalSysMessage("DB table `reference_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesSkinningCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`skinning_loot_template`)"); LoadLootTemplates_Skinning(); LootTemplates_Skinning.CheckLootRefs(); SendGlobalSysMessage("DB table `skinning_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesSpellCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`spell_loot_template`)"); LoadLootTemplates_Spell(); LootTemplates_Spell.CheckLootRefs(); SendGlobalSysMessage("DB table `spell_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadMangosStringCommand(char* /*args*/) { sLog.outString("Re-Loading mangos_string Table!"); sObjectMgr.LoadMangosStrings(); SendGlobalSysMessage("DB table `mangos_string` reloaded."); return true; } bool ChatHandler::HandleReloadNpcGossipCommand(char* /*args*/) { sLog.outString("Re-Loading `npc_gossip` Table!"); sObjectMgr.LoadNpcGossips(); SendGlobalSysMessage("DB table `npc_gossip` reloaded."); return true; } bool ChatHandler::HandleReloadNpcTextCommand(char* /*args*/) { sLog.outString("Re-Loading `npc_text` Table!"); sObjectMgr.LoadGossipText(); SendGlobalSysMessage("DB table `npc_text` reloaded."); return true; } bool ChatHandler::HandleReloadNpcTrainerCommand(char* /*args*/) { sLog.outString("Re-Loading `npc_trainer_template` Table!"); sObjectMgr.LoadTrainerTemplates(); SendGlobalSysMessage("DB table `npc_trainer_template` reloaded."); sLog.outString("Re-Loading `npc_trainer` Table!"); sObjectMgr.LoadTrainers(); SendGlobalSysMessage("DB table `npc_trainer` reloaded."); return true; } bool ChatHandler::HandleReloadNpcVendorCommand(char* /*args*/) { // not safe reload vendor template tables independent... sLog.outString("Re-Loading `npc_vendor_template` Table!"); sObjectMgr.LoadVendorTemplates(); SendGlobalSysMessage("DB table `npc_vendor_template` reloaded."); sLog.outString("Re-Loading `npc_vendor` Table!"); sObjectMgr.LoadVendors(); SendGlobalSysMessage("DB table `npc_vendor` reloaded."); return true; } bool ChatHandler::HandleReloadPointsOfInterestCommand(char* /*args*/) { sLog.outString("Re-Loading `points_of_interest` Table!"); sObjectMgr.LoadPointsOfInterest(); SendGlobalSysMessage("DB table `points_of_interest` reloaded."); return true; } bool ChatHandler::HandleReloadQuestPOICommand(char* /*args*/) { sLog.outString("Re-Loading `quest_poi` and `quest_poi_points` Tables!"); sObjectMgr.LoadQuestPOI(); SendGlobalSysMessage("DB Table `quest_poi` and `quest_poi_points` reloaded."); return true; } bool ChatHandler::HandleReloadSpellClickSpellsCommand(char* /*args*/) { sLog.outString("Re-Loading `npc_spellclick_spells` Table!"); sObjectMgr.LoadNPCSpellClickSpells(); SendGlobalSysMessage("DB table `npc_spellclick_spells` reloaded."); return true; } bool ChatHandler::HandleReloadReservedNameCommand(char* /*args*/) { sLog.outString("Loading ReservedNames... (`reserved_name`)"); sObjectMgr.LoadReservedPlayersNames(); SendGlobalSysMessage("DB table `reserved_name` (player reserved names) reloaded."); return true; } bool ChatHandler::HandleReloadReputationRewardRateCommand(char* /*args*/) { sLog.outString("Re-Loading `reputation_reward_rate` Table!"); sObjectMgr.LoadReputationRewardRate(); SendGlobalSysMessage("DB table `reputation_reward_rate` reloaded."); return true; } bool ChatHandler::HandleReloadReputationSpilloverTemplateCommand(char* /*args*/) { sLog.outString("Re-Loading `reputation_spillover_template` Table!"); sObjectMgr.LoadReputationSpilloverTemplate(); SendGlobalSysMessage("DB table `reputation_spillover_template` reloaded."); return true; } bool ChatHandler::HandleReloadSkillDiscoveryTemplateCommand(char* /*args*/) { sLog.outString("Re-Loading Skill Discovery Table..."); LoadSkillDiscoveryTable(); SendGlobalSysMessage("DB table `skill_discovery_template` (recipes discovered at crafting) reloaded."); return true; } bool ChatHandler::HandleReloadSkillExtraItemTemplateCommand(char* /*args*/) { sLog.outString("Re-Loading Skill Extra Item Table..."); LoadSkillExtraItemTable(); SendGlobalSysMessage("DB table `skill_extra_item_template` (extra item creation when crafting) reloaded."); return true; } bool ChatHandler::HandleReloadScriptBindingCommand(char* /*args*/) { sLog.outString("Trying to re-load `script_binding` Table!"); if (sScriptMgr.ReloadScriptBinding()) SendGlobalSysMessage("DB table `script_binding` reloaded."); else SendSysMessage("DENIED: DB table `script_binding` is reloadable only in Debug build."); return true; } bool ChatHandler::HandleReloadSkillFishingBaseLevelCommand(char* /*args*/) { sLog.outString("Re-Loading Skill Fishing base level requirements..."); sObjectMgr.LoadFishingBaseSkillLevel(); SendGlobalSysMessage("DB table `skill_fishing_base_level` (fishing base level for zone/subzone) reloaded."); return true; } bool ChatHandler::HandleReloadSpellAreaCommand(char* /*args*/) { sLog.outString("Re-Loading SpellArea Data..."); sSpellMgr.LoadSpellAreas(); SendGlobalSysMessage("DB table `spell_area` (spell dependences from area/quest/auras state) reloaded."); return true; } bool ChatHandler::HandleReloadSpellBonusesCommand(char* /*args*/) { sLog.outString("Re-Loading Spell Bonus Data..."); sSpellMgr.LoadSpellBonuses(); SendGlobalSysMessage("DB table `spell_bonus_data` (spell damage/healing coefficients) reloaded."); return true; } bool ChatHandler::HandleReloadSpellChainCommand(char* /*args*/) { sLog.outString("Re-Loading Spell Chain Data... "); sSpellMgr.LoadSpellChains(); SendGlobalSysMessage("DB table `spell_chain` (spell ranks) reloaded."); return true; } bool ChatHandler::HandleReloadSpellElixirCommand(char* /*args*/) { sLog.outString("Re-Loading Spell Elixir types..."); sSpellMgr.LoadSpellElixirs(); SendGlobalSysMessage("DB table `spell_elixir` (spell elixir types) reloaded."); return true; } bool ChatHandler::HandleReloadSpellLearnSpellCommand(char* /*args*/) { sLog.outString("Re-Loading Spell Learn Spells..."); sSpellMgr.LoadSpellLearnSpells(); SendGlobalSysMessage("DB table `spell_learn_spell` reloaded."); return true; } bool ChatHandler::HandleReloadSpellProcEventCommand(char* /*args*/) { sLog.outString("Re-Loading Spell Proc Event conditions..."); sSpellMgr.LoadSpellProcEvents(); SendGlobalSysMessage("DB table `spell_proc_event` (spell proc trigger requirements) reloaded."); return true; } bool ChatHandler::HandleReloadSpellProcItemEnchantCommand(char* /*args*/) { sLog.outString("Re-Loading Spell Proc Item Enchant..."); sSpellMgr.LoadSpellProcItemEnchant(); SendGlobalSysMessage("DB table `spell_proc_item_enchant` (item enchantment ppm) reloaded."); return true; } bool ChatHandler::HandleReloadSpellScriptTargetCommand(char* /*args*/) { sLog.outString("Re-Loading SpellsScriptTarget..."); sSpellMgr.LoadSpellScriptTarget(); SendGlobalSysMessage("DB table `spell_script_target` (spell targets selection in case specific creature/GO requirements) reloaded."); return true; } bool ChatHandler::HandleReloadSpellTargetPositionCommand(char* /*args*/) { sLog.outString("Re-Loading spell target destination coordinates..."); sSpellMgr.LoadSpellTargetPositions(); SendGlobalSysMessage("DB table `spell_target_position` (destination coordinates for spell targets) reloaded."); return true; } bool ChatHandler::HandleReloadSpellThreatsCommand(char* /*args*/) { sLog.outString("Re-Loading Aggro Spells Definitions..."); sSpellMgr.LoadSpellThreats(); SendGlobalSysMessage("DB table `spell_threat` (spell aggro definitions) reloaded."); return true; } bool ChatHandler::HandleReloadSpellPetAurasCommand(char* /*args*/) { sLog.outString("Re-Loading Spell pet auras..."); sSpellMgr.LoadSpellPetAuras(); SendGlobalSysMessage("DB table `spell_pet_auras` reloaded."); return true; } bool ChatHandler::HandleReloadPageTextsCommand(char* /*args*/) { sLog.outString("Re-Loading Page Texts..."); sObjectMgr.LoadPageTexts(); SendGlobalSysMessage("DB table `page_texts` reloaded."); return true; } bool ChatHandler::HandleReloadItemEnchantementsCommand(char* /*args*/) { sLog.outString("Re-Loading Item Random Enchantments Table..."); LoadRandomEnchantmentsTable(); SendGlobalSysMessage("DB table `item_enchantment_template` reloaded."); return true; } bool ChatHandler::HandleReloadItemConvertCommand(char* /*args*/) { sLog.outString("Re-Loading Item Converts Table..."); sObjectMgr.LoadItemConverts(); SendGlobalSysMessage("DB table `item_convert` reloaded."); return true; } bool ChatHandler::HandleReloadItemRequiredTragetCommand(char* /*args*/) { sLog.outString("Re-Loading Item Required Targets Table..."); sObjectMgr.LoadItemRequiredTarget(); SendGlobalSysMessage("DB table `item_required_target` reloaded."); return true; } bool ChatHandler::HandleReloadBattleEventCommand(char* /*args*/) { sLog.outString("Re-Loading BattleGround Eventindexes..."); sBattleGroundMgr.LoadBattleEventIndexes(); SendGlobalSysMessage("DB table `gameobject_battleground` and `creature_battleground` reloaded."); return true; } bool ChatHandler::HandleReloadEventAITextsCommand(char* /*args*/) { sLog.outString("Re-Loading Texts from `creature_ai_texts`..."); sEventAIMgr.LoadCreatureEventAI_Texts(true); SendGlobalSysMessage("DB table `creature_ai_texts` reloaded."); return true; } bool ChatHandler::HandleReloadEventAISummonsCommand(char* /*args*/) { sLog.outString("Re-Loading Summons from `creature_ai_summons`..."); sEventAIMgr.LoadCreatureEventAI_Summons(true); SendGlobalSysMessage("DB table `creature_ai_summons` reloaded."); return true; } bool ChatHandler::HandleReloadEventAIScriptsCommand(char* /*args*/) { sLog.outString("Re-Loading Scripts from `creature_ai_scripts`..."); sEventAIMgr.LoadCreatureEventAI_Scripts(); SendGlobalSysMessage("DB table `creature_ai_scripts` reloaded."); return true; } bool ChatHandler::HandleReloadDbScriptStringCommand(char* /*args*/) { sLog.outString("Re-Loading Script strings from `db_script_string`..."); sScriptMgr.LoadDbScriptStrings(); SendGlobalSysMessage("DB table `db_script_string` reloaded."); return true; } bool ChatHandler::HandleReloadDBScriptsOnGossipCommand(char* args) { if (sScriptMgr.IsScriptScheduled()) { SendSysMessage("DB scripts used currently, please attempt reload later."); SetSentErrorMessage(true); return false; } if (*args != 'a') { sLog.outString("Re-Loading Scripts from `db_scripts [type = DBS_ON_GOSSIP]`..."); } sScriptMgr.LoadDbScripts(DBS_ON_GOSSIP); if (*args != 'a') SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_GOSSIP]` reloaded."); return true; } bool ChatHandler::HandleReloadDBScriptsOnSpellCommand(char* args) { if (sScriptMgr.IsScriptScheduled()) { SendSysMessage("DB scripts used currently, please attempt reload later."); SetSentErrorMessage(true); return false; } if (*args != 'a') { sLog.outString("Re-Loading Scripts from `db_scripts [type = DBS_ON_SPELL]`..."); } sScriptMgr.LoadDbScripts(DBS_ON_SPELL); if (*args != 'a') SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_SPELL]` reloaded."); return true; } bool ChatHandler::HandleReloadDBScriptsOnQuestStartCommand(char* args) { if (sScriptMgr.IsScriptScheduled()) { SendSysMessage("DB scripts used currently, please attempt reload later."); SetSentErrorMessage(true); return false; } if (*args != 'a') { sLog.outString("Re-Loading Scripts from `db_scripts [type = DBS_ON_QUEST_START]`..."); } sScriptMgr.LoadDbScripts(DBS_ON_QUEST_START); if (*args != 'a') SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_QUEST_START]` reloaded."); return true; } bool ChatHandler::HandleReloadDBScriptsOnQuestEndCommand(char* args) { if (sScriptMgr.IsScriptScheduled()) { SendSysMessage("DB scripts used currently, please attempt reload later."); SetSentErrorMessage(true); return false; } if (*args != 'a') { sLog.outString("Re-Loading Scripts from `db_scripts [type = DBS_ON_QUEST_END]`..."); } sScriptMgr.LoadDbScripts(DBS_ON_QUEST_END); if (*args != 'a') SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_QUEST_END]` reloaded."); return true; } bool ChatHandler::HandleReloadDBScriptsOnEventCommand(char* args) { if (sScriptMgr.IsScriptScheduled()) { SendSysMessage("DB scripts used currently, please attempt reload later."); SetSentErrorMessage(true); return false; } if (*args != 'a') { sLog.outString("Re-Loading Scripts from `db_scripts [type = DBS_ON_EVENT]`..."); } sScriptMgr.LoadDbScripts(DBS_ON_EVENT); if (*args != 'a') SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_EVENT]` reloaded."); return true; } bool ChatHandler::HandleReloadDBScriptsOnGoUseCommand(char* args) { if (sScriptMgr.IsScriptScheduled()) { SendSysMessage("DB scripts used currently, please attempt reload later."); SetSentErrorMessage(true); return false; } if (*args != 'a') { sLog.outString("Re-Loading Scripts from `db_scripts [type = DBS_ON_GO[_TEMPLATE]_USE]`..."); } sScriptMgr.LoadDbScripts(DBS_ON_GO_USE); sScriptMgr.LoadDbScripts(DBS_ON_GOT_USE); if (*args != 'a') SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_GO[_TEMPLATE]_USE]` reloaded."); return true; } bool ChatHandler::HandleReloadDBScriptsOnCreatureDeathCommand(char* args) { if (sScriptMgr.IsScriptScheduled()) { SendSysMessage("DB scripts used currently, please attempt reload later."); SetSentErrorMessage(true); return false; } if (*args != 'a') { sLog.outString("Re-Loading Scripts from `db_scripts [type = DBS_ON_CREATURE_DEATH]`..."); } sScriptMgr.LoadDbScripts(DBS_ON_CREATURE_DEATH); if (*args != 'a') SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_CREATURE_DEATH]` reloaded."); return true; } bool ChatHandler::HandleReloadGameGraveyardZoneCommand(char* /*args*/) { sLog.outString("Re-Loading Graveyard-zone links..."); sObjectMgr.LoadGraveyardZones(); SendGlobalSysMessage("DB table `game_graveyard_zone` reloaded."); return true; } bool ChatHandler::HandleReloadGameTeleCommand(char* /*args*/) { sLog.outString("Re-Loading Game Tele coordinates..."); sObjectMgr.LoadGameTele(); SendGlobalSysMessage("DB table `game_tele` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesAchievementRewardCommand(char* /*args*/) { sLog.outString("Re-Loading Locales Achievement Reward Data..."); sAchievementMgr.LoadRewardLocales(); SendGlobalSysMessage("DB table `locales_achievement_reward` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesCreatureCommand(char* /*args*/) { sLog.outString("Re-Loading Locales Creature ..."); sObjectMgr.LoadCreatureLocales(); SendGlobalSysMessage("DB table `locales_creature` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesGameobjectCommand(char* /*args*/) { sLog.outString("Re-Loading Locales Gameobject ... "); sObjectMgr.LoadGameObjectLocales(); SendGlobalSysMessage("DB table `locales_gameobject` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesGossipMenuOptionCommand(char* /*args*/) { sLog.outString("Re-Loading Locales Gossip Menu Option ... "); sObjectMgr.LoadGossipMenuItemsLocales(); SendGlobalSysMessage("DB table `locales_gossip_menu_option` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesItemCommand(char* /*args*/) { sLog.outString("Re-Loading Locales Item ... "); sObjectMgr.LoadItemLocales(); SendGlobalSysMessage("DB table `locales_item` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesNpcTextCommand(char* /*args*/) { sLog.outString("Re-Loading Locales NPC Text ... "); sObjectMgr.LoadGossipTextLocales(); SendGlobalSysMessage("DB table `locales_npc_text` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesPageTextCommand(char* /*args*/) { sLog.outString("Re-Loading Locales Page Text ... "); sObjectMgr.LoadPageTextLocales(); SendGlobalSysMessage("DB table `locales_page_text` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesPointsOfInterestCommand(char* /*args*/) { sLog.outString("Re-Loading Locales Points Of Interest ... "); sObjectMgr.LoadPointOfInterestLocales(); SendGlobalSysMessage("DB table `locales_points_of_interest` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesQuestCommand(char* /*args*/) { sLog.outString("Re-Loading Locales Quest ... "); sObjectMgr.LoadQuestLocales(); SendGlobalSysMessage("DB table `locales_quest` reloaded."); return true; } bool ChatHandler::HandleReloadMailLevelRewardCommand(char* /*args*/) { sLog.outString("Re-Loading Player level dependent mail rewards..."); sObjectMgr.LoadMailLevelRewards(); SendGlobalSysMessage("DB table `mail_level_reward` reloaded."); return true; } bool ChatHandler::HandleReloadCreaturesStatsCommand(char* /*args*/) { sLog.outString("Re-Loading stats data..."); sObjectMgr.LoadCreatureClassLvlStats(); SendGlobalSysMessage("DB table `creature_template_classlevelstats` reloaded."); return true; } bool ChatHandler::HandleLoadScriptsCommand(char* args) { if (!*args) { return false; } switch (sScriptMgr.LoadScriptLibrary(args)) { case SCRIPT_LOAD_OK: sWorld.SendWorldText(LANG_SCRIPTS_RELOADED_ANNOUNCE); SendSysMessage(LANG_SCRIPTS_RELOADED_OK); break; case SCRIPT_LOAD_ERR_NOT_FOUND: SendSysMessage(LANG_SCRIPTS_NOT_FOUND); break; case SCRIPT_LOAD_ERR_WRONG_API: SendSysMessage(LANG_SCRIPTS_WRONG_API); break; case SCRIPT_LOAD_ERR_OUTDATED: SendSysMessage(LANG_SCRIPTS_OUTDATED); break; } return true; } bool ChatHandler::HandleAccountSetGmLevelCommand(char* args) { char* accountStr = ExtractOptNotLastArg(&args); std::string targetAccountName; Player* targetPlayer = NULL; uint32 targetAccountId = ExtractAccountId(&accountStr, &targetAccountName, &targetPlayer); if (!targetAccountId) { return false; } /// only target player different from self allowed if (GetAccountId() == targetAccountId) { return false; } int32 gm; if (!ExtractInt32(&args, gm)) { return false; } if (gm < SEC_PLAYER || gm > SEC_ADMINISTRATOR) { SendSysMessage(LANG_BAD_VALUE); SetSentErrorMessage(true); return false; } /// can set security level only for target with less security and to less security that we have /// This will reject self apply by specify account name if (HasLowerSecurityAccount(NULL, targetAccountId, true)) { return false; } /// account can't set security to same or grater level, need more power GM or console AccountTypes plSecurity = GetAccessLevel(); if (AccountTypes(gm) >= plSecurity) { SendSysMessage(LANG_YOURS_SECURITY_IS_LOW); SetSentErrorMessage(true); return false; } if (targetPlayer) { ChatHandler(targetPlayer).PSendSysMessage(LANG_YOURS_SECURITY_CHANGED, GetNameLink().c_str(), gm); targetPlayer->GetSession()->SetSecurity(AccountTypes(gm)); } PSendSysMessage(LANG_YOU_CHANGE_SECURITY, targetAccountName.c_str(), gm); LoginDatabase.PExecute("UPDATE account SET gmlevel = '%i' WHERE id = '%u'", gm, targetAccountId); return true; } /// Set password for account bool ChatHandler::HandleAccountSetPasswordCommand(char* args) { ///- Get the command line arguments std::string account_name; uint32 targetAccountId = ExtractAccountId(&args, &account_name); if (!targetAccountId) { return false; } // allow or quoted string with possible spaces or literal without spaces char* szPassword1 = ExtractQuotedOrLiteralArg(&args); char* szPassword2 = ExtractQuotedOrLiteralArg(&args); if (!szPassword1 || !szPassword2) { return false; } /// can set password only for target with less security /// This is also reject self apply in fact if (HasLowerSecurityAccount(NULL, targetAccountId, true)) { return false; } if (strcmp(szPassword1, szPassword2)) { SendSysMessage(LANG_NEW_PASSWORDS_NOT_MATCH); SetSentErrorMessage(true); return false; } AccountOpResult result = sAccountMgr.ChangePassword(targetAccountId, szPassword1); switch (result) { case AOR_OK: SendSysMessage(LANG_COMMAND_PASSWORD); break; case AOR_NAME_NOT_EXIST: PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, account_name.c_str()); SetSentErrorMessage(true); return false; case AOR_PASS_TOO_LONG: SendSysMessage(LANG_PASSWORD_TOO_LONG); SetSentErrorMessage(true); return false; default: SendSysMessage(LANG_COMMAND_NOTCHANGEPASSWORD); SetSentErrorMessage(true); return false; } // OK, but avoid normal report for hide passwords, but log use command for anyone char msg[100]; snprintf(msg, 100, ".account set password %s *** ***", account_name.c_str()); LogCommand(msg); SetSentErrorMessage(true); return false; } void ChatHandler::ShowAchievementCriteriaListHelper(AchievementCriteriaEntry const* criEntry, AchievementEntry const* achEntry, LocaleConstant loc, Player* target /*= NULL*/) { std::ostringstream ss; if (m_session) { ss << criEntry->ID << " - |cffffffff|Hachievement_criteria:" << criEntry->ID << "|h[" << criEntry->name[loc] << " " << localeNames[loc] << "]|h|r"; } else ss << criEntry->ID << " - " << criEntry->name[loc] << " " << localeNames[loc]; if (target) ss << " = " << target->GetAchievementMgr().GetCriteriaProgressCounter(criEntry); if (achEntry->flags & ACHIEVEMENT_FLAG_COUNTER) ss << GetMangosString(LANG_COUNTER); else { ss << " [" << AchievementMgr::GetCriteriaProgressMaxCounter(criEntry, achEntry) << "]"; if (target && target->GetAchievementMgr().IsCompletedCriteria(criEntry, achEntry)) ss << GetMangosString(LANG_COMPLETE); } SendSysMessage(ss.str().c_str()); } bool ChatHandler::HandleAchievementCommand(char* args) { char* nameStr = ExtractOptNotLastArg(&args); Player* target = NULL; if (nameStr) { if (!ExtractPlayerTarget(&nameStr, &target)) return false; } else target = getSelectedPlayer(); uint32 achId; if (!ExtractUint32KeyFromLink(&args, "Hachievement", achId)) return false; AchievementEntry const* achEntry = sAchievementStore.LookupEntry(achId); if (!achEntry) { PSendSysMessage(LANG_ACHIEVEMENT_NOT_EXIST, achId); SetSentErrorMessage(true); return false; } LocaleConstant loc = GetSessionDbcLocale(); CompletedAchievementData const* completed = target ? target->GetAchievementMgr().GetCompleteData(achId) : NULL; ShowAchievementListHelper(achEntry, loc, completed ? &completed->date : NULL, target); if (AchievementCriteriaEntryList const* criteriaList = sAchievementMgr.GetAchievementCriteriaByAchievement(achEntry->ID)) { SendSysMessage(LANG_COMMAND_ACHIEVEMENT_CRITERIA); for (AchievementCriteriaEntryList::const_iterator itr = criteriaList->begin(); itr != criteriaList->end(); ++itr) ShowAchievementCriteriaListHelper(*itr, achEntry, loc, target); } return true; } bool ChatHandler::HandleAchievementAddCommand(char* args) { char* nameStr = ExtractOptNotLastArg(&args); Player* target; if (!ExtractPlayerTarget(&nameStr, &target)) return false; uint32 achId; if (!ExtractUint32KeyFromLink(&args, "Hachievement", achId)) return false; AchievementEntry const* achEntry = sAchievementStore.LookupEntry(achId); if (!achEntry || achEntry->flags & ACHIEVEMENT_FLAG_COUNTER) { PSendSysMessage(LANG_ACHIEVEMENT_NOT_EXIST, achId); SetSentErrorMessage(true); return false; } AchievementMgr& mgr = target->GetAchievementMgr(); if (AchievementCriteriaEntryList const* criteriaList = sAchievementMgr.GetAchievementCriteriaByAchievement(achEntry->ID)) { for (AchievementCriteriaEntryList::const_iterator itr = criteriaList->begin(); itr != criteriaList->end(); ++itr) { if (mgr.IsCompletedCriteria(*itr, achEntry)) continue; uint32 maxValue = AchievementMgr::GetCriteriaProgressMaxCounter(*itr, achEntry); if (maxValue == std::numeric_limits<uint32>::max()) maxValue = 1; // Exception for counter like achievements, set them only to 1 mgr.SetCriteriaProgress(*itr, achEntry, maxValue, AchievementMgr::PROGRESS_SET); } } LocaleConstant loc = GetSessionDbcLocale(); CompletedAchievementData const* completed = target ? target->GetAchievementMgr().GetCompleteData(achId) : NULL; ShowAchievementListHelper(achEntry, loc, completed ? &completed->date : NULL, target); return true; } bool ChatHandler::HandleAchievementRemoveCommand(char* args) { char* nameStr = ExtractOptNotLastArg(&args); Player* target; if (!ExtractPlayerTarget(&nameStr, &target)) return false; uint32 achId; if (!ExtractUint32KeyFromLink(&args, "Hachievement", achId)) return false; AchievementEntry const* achEntry = sAchievementStore.LookupEntry(achId); if (!achEntry) { PSendSysMessage(LANG_ACHIEVEMENT_NOT_EXIST, achId); SetSentErrorMessage(true); return false; } AchievementMgr& mgr = target->GetAchievementMgr(); if (AchievementCriteriaEntryList const* criteriaList = sAchievementMgr.GetAchievementCriteriaByAchievement(achEntry->ID)) for (AchievementCriteriaEntryList::const_iterator itr = criteriaList->begin(); itr != criteriaList->end(); ++itr) mgr.SetCriteriaProgress(*itr, achEntry, 0, AchievementMgr::PROGRESS_SET); LocaleConstant loc = GetSessionDbcLocale(); CompletedAchievementData const* completed = target ? target->GetAchievementMgr().GetCompleteData(achId) : NULL; ShowAchievementListHelper(achEntry, loc, completed ? &completed->date : NULL, target); return true; } bool ChatHandler::HandleAchievementCriteriaAddCommand(char* args) { Player* target; uint32 criId; if (!ExtractUint32KeyFromLink(&args, "Hachievement_criteria", criId)) { // maybe player first char* nameStr = ExtractArg(&args); if (!ExtractPlayerTarget(&nameStr, &target)) return false; if (!ExtractUint32KeyFromLink(&args, "Hachievement_criteria", criId)) return false; } else target = getSelectedPlayer(); AchievementCriteriaEntry const* criEntry = sAchievementCriteriaStore.LookupEntry(criId); if (!criEntry) { PSendSysMessage(LANG_ACHIEVEMENT_CRITERIA_NOT_EXIST, criId); SetSentErrorMessage(true); return false; } AchievementEntry const* achEntry = sAchievementStore.LookupEntry(criEntry->referredAchievement); if (!achEntry) return false; LocaleConstant loc = GetSessionDbcLocale(); uint32 maxValue = AchievementMgr::GetCriteriaProgressMaxCounter(criEntry, achEntry); if (maxValue == std::numeric_limits<uint32>::max()) maxValue = 1; // Exception for counter like achievements, set them only to 1 AchievementMgr& mgr = target->GetAchievementMgr(); // nothing do if completed if (mgr.IsCompletedCriteria(criEntry, achEntry)) { ShowAchievementCriteriaListHelper(criEntry, achEntry, loc, target); return true; } uint32 progress = mgr.GetCriteriaProgressCounter(criEntry); uint32 val; if (!ExtractOptUInt32(&args, val, maxValue ? maxValue : 1)) return false; uint32 new_val; if (maxValue) new_val = progress < maxValue && maxValue - progress > val ? progress + val : maxValue; else { uint32 max_int = std::numeric_limits<uint32>::max(); new_val = progress < max_int && max_int - progress > val ? progress + val : max_int; } mgr.SetCriteriaProgress(criEntry, achEntry, new_val, AchievementMgr::PROGRESS_SET); ShowAchievementCriteriaListHelper(criEntry, achEntry, loc, target); return true; } bool ChatHandler::HandleAchievementCriteriaRemoveCommand(char* args) { Player* target; uint32 criId; if (!ExtractUint32KeyFromLink(&args, "Hachievement_criteria", criId)) { // maybe player first char* nameStr = ExtractArg(&args); if (!ExtractPlayerTarget(&nameStr, &target)) return false; if (!ExtractUint32KeyFromLink(&args, "Hachievement_criteria", criId)) return false; } else target = getSelectedPlayer(); AchievementCriteriaEntry const* criEntry = sAchievementCriteriaStore.LookupEntry(criId); if (!criEntry) { PSendSysMessage(LANG_ACHIEVEMENT_CRITERIA_NOT_EXIST, criId); SetSentErrorMessage(true); return false; } AchievementEntry const* achEntry = sAchievementStore.LookupEntry(criEntry->referredAchievement); if (!achEntry) return false; LocaleConstant loc = GetSessionDbcLocale(); uint32 maxValue = AchievementMgr::GetCriteriaProgressMaxCounter(criEntry, achEntry); if (maxValue == std::numeric_limits<uint32>::max()) maxValue = 1; // Exception for counter like achievements, set them only to 1 AchievementMgr& mgr = target->GetAchievementMgr(); uint32 progress = mgr.GetCriteriaProgressCounter(criEntry); // nothing do if not started if (progress == 0) { ShowAchievementCriteriaListHelper(criEntry, achEntry, loc, target); return true; } uint32 change; if (!ExtractOptUInt32(&args, change, maxValue ? maxValue : 1)) return false; uint32 newval = change < progress ? progress - change : 0; mgr.SetCriteriaProgress(criEntry, achEntry, newval, AchievementMgr::PROGRESS_SET); ShowAchievementCriteriaListHelper(criEntry, achEntry, loc, target); return true; } bool ChatHandler::HandleMaxSkillCommand(char* /*args*/) { Player* SelectedPlayer = getSelectedPlayer(); if (!SelectedPlayer) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } // each skills that have max skill value dependent from level seted to current level max skill value SelectedPlayer->UpdateSkillsToMaxSkillsForLevel(); return true; } bool ChatHandler::HandleSetSkillCommand(char* args) { Player* target = getSelectedPlayer(); if (!target) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } // number or [name] Shift-click form |color|Hskill:skill_id|h[name]|h|r char* skill_p = ExtractKeyFromLink(&args, "Hskill"); if (!skill_p) { return false; } int32 skill; if (!ExtractInt32(&skill_p, skill)) { return false; } int32 level; if (!ExtractInt32(&args, level)) { return false; } int32 maxskill; if (!ExtractOptInt32(&args, maxskill, target->GetPureMaxSkillValue(skill))) { return false; } if (skill <= 0) { PSendSysMessage(LANG_INVALID_SKILL_ID, skill); SetSentErrorMessage(true); return false; } SkillLineEntry const* sl = sSkillLineStore.LookupEntry(skill); if (!sl) { PSendSysMessage(LANG_INVALID_SKILL_ID, skill); SetSentErrorMessage(true); return false; } std::string tNameLink = GetNameLink(target); if (!target->GetSkillValue(skill)) { PSendSysMessage(LANG_SET_SKILL_ERROR, tNameLink.c_str(), skill, sl->name[GetSessionDbcLocale()]); SetSentErrorMessage(true); return false; } if (level <= 0 || level > maxskill || maxskill <= 0) { return false; } target->SetSkill(skill, level, maxskill); PSendSysMessage(LANG_SET_SKILL, skill, sl->name[GetSessionDbcLocale()], tNameLink.c_str(), level, maxskill); return true; } bool ChatHandler::HandleUnLearnCommand(char* args) { if (!*args) { return false; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r uint32 spell_id = ExtractSpellIdFromLink(&args); if (!spell_id) { return false; } bool allRanks = ExtractLiteralArg(&args, "all") != NULL; if (!allRanks && *args) // can be fail also at syntax error { return false; } Player* target = getSelectedPlayer(); if (!target) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } if (allRanks) { spell_id = sSpellMgr.GetFirstSpellInChain(spell_id); } if (target->HasSpell(spell_id)) { target->removeSpell(spell_id, false, !allRanks); } else { SendSysMessage(LANG_FORGET_SPELL); } if (GetTalentSpellCost(spell_id)) target->SendTalentsInfoData(false); return true; } bool ChatHandler::HandleCooldownCommand(char* args) { Player* target = getSelectedPlayer(); if (!target) { SendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } std::string tNameLink = GetNameLink(target); if (!*args) { target->RemoveAllSpellCooldown(); PSendSysMessage(LANG_REMOVEALL_COOLDOWN, tNameLink.c_str()); } else { // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spell_id = ExtractSpellIdFromLink(&args); if (!spell_id) { return false; } if (!sSpellStore.LookupEntry(spell_id)) { PSendSysMessage(LANG_UNKNOWN_SPELL, target == m_session->GetPlayer() ? GetMangosString(LANG_YOU) : tNameLink.c_str()); SetSentErrorMessage(true); return false; } target->RemoveSpellCooldown(spell_id, true); PSendSysMessage(LANG_REMOVE_COOLDOWN, spell_id, target == m_session->GetPlayer() ? GetMangosString(LANG_YOU) : tNameLink.c_str()); } return true; } bool ChatHandler::HandleLearnAllCommand(char* /*args*/) { static const char* allSpellList[] = { "3365", "6233", "6247", "6246", "6477", "6478", "22810", "8386", "21651", "21652", "522", "7266", "8597", "2479", "22027", "6603", "5019", "133", "168", "227", "5009", "9078", "668", "203", "20599", "20600", "81", "20597", "20598", "20864", "1459", "5504", "587", "5143", "118", "5505", "597", "604", "1449", "1460", "2855", "1008", "475", "5506", "1463", "12824", "8437", "990", "5145", "8450", "1461", "759", "8494", "8455", "8438", "6127", "8416", "6129", "8451", "8495", "8439", "3552", "8417", "10138", "12825", "10169", "10156", "10144", "10191", "10201", "10211", "10053", "10173", "10139", "10145", "10192", "10170", "10202", "10054", "10174", "10193", "12826", "2136", "143", "145", "2137", "2120", "3140", "543", "2138", "2948", "8400", "2121", "8444", "8412", "8457", "8401", "8422", "8445", "8402", "8413", "8458", "8423", "8446", "10148", "10197", "10205", "10149", "10215", "10223", "10206", "10199", "10150", "10216", "10207", "10225", "10151", "116", "205", "7300", "122", "837", "10", "7301", "7322", "6143", "120", "865", "8406", "6141", "7302", "8461", "8407", "8492", "8427", "8408", "6131", "7320", "10159", "8462", "10185", "10179", "10160", "10180", "10219", "10186", "10177", "10230", "10181", "10161", "10187", "10220", "2018", "2663", "12260", "2660", "3115", "3326", "2665", "3116", "2738", "3293", "2661", "3319", "2662", "9983", "8880", "2737", "2739", "7408", "3320", "2666", "3323", "3324", "3294", "22723", "23219", "23220", "23221", "23228", "23338", "10788", "10790", "5611", "5016", "5609", "2060", "10963", "10964", "10965", "22593", "22594", "596", "996", "499", "768", "17002", "1448", "1082", "16979", "1079", "5215", "20484", "5221", "15590", "17007", "6795", "6807", "5487", "1446", "1066", "5421", "3139", "779", "6811", "6808", "1445", "5216", "1737", "5222", "5217", "1432", "6812", "9492", "5210", "3030", "1441", "783", "6801", "20739", "8944", "9491", "22569", "5226", "6786", "1433", "8973", "1828", "9495", "9006", "6794", "8993", "5203", "16914", "6784", "9635", "22830", "20722", "9748", "6790", "9753", "9493", "9752", "9831", "9825", "9822", "5204", "5401", "22831", "6793", "9845", "17401", "9882", "9868", "20749", "9893", "9899", "9895", "9832", "9902", "9909", "22832", "9828", "9851", "9883", "9869", "17406", "17402", "9914", "20750", "9897", "9848", "3127", "107", "204", "9116", "2457", "78", "18848", "331", "403", "2098", "1752", "11278", "11288", "11284", "6461", "2344", "2345", "6463", "2346", "2352", "775", "1434", "1612", "71", "2468", "2458", "2467", "7164", "7178", "7367", "7376", "7381", "21156", "5209", "3029", "5201", "9849", "9850", "20719", "22568", "22827", "22828", "22829", "6809", "8972", "9005", "9823", "9827", "6783", "9913", "6785", "6787", "9866", "9867", "9894", "9896", "6800", "8992", "9829", "9830", "780", "769", "6749", "6750", "9755", "9754", "9908", "20745", "20742", "20747", "20748", "9746", "9745", "9880", "9881", "5391", "842", "3025", "3031", "3287", "3329", "1945", "3559", "4933", "4934", "4935", "4936", "5142", "5390", "5392", "5404", "5420", "6405", "7293", "7965", "8041", "8153", "9033", "9034", //"9036", problems with ghost state "16421", "21653", "22660", "5225", "9846", "2426", "5916", "6634", //"6718", phasing stealth, annoying for learn all case. "6719", "8822", "9591", "9590", "10032", "17746", "17747", "8203", "11392", "12495", "16380", "23452", "4079", "4996", "4997", "4998", "4999", "5000", "6348", "6349", "6481", "6482", "6483", "6484", "11362", "11410", "11409", "12510", "12509", "12885", "13142", "21463", "23460", "11421", "11416", "11418", "1851", "10059", "11423", "11417", "11422", "11419", "11424", "11420", "27", "31", "33", "34", "35", "15125", "21127", "22950", "1180", "201", "12593", "12842", "16770", "6057", "12051", "18468", "12606", "12605", "18466", "12502", "12043", "15060", "12042", "12341", "12848", "12344", "12353", "18460", "11366", "12350", "12352", "13043", "11368", "11113", "12400", "11129", "16766", "12573", "15053", "12580", "12475", "12472", "12953", "12488", "11189", "12985", "12519", "16758", "11958", "12490", "11426", "3565", "3562", "18960", "3567", "3561", "3566", "3563", "1953", "2139", "12505", "13018", "12522", "12523", "5146", "5144", "5148", "8419", "8418", "10213", "10212", "10157", "12524", "13019", "12525", "13020", "12526", "13021", "18809", "13031", "13032", "13033", "4036", "3920", "3919", "3918", "7430", "3922", "3923", "7411", "7418", "7421", "13262", "7412", "7415", "7413", "7416", "13920", "13921", "7745", "7779", "7428", "7457", "7857", "7748", "7426", "13421", "7454", "13378", "7788", "14807", "14293", "7795", "6296", "20608", "755", "444", "427", "428", "442", "447", "3578", "3581", "19027", "3580", "665", "3579", "3577", "6755", "3576", "2575", "2577", "2578", "2579", "2580", "2656", "2657", "2576", "3564", "10248", "8388", "2659", "14891", "3308", "3307", "10097", "2658", "3569", "16153", "3304", "10098", "4037", "3929", "3931", "3926", "3924", "3930", "3977", "3925", "136", "228", "5487", "43", "202", "0" }; int loop = 0; while (strcmp(allSpellList[loop], "0")) { uint32 spell = atol((char*)allSpellList[loop++]); if (m_session->GetPlayer()->HasSpell(spell)) { continue; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell); if (!spellInfo || !SpellMgr::IsSpellValid(spellInfo, m_session->GetPlayer())) { PSendSysMessage(LANG_COMMAND_SPELL_BROKEN, spell); continue; } m_session->GetPlayer()->learnSpell(spell, false); } SendSysMessage(LANG_COMMAND_LEARN_MANY_SPELLS); return true; } bool ChatHandler::HandleLearnAllGMCommand(char* /*args*/) { static const char* gmSpellList[] = { "24347", // Become A Fish, No Breath Bar "35132", // Visual Boom "38488", // Attack 4000-8000 AOE "38795", // Attack 2000 AOE + Slow Down 90% "15712", // Attack 200 "1852", // GM Spell Silence "31899", // Kill "31924", // Kill "29878", // Kill My Self "26644", // More Kill "28550", // Invisible 24 "23452", // Invisible + Target "0" }; uint16 gmSpellIter = 0; while (strcmp(gmSpellList[gmSpellIter], "0")) { uint32 spell = atol((char*)gmSpellList[gmSpellIter++]); SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell); if (!spellInfo || !SpellMgr::IsSpellValid(spellInfo, m_session->GetPlayer())) { PSendSysMessage(LANG_COMMAND_SPELL_BROKEN, spell); continue; } m_session->GetPlayer()->learnSpell(spell, false); } SendSysMessage(LANG_LEARNING_GM_SKILLS); return true; } bool ChatHandler::HandleLearnAllMyClassCommand(char* /*args*/) { HandleLearnAllMySpellsCommand((char*)""); HandleLearnAllMyTalentsCommand((char*)""); return true; } bool ChatHandler::HandleLearnAllMySpellsCommand(char* /*args*/) { Player* player = m_session->GetPlayer(); ChrClassesEntry const* clsEntry = sChrClassesStore.LookupEntry(player->getClass()); if (!clsEntry) { return true; } uint32 family = clsEntry->spellfamily; for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); ++i) { SkillLineAbilityEntry const* entry = sSkillLineAbilityStore.LookupEntry(i); if (!entry) { continue; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(entry->spellId); if (!spellInfo) { continue; } // skip server-side/triggered spells if (spellInfo->spellLevel == 0) { continue; } // skip wrong class/race skills if (!player->IsSpellFitByClassAndRace(spellInfo->Id)) { continue; } // skip other spell families if (spellInfo->SpellFamilyName != family) { continue; } // skip spells with first rank learned as talent (and all talents then also) uint32 first_rank = sSpellMgr.GetFirstSpellInChain(spellInfo->Id); if (GetTalentSpellCost(first_rank) > 0) { continue; } // skip broken spells if (!SpellMgr::IsSpellValid(spellInfo, player, false)) { continue; } player->learnSpell(spellInfo->Id, false); } SendSysMessage(LANG_COMMAND_LEARN_CLASS_SPELLS); return true; } bool ChatHandler::HandleLearnAllMyTalentsCommand(char* /*args*/) { Player* player = m_session->GetPlayer(); uint32 classMask = player->getClassMask(); for (uint32 i = 0; i < sTalentStore.GetNumRows(); ++i) { TalentEntry const* talentInfo = sTalentStore.LookupEntry(i); if (!talentInfo) { continue; } TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab); if (!talentTabInfo) { continue; } if ((classMask & talentTabInfo->ClassMask) == 0) { continue; } // search highest talent rank uint32 spellid = 0; for (int rank = MAX_TALENT_RANK - 1; rank >= 0; --rank) { if (talentInfo->RankID[rank] != 0) { spellid = talentInfo->RankID[rank]; break; } } if (!spellid) // ??? none spells in talent { continue; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellid); if (!spellInfo || !SpellMgr::IsSpellValid(spellInfo, player, false)) { continue; } // learn highest rank of talent and learn all non-talent spell ranks (recursive by tree) player->learnSpellHighRank(spellid); } player->SendTalentsInfoData(false); SendSysMessage(LANG_COMMAND_LEARN_CLASS_TALENTS); return true; } bool ChatHandler::HandleLearnAllMyPetTalentsCommand(char* /*args*/) { Player* player = m_session->GetPlayer(); Pet* pet = player->GetPet(); if (!pet) { SendSysMessage(LANG_NO_PET_FOUND); SetSentErrorMessage(true); return false; } CreatureInfo const* ci = pet->GetCreatureInfo(); if (!ci) { SendSysMessage(LANG_WRONG_PET_TYPE); SetSentErrorMessage(true); return false; } CreatureFamilyEntry const* pet_family = sCreatureFamilyStore.LookupEntry(ci->Family); if (!pet_family) { SendSysMessage(LANG_WRONG_PET_TYPE); SetSentErrorMessage(true); return false; } if (pet_family->petTalentType < 0) // not hunter pet { SendSysMessage(LANG_WRONG_PET_TYPE); SetSentErrorMessage(true); return false; } for (uint32 i = 0; i < sTalentStore.GetNumRows(); ++i) { TalentEntry const* talentInfo = sTalentStore.LookupEntry(i); if (!talentInfo) continue; TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab); if (!talentTabInfo) continue; // prevent learn talent for different family (cheating) if (((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask) == 0) continue; // search highest talent rank uint32 spellid = 0; for (int rank = MAX_TALENT_RANK - 1; rank >= 0; --rank) { if (talentInfo->RankID[rank] != 0) { spellid = talentInfo->RankID[rank]; break; } } if (!spellid) // ??? none spells in talent continue; SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellid); if (!spellInfo || !SpellMgr::IsSpellValid(spellInfo, player, false)) continue; // learn highest rank of talent and learn all non-talent spell ranks (recursive by tree) pet->learnSpellHighRank(spellid); } player->SendTalentsInfoData(true); SendSysMessage(LANG_COMMAND_LEARN_PET_TALENTS); return true; } bool ChatHandler::HandleLearnAllLangCommand(char* /*args*/) { Player* player = m_session->GetPlayer(); // skipping UNIVERSAL language (0) for (int i = 1; i < LANGUAGES_COUNT; ++i) { player->learnSpell(lang_description[i].spell_id, false); } SendSysMessage(LANG_COMMAND_LEARN_ALL_LANG); return true; } bool ChatHandler::HandleLearnAllDefaultCommand(char* args) { Player* target; if (!ExtractPlayerTarget(&args, &target)) { return false; } target->learnDefaultSpells(); target->learnQuestRewardedSpells(); PSendSysMessage(LANG_COMMAND_LEARN_ALL_DEFAULT_AND_QUEST, GetNameLink(target).c_str()); return true; } bool ChatHandler::HandleLearnCommand(char* args) { Player* player = m_session->GetPlayer(); Player* targetPlayer = getSelectedPlayer(); if (!targetPlayer) { SendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spell = ExtractSpellIdFromLink(&args); if (!spell || !sSpellStore.LookupEntry(spell)) { return false; } bool allRanks = ExtractLiteralArg(&args, "all") != NULL; if (!allRanks && *args) // can be fail also at syntax error { return false; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell); if (!spellInfo || !SpellMgr::IsSpellValid(spellInfo, player)) { PSendSysMessage(LANG_COMMAND_SPELL_BROKEN, spell); SetSentErrorMessage(true); return false; } if (!allRanks && targetPlayer->HasSpell(spell)) { if (targetPlayer == player) { SendSysMessage(LANG_YOU_KNOWN_SPELL); } else PSendSysMessage(LANG_TARGET_KNOWN_SPELL, GetNameLink(targetPlayer).c_str()); SetSentErrorMessage(true); return false; } if (allRanks) { targetPlayer->learnSpellHighRank(spell); } else { targetPlayer->learnSpell(spell, false); } uint32 first_spell = sSpellMgr.GetFirstSpellInChain(spell); if (GetTalentSpellCost(first_spell)) targetPlayer->SendTalentsInfoData(false); return true; } bool ChatHandler::HandleAddItemCommand(char* args) { char* cId = ExtractKeyFromLink(&args, "Hitem"); if (!cId) { return false; } uint32 itemId = 0; if (!ExtractUInt32(&cId, itemId)) // [name] manual form { std::string itemName = cId; WorldDatabase.escape_string(itemName); QueryResult* result = WorldDatabase.PQuery("SELECT entry FROM item_template WHERE name = '%s'", itemName.c_str()); if (!result) { PSendSysMessage(LANG_COMMAND_COULDNOTFIND, cId); SetSentErrorMessage(true); return false; } itemId = result->Fetch()->GetUInt16(); delete result; } int32 count; if (!ExtractOptInt32(&args, count, 1)) { return false; } Player* pl = m_session->GetPlayer(); Player* plTarget = getSelectedPlayer(); if (!plTarget) { plTarget = pl; } DETAIL_LOG(GetMangosString(LANG_ADDITEM), itemId, count); ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(itemId); if (!pProto) { PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, itemId); SetSentErrorMessage(true); return false; } // Subtract if (count < 0) { plTarget->DestroyItemCount(itemId, -count, true, false); PSendSysMessage(LANG_REMOVEITEM, itemId, -count, GetNameLink(plTarget).c_str()); return true; } // Adding items uint32 noSpaceForCount = 0; // check space and find places ItemPosCountVec dest; uint8 msg = plTarget->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, count, &noSpaceForCount); if (msg != EQUIP_ERR_OK) // convert to possible store amount { count -= noSpaceForCount; } if (count == 0 || dest.empty()) // can't add any { PSendSysMessage(LANG_ITEM_CANNOT_CREATE, itemId, noSpaceForCount); SetSentErrorMessage(true); return false; } Item* item = plTarget->StoreNewItem(dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId)); // remove binding (let GM give it to another player later) if (pl == plTarget) for (ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr) if (Item* item1 = pl->GetItemByPos(itr->pos)) { item1->SetBinding(false); } if (count > 0 && item) { pl->SendNewItem(item, count, false, true); if (pl != plTarget) { plTarget->SendNewItem(item, count, true, false); } } if (noSpaceForCount > 0) { PSendSysMessage(LANG_ITEM_CANNOT_CREATE, itemId, noSpaceForCount); } return true; } bool ChatHandler::HandleAddItemSetCommand(char* args) { uint32 itemsetId; if (!ExtractUint32KeyFromLink(&args, "Hitemset", itemsetId)) { return false; } // prevent generation all items with itemset field value '0' if (itemsetId == 0) { PSendSysMessage(LANG_NO_ITEMS_FROM_ITEMSET_FOUND, itemsetId); SetSentErrorMessage(true); return false; } Player* pl = m_session->GetPlayer(); Player* plTarget = getSelectedPlayer(); if (!plTarget) { plTarget = pl; } DETAIL_LOG(GetMangosString(LANG_ADDITEMSET), itemsetId); bool found = false; for (uint32 id = 0; id < sItemStorage.GetMaxEntry(); ++id) { ItemPrototype const* pProto = sItemStorage.LookupEntry<ItemPrototype>(id); if (!pProto) { continue; } if (pProto->ItemSet == itemsetId) { found = true; ItemPosCountVec dest; InventoryResult msg = plTarget->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, pProto->ItemId, 1); if (msg == EQUIP_ERR_OK) { Item* item = plTarget->StoreNewItem(dest, pProto->ItemId, true); // remove binding (let GM give it to another player later) if (pl == plTarget) { item->SetBinding(false); } pl->SendNewItem(item, 1, false, true); if (pl != plTarget) { plTarget->SendNewItem(item, 1, true, false); } } else { pl->SendEquipError(msg, NULL, NULL, pProto->ItemId); PSendSysMessage(LANG_ITEM_CANNOT_CREATE, pProto->ItemId, 1); } } } if (!found) { PSendSysMessage(LANG_NO_ITEMS_FROM_ITEMSET_FOUND, itemsetId); SetSentErrorMessage(true); return false; } return true; } bool ChatHandler::HandleListItemCommand(char* args) { uint32 item_id; if (!ExtractUint32KeyFromLink(&args, "Hitem", item_id)) { return false; } if (!item_id) { PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, item_id); SetSentErrorMessage(true); return false; } ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(item_id); if (!itemProto) { PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, item_id); SetSentErrorMessage(true); return false; } uint32 count; if (!ExtractOptUInt32(&args, count, 10)) { return false; } QueryResult* result; // inventory case uint32 inv_count = 0; result = CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM character_inventory WHERE item_template='%u'", item_id); if (result) { inv_count = (*result)[0].GetUInt32(); delete result; } result = CharacterDatabase.PQuery( // 0 1 2 3 4 5 "SELECT ci.item, cibag.slot AS bag, ci.slot, ci.guid, characters.account,characters.name " "FROM character_inventory AS ci LEFT JOIN character_inventory AS cibag ON (cibag.item=ci.bag),characters " "WHERE ci.item_template='%u' AND ci.guid = characters.guid LIMIT %u ", item_id, uint32(count)); if (result) { do { Field* fields = result->Fetch(); uint32 item_guid = fields[0].GetUInt32(); uint32 item_bag = fields[1].GetUInt32(); uint32 item_slot = fields[2].GetUInt32(); uint32 owner_guid = fields[3].GetUInt32(); uint32 owner_acc = fields[4].GetUInt32(); std::string owner_name = fields[5].GetCppString(); char const* item_pos = 0; if (Player::IsEquipmentPos(item_bag, item_slot)) { item_pos = "[equipped]"; } else if (Player::IsInventoryPos(item_bag, item_slot)) { item_pos = "[in inventory]"; } else if (Player::IsBankPos(item_bag, item_slot)) { item_pos = "[in bank]"; } else { item_pos = ""; } PSendSysMessage(LANG_ITEMLIST_SLOT, item_guid, owner_name.c_str(), owner_guid, owner_acc, item_pos); } while (result->NextRow()); uint32 res_count = uint32(result->GetRowCount()); delete result; if (count > res_count) { count -= res_count; } else if (count) { count = 0; } } // mail case uint32 mail_count = 0; result = CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM mail_items WHERE item_template='%u'", item_id); if (result) { mail_count = (*result)[0].GetUInt32(); delete result; } if (count > 0) { result = CharacterDatabase.PQuery( // 0 1 2 3 4 5 6 "SELECT mail_items.item_guid, mail.sender, mail.receiver, char_s.account, char_s.name, char_r.account, char_r.name " "FROM mail,mail_items,characters as char_s,characters as char_r " "WHERE mail_items.item_template='%u' AND char_s.guid = mail.sender AND char_r.guid = mail.receiver AND mail.id=mail_items.mail_id LIMIT %u", item_id, uint32(count)); } else { result = NULL; } if (result) { do { Field* fields = result->Fetch(); uint32 item_guid = fields[0].GetUInt32(); uint32 item_s = fields[1].GetUInt32(); uint32 item_r = fields[2].GetUInt32(); uint32 item_s_acc = fields[3].GetUInt32(); std::string item_s_name = fields[4].GetCppString(); uint32 item_r_acc = fields[5].GetUInt32(); std::string item_r_name = fields[6].GetCppString(); char const* item_pos = "[in mail]"; PSendSysMessage(LANG_ITEMLIST_MAIL, item_guid, item_s_name.c_str(), item_s, item_s_acc, item_r_name.c_str(), item_r, item_r_acc, item_pos); } while (result->NextRow()); uint32 res_count = uint32(result->GetRowCount()); delete result; if (count > res_count) { count -= res_count; } else if (count) { count = 0; } } // auction case uint32 auc_count = 0; result = CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM auction WHERE item_template='%u'", item_id); if (result) { auc_count = (*result)[0].GetUInt32(); delete result; } if (count > 0) { result = CharacterDatabase.PQuery( // 0 1 2 3 "SELECT auction.itemguid, auction.itemowner, characters.account, characters.name " "FROM auction,characters WHERE auction.item_template='%u' AND characters.guid = auction.itemowner LIMIT %u", item_id, uint32(count)); } else { result = NULL; } if (result) { do { Field* fields = result->Fetch(); uint32 item_guid = fields[0].GetUInt32(); uint32 owner = fields[1].GetUInt32(); uint32 owner_acc = fields[2].GetUInt32(); std::string owner_name = fields[3].GetCppString(); char const* item_pos = "[in auction]"; PSendSysMessage(LANG_ITEMLIST_AUCTION, item_guid, owner_name.c_str(), owner, owner_acc, item_pos); } while (result->NextRow()); delete result; } // guild bank case uint32 guild_count = 0; result = CharacterDatabase.PQuery("SELECT COUNT(item_entry) FROM guild_bank_item WHERE item_entry='%u'", item_id); if (result) { guild_count = (*result)[0].GetUInt32(); delete result; } result = CharacterDatabase.PQuery( // 0 1 2 "SELECT gi.item_guid, gi.guildid, guild.name " "FROM guild_bank_item AS gi, guild WHERE gi.item_entry='%u' AND gi.guildid = guild.guildid LIMIT %u ", item_id, uint32(count)); if (result) { do { Field* fields = result->Fetch(); uint32 item_guid = fields[0].GetUInt32(); uint32 guild_guid = fields[1].GetUInt32(); std::string guild_name = fields[2].GetCppString(); char const* item_pos = "[in guild bank]"; PSendSysMessage(LANG_ITEMLIST_GUILD, item_guid, guild_name.c_str(), guild_guid, item_pos); } while (result->NextRow()); uint32 res_count = uint32(result->GetRowCount()); delete result; if (count > res_count) count -= res_count; else if (count) count = 0; } if (inv_count + mail_count + auc_count + guild_count == 0) { SendSysMessage(LANG_COMMAND_NOITEMFOUND); SetSentErrorMessage(true); return false; } PSendSysMessage(LANG_COMMAND_LISTITEMMESSAGE, item_id, inv_count + mail_count + auc_count + guild_count, inv_count, mail_count, auc_count, guild_count); return true; } bool ChatHandler::HandleListObjectCommand(char* args) { // number or [name] Shift-click form |color|Hgameobject_entry:go_id|h[name]|h|r uint32 go_id; if (!ExtractUint32KeyFromLink(&args, "Hgameobject_entry", go_id)) { return false; } if (!go_id) { PSendSysMessage(LANG_COMMAND_LISTOBJINVALIDID, go_id); SetSentErrorMessage(true); return false; } GameObjectInfo const* gInfo = ObjectMgr::GetGameObjectInfo(go_id); if (!gInfo) { PSendSysMessage(LANG_COMMAND_LISTOBJINVALIDID, go_id); SetSentErrorMessage(true); return false; } uint32 count; if (!ExtractOptUInt32(&args, count, 10)) { return false; } QueryResult* result; uint32 obj_count = 0; result = WorldDatabase.PQuery("SELECT COUNT(guid) FROM gameobject WHERE id='%u'", go_id); if (result) { obj_count = (*result)[0].GetUInt32(); delete result; } if (m_session) { Player* pl = m_session->GetPlayer(); result = WorldDatabase.PQuery("SELECT guid, position_x, position_y, position_z, map, (POW(position_x - '%f', 2) + POW(position_y - '%f', 2) + POW(position_z - '%f', 2)) AS order_ FROM gameobject WHERE id = '%u' ORDER BY order_ ASC LIMIT %u", pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(), go_id, uint32(count)); } else result = WorldDatabase.PQuery("SELECT guid, position_x, position_y, position_z, map FROM gameobject WHERE id = '%u' LIMIT %u", go_id, uint32(count)); if (result) { do { Field* fields = result->Fetch(); uint32 guid = fields[0].GetUInt32(); float x = fields[1].GetFloat(); float y = fields[2].GetFloat(); float z = fields[3].GetFloat(); int mapid = fields[4].GetUInt16(); if (m_session) { PSendSysMessage(LANG_GO_LIST_CHAT, guid, PrepareStringNpcOrGoSpawnInformation<GameObject>(guid).c_str(), guid, gInfo->name, x, y, z, mapid); } else { PSendSysMessage(LANG_GO_LIST_CONSOLE, guid, PrepareStringNpcOrGoSpawnInformation<GameObject>(guid).c_str(), gInfo->name, x, y, z, mapid); } } while (result->NextRow()); delete result; } PSendSysMessage(LANG_COMMAND_LISTOBJMESSAGE, go_id, obj_count); return true; } bool ChatHandler::HandleListCreatureCommand(char* args) { // number or [name] Shift-click form |color|Hcreature_entry:creature_id|h[name]|h|r uint32 cr_id; if (!ExtractUint32KeyFromLink(&args, "Hcreature_entry", cr_id)) { return false; } if (!cr_id) { PSendSysMessage(LANG_COMMAND_INVALIDCREATUREID, cr_id); SetSentErrorMessage(true); return false; } CreatureInfo const* cInfo = ObjectMgr::GetCreatureTemplate(cr_id); if (!cInfo) { PSendSysMessage(LANG_COMMAND_INVALIDCREATUREID, cr_id); SetSentErrorMessage(true); return false; } uint32 count; if (!ExtractOptUInt32(&args, count, 10)) { return false; } QueryResult* result; uint32 cr_count = 0; result = WorldDatabase.PQuery("SELECT COUNT(guid) FROM creature WHERE id='%u'", cr_id); if (result) { cr_count = (*result)[0].GetUInt32(); delete result; } if (m_session) { Player* pl = m_session->GetPlayer(); result = WorldDatabase.PQuery("SELECT guid, position_x, position_y, position_z, map, (POW(position_x - '%f', 2) + POW(position_y - '%f', 2) + POW(position_z - '%f', 2)) AS order_ FROM creature WHERE id = '%u' ORDER BY order_ ASC LIMIT %u", pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(), cr_id, uint32(count)); } else result = WorldDatabase.PQuery("SELECT guid, position_x, position_y, position_z, map FROM creature WHERE id = '%u' LIMIT %u", cr_id, uint32(count)); if (result) { do { Field* fields = result->Fetch(); uint32 guid = fields[0].GetUInt32(); float x = fields[1].GetFloat(); float y = fields[2].GetFloat(); float z = fields[3].GetFloat(); int mapid = fields[4].GetUInt16(); if (m_session) { PSendSysMessage(LANG_CREATURE_LIST_CHAT, guid, PrepareStringNpcOrGoSpawnInformation<Creature>(guid).c_str(), guid, cInfo->Name, x, y, z, mapid); } else { PSendSysMessage(LANG_CREATURE_LIST_CONSOLE, guid, PrepareStringNpcOrGoSpawnInformation<Creature>(guid).c_str(), cInfo->Name, x, y, z, mapid); } } while (result->NextRow()); delete result; } PSendSysMessage(LANG_COMMAND_LISTCREATUREMESSAGE, cr_id, cr_count); return true; } void ChatHandler::ShowItemListHelper(uint32 itemId, int loc_idx, Player* target /*=NULL*/) { ItemPrototype const* itemProto = sItemStorage.LookupEntry<ItemPrototype >(itemId); if (!itemProto) { return; } std::string name = itemProto->Name1; sObjectMgr.GetItemLocaleStrings(itemProto->ItemId, loc_idx, &name); char const* usableStr = ""; if (target) { if (target->CanUseItem(itemProto)) { usableStr = GetMangosString(LANG_COMMAND_ITEM_USABLE); } } if (m_session) { PSendSysMessage(LANG_ITEM_LIST_CHAT, itemId, itemId, name.c_str(), usableStr); } else { PSendSysMessage(LANG_ITEM_LIST_CONSOLE, itemId, name.c_str(), usableStr); } } bool ChatHandler::HandleLookupItemCommand(char* args) { if (!*args) { return false; } std::string namepart = args; std::wstring wnamepart; // converting string that we try to find to lower case if (!Utf8toWStr(namepart, wnamepart)) { return false; } wstrToLower(wnamepart); Player* pl = m_session ? m_session->GetPlayer() : NULL; uint32 counter = 0; // Search in `item_template` for (uint32 id = 0; id < sItemStorage.GetMaxEntry(); ++id) { ItemPrototype const* pProto = sItemStorage.LookupEntry<ItemPrototype >(id); if (!pProto) { continue; } int loc_idx = GetSessionDbLocaleIndex(); std::string name; // "" for let later only single time check default locale name directly sObjectMgr.GetItemLocaleStrings(id, loc_idx, &name); if ((name.empty() || !Utf8FitTo(name, wnamepart)) && !Utf8FitTo(pProto->Name1, wnamepart)) { continue; } ShowItemListHelper(id, loc_idx, pl); ++counter; } if (counter == 0) { SendSysMessage(LANG_COMMAND_NOITEMFOUND); } return true; } bool ChatHandler::HandleLookupItemSetCommand(char* args) { if (!*args) { return false; } std::string namepart = args; std::wstring wnamepart; if (!Utf8toWStr(namepart, wnamepart)) { return false; } // converting string that we try to find to lower case wstrToLower(wnamepart); uint32 counter = 0; // Counter for figure out that we found smth. // Search in ItemSet.dbc for (uint32 id = 0; id < sItemSetStore.GetNumRows(); ++id) { ItemSetEntry const* set = sItemSetStore.LookupEntry(id); if (set) { int loc = GetSessionDbcLocale(); std::string name = set->name[loc]; if (name.empty()) { continue; } if (!Utf8FitTo(name, wnamepart)) { loc = 0; for (; loc < MAX_LOCALE; ++loc) { if (loc == GetSessionDbcLocale()) { continue; } name = set->name[loc]; if (name.empty()) { continue; } if (Utf8FitTo(name, wnamepart)) { break; } } } if (loc < MAX_LOCALE) { // send item set in "id - [namedlink locale]" format if (m_session) { PSendSysMessage(LANG_ITEMSET_LIST_CHAT, id, id, name.c_str(), localeNames[loc]); } else { PSendSysMessage(LANG_ITEMSET_LIST_CONSOLE, id, name.c_str(), localeNames[loc]); } ++counter; } } } if (counter == 0) // if counter == 0 then we found nth { SendSysMessage(LANG_COMMAND_NOITEMSETFOUND); } return true; } bool ChatHandler::HandleLookupSkillCommand(char* args) { if (!*args) { return false; } // can be NULL in console call Player* target = getSelectedPlayer(); std::string namepart = args; std::wstring wnamepart; if (!Utf8toWStr(namepart, wnamepart)) { return false; } // converting string that we try to find to lower case wstrToLower(wnamepart); uint32 counter = 0; // Counter for figure out that we found smth. // Search in SkillLine.dbc for (uint32 id = 0; id < sSkillLineStore.GetNumRows(); ++id) { SkillLineEntry const* skillInfo = sSkillLineStore.LookupEntry(id); if (skillInfo) { int loc = GetSessionDbcLocale(); std::string name = skillInfo->name[loc]; if (name.empty()) { continue; } if (!Utf8FitTo(name, wnamepart)) { loc = 0; for (; loc < MAX_LOCALE; ++loc) { if (loc == GetSessionDbcLocale()) { continue; } name = skillInfo->name[loc]; if (name.empty()) { continue; } if (Utf8FitTo(name, wnamepart)) { break; } } } if (loc < MAX_LOCALE) { char valStr[50] = ""; char const* knownStr = ""; if (target && target->HasSkill(id)) { knownStr = GetMangosString(LANG_KNOWN); uint32 curValue = target->GetPureSkillValue(id); uint32 maxValue = target->GetPureMaxSkillValue(id); uint32 permValue = target->GetSkillPermBonusValue(id); uint32 tempValue = target->GetSkillTempBonusValue(id); char const* valFormat = GetMangosString(LANG_SKILL_VALUES); snprintf(valStr, 50, valFormat, curValue, maxValue, permValue, tempValue); } // send skill in "id - [namedlink locale]" format if (m_session) { PSendSysMessage(LANG_SKILL_LIST_CHAT, id, id, name.c_str(), localeNames[loc], knownStr, valStr); } else { PSendSysMessage(LANG_SKILL_LIST_CONSOLE, id, name.c_str(), localeNames[loc], knownStr, valStr); } ++counter; } } } if (counter == 0) // if counter == 0 then we found nth { SendSysMessage(LANG_COMMAND_NOSKILLFOUND); } return true; } void ChatHandler::ShowSpellListHelper(Player* target, SpellEntry const* spellInfo, LocaleConstant loc) { uint32 id = spellInfo->Id; bool known = target && target->HasSpell(id); bool learn = (spellInfo->Effect[EFFECT_INDEX_0] == SPELL_EFFECT_LEARN_SPELL); uint32 talentCost = GetTalentSpellCost(id); bool talent = (talentCost > 0); bool passive = IsPassiveSpell(spellInfo); bool active = target && target->HasAura(id); // unit32 used to prevent interpreting uint8 as char at output // find rank of learned spell for learning spell, or talent rank uint32 rank = talentCost ? talentCost : sSpellMgr.GetSpellRank(learn ? spellInfo->EffectTriggerSpell[EFFECT_INDEX_0] : id); // send spell in "id - [name, rank N] [talent] [passive] [learn] [known]" format std::ostringstream ss; if (m_session) { ss << id << " - |cffffffff|Hspell:" << id << "|h[" << spellInfo->SpellName[loc]; } else { ss << id << " - " << spellInfo->SpellName[loc]; } // include rank in link name if (rank) { ss << GetMangosString(LANG_SPELL_RANK) << rank; } if (m_session) { ss << " " << localeNames[loc] << "]|h|r"; } else { ss << " " << localeNames[loc]; } if (talent) { ss << GetMangosString(LANG_TALENT); } if (passive) { ss << GetMangosString(LANG_PASSIVE); } if (learn) { ss << GetMangosString(LANG_LEARN); } if (known) { ss << GetMangosString(LANG_KNOWN); } if (active) { ss << GetMangosString(LANG_ACTIVE); } SendSysMessage(ss.str().c_str()); } bool ChatHandler::HandleLookupSpellCommand(char* args) { if (!*args) { return false; } // can be NULL at console call Player* target = getSelectedPlayer(); std::string namepart = args; std::wstring wnamepart; if (!Utf8toWStr(namepart, wnamepart)) { return false; } // converting string that we try to find to lower case wstrToLower(wnamepart); uint32 counter = 0; // Counter for figure out that we found smth. // Search in Spell.dbc for (uint32 id = 0; id < sSpellStore.GetNumRows(); ++id) { SpellEntry const* spellInfo = sSpellStore.LookupEntry(id); if (spellInfo) { int loc = GetSessionDbcLocale(); std::string name = spellInfo->SpellName[loc]; if (name.empty()) { continue; } if (!Utf8FitTo(name, wnamepart)) { loc = 0; for (; loc < MAX_LOCALE; ++loc) { if (loc == GetSessionDbcLocale()) { continue; } name = spellInfo->SpellName[loc]; if (name.empty()) { continue; } if (Utf8FitTo(name, wnamepart)) { break; } } } if (loc < MAX_LOCALE) { ShowSpellListHelper(target, spellInfo, LocaleConstant(loc)); ++counter; } } } if (counter == 0) // if counter == 0 then we found nth { SendSysMessage(LANG_COMMAND_NOSPELLFOUND); } return true; } void ChatHandler::ShowQuestListHelper(uint32 questId, int32 loc_idx, Player* target /*= NULL*/) { Quest const* qinfo = sObjectMgr.GetQuestTemplate(questId); if (!qinfo) { return; } std::string title = qinfo->GetTitle(); sObjectMgr.GetQuestLocaleStrings(questId, loc_idx, &title); char const* statusStr = ""; if (target) { QuestStatus status = target->GetQuestStatus(qinfo->GetQuestId()); if (status == QUEST_STATUS_COMPLETE) { if (target->GetQuestRewardStatus(qinfo->GetQuestId())) { statusStr = GetMangosString(LANG_COMMAND_QUEST_REWARDED); } else { statusStr = GetMangosString(LANG_COMMAND_QUEST_COMPLETE); } } else if (status == QUEST_STATUS_INCOMPLETE) { statusStr = GetMangosString(LANG_COMMAND_QUEST_ACTIVE); } } if (m_session) { PSendSysMessage(LANG_QUEST_LIST_CHAT, qinfo->GetQuestId(), qinfo->GetQuestId(), qinfo->GetQuestLevel(), title.c_str(), statusStr); } else { PSendSysMessage(LANG_QUEST_LIST_CONSOLE, qinfo->GetQuestId(), title.c_str(), statusStr); } } bool ChatHandler::HandleLookupQuestCommand(char* args) { if (!*args) { return false; } // can be NULL at console call Player* target = getSelectedPlayer(); std::string namepart = args; std::wstring wnamepart; // converting string that we try to find to lower case if (!Utf8toWStr(namepart, wnamepart)) { return false; } wstrToLower(wnamepart); uint32 counter = 0 ; int loc_idx = GetSessionDbLocaleIndex(); ObjectMgr::QuestMap const& qTemplates = sObjectMgr.GetQuestTemplates(); for (ObjectMgr::QuestMap::const_iterator iter = qTemplates.begin(); iter != qTemplates.end(); ++iter) { Quest* qinfo = iter->second; std::string title; // "" for avoid repeating check default locale sObjectMgr.GetQuestLocaleStrings(qinfo->GetQuestId(), loc_idx, &title); if ((title.empty() || !Utf8FitTo(title, wnamepart)) && !Utf8FitTo(qinfo->GetTitle(), wnamepart)) { continue; } ShowQuestListHelper(qinfo->GetQuestId(), loc_idx, target); ++counter; } if (counter == 0) { SendSysMessage(LANG_COMMAND_NOQUESTFOUND); } return true; } bool ChatHandler::HandleLookupCreatureCommand(char* args) { if (!*args) { return false; } std::string namepart = args; std::wstring wnamepart; // converting string that we try to find to lower case if (!Utf8toWStr(namepart, wnamepart)) { return false; } wstrToLower(wnamepart); uint32 counter = 0; for (uint32 id = 0; id < sCreatureStorage.GetMaxEntry(); ++id) { CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo> (id); if (!cInfo) { continue; } int loc_idx = GetSessionDbLocaleIndex(); char const* name = ""; // "" for avoid repeating check for default locale sObjectMgr.GetCreatureLocaleStrings(id, loc_idx, &name); if (!*name || !Utf8FitTo(name, wnamepart)) { name = cInfo->Name; if (!Utf8FitTo(name, wnamepart)) { continue; } } if (m_session) { PSendSysMessage(LANG_CREATURE_ENTRY_LIST_CHAT, id, id, name); } else { PSendSysMessage(LANG_CREATURE_ENTRY_LIST_CONSOLE, id, name); } ++counter; } if (counter == 0) { SendSysMessage(LANG_COMMAND_NOCREATUREFOUND); } return true; } bool ChatHandler::HandleLookupObjectCommand(char* args) { if (!*args) { return false; } std::string namepart = args; std::wstring wnamepart; // converting string that we try to find to lower case if (!Utf8toWStr(namepart, wnamepart)) { return false; } wstrToLower(wnamepart); uint32 counter = 0; for (SQLStorageBase::SQLSIterator<GameObjectInfo> itr = sGOStorage.getDataBegin<GameObjectInfo>(); itr < sGOStorage.getDataEnd<GameObjectInfo>(); ++itr) { int loc_idx = GetSessionDbLocaleIndex(); if (loc_idx >= 0) { GameObjectLocale const* gl = sObjectMgr.GetGameObjectLocale(itr->id); if (gl) { if ((int32)gl->Name.size() > loc_idx && !gl->Name[loc_idx].empty()) { std::string name = gl->Name[loc_idx]; if (Utf8FitTo(name, wnamepart)) { if (m_session) { PSendSysMessage(LANG_GO_ENTRY_LIST_CHAT, itr->id, itr->id, name.c_str()); } else { PSendSysMessage(LANG_GO_ENTRY_LIST_CONSOLE, itr->id, name.c_str()); } ++counter; continue; } } } } std::string name = itr->name; if (name.empty()) { continue; } if (Utf8FitTo(name, wnamepart)) { if (m_session) { PSendSysMessage(LANG_GO_ENTRY_LIST_CHAT, itr->id, itr->id, name.c_str()); } else { PSendSysMessage(LANG_GO_ENTRY_LIST_CONSOLE, itr->id, name.c_str()); } ++counter; } } if (counter == 0) { SendSysMessage(LANG_COMMAND_NOGAMEOBJECTFOUND); } return true; } bool ChatHandler::HandleLookupTaxiNodeCommand(char* args) { if (!*args) { return false; } std::string namepart = args; std::wstring wnamepart; if (!Utf8toWStr(namepart, wnamepart)) { return false; } // converting string that we try to find to lower case wstrToLower(wnamepart); uint32 counter = 0; // Counter for figure out that we found smth. // Search in TaxiNodes.dbc for (uint32 id = 0; id < sTaxiNodesStore.GetNumRows(); ++id) { TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(id); if (nodeEntry) { int loc = GetSessionDbcLocale(); std::string name = nodeEntry->name[loc]; if (name.empty()) { continue; } if (!Utf8FitTo(name, wnamepart)) { loc = 0; for (; loc < MAX_LOCALE; ++loc) { if (loc == GetSessionDbcLocale()) { continue; } name = nodeEntry->name[loc]; if (name.empty()) { continue; } if (Utf8FitTo(name, wnamepart)) { break; } } } if (loc < MAX_LOCALE) { // send taxinode in "id - [name] (Map:m X:x Y:y Z:z)" format if (m_session) PSendSysMessage(LANG_TAXINODE_ENTRY_LIST_CHAT, id, id, name.c_str(), localeNames[loc], nodeEntry->map_id, nodeEntry->x, nodeEntry->y, nodeEntry->z); else PSendSysMessage(LANG_TAXINODE_ENTRY_LIST_CONSOLE, id, name.c_str(), localeNames[loc], nodeEntry->map_id, nodeEntry->x, nodeEntry->y, nodeEntry->z); ++counter; } } } if (counter == 0) // if counter == 0 then we found nth { SendSysMessage(LANG_COMMAND_NOTAXINODEFOUND); } return true; } /** \brief GM command level 3 - Create a guild. * * This command allows a GM (level 3) to create a guild. * * The "args" parameter contains the name of the guild leader * and then the name of the guild. * */ bool ChatHandler::HandleGuildCreateCommand(char* args) { // guildmaster name optional char* guildMasterStr = ExtractOptNotLastArg(&args); Player* target; if (!ExtractPlayerTarget(&guildMasterStr, &target)) { return false; } char* guildStr = ExtractQuotedArg(&args); if (!guildStr) { return false; } std::string guildname = guildStr; if (target->GetGuildId()) { SendSysMessage(LANG_PLAYER_IN_GUILD); return true; } Guild* guild = new Guild; if (!guild->Create(target, guildname)) { delete guild; SendSysMessage(LANG_GUILD_NOT_CREATED); SetSentErrorMessage(true); return false; } sGuildMgr.AddGuild(guild); return true; } bool ChatHandler::HandleGuildInviteCommand(char* args) { // player name optional char* nameStr = ExtractOptNotLastArg(&args); // if not guild name only (in "") then player name ObjectGuid target_guid; if (!ExtractPlayerTarget(&nameStr, NULL, &target_guid)) { return false; } char* guildStr = ExtractQuotedArg(&args); if (!guildStr) { return false; } std::string glName = guildStr; Guild* targetGuild = sGuildMgr.GetGuildByName(glName); if (!targetGuild) { return false; } // player's guild membership checked in AddMember before add if (!targetGuild->AddMember(target_guid, targetGuild->GetLowestRank())) { return false; } return true; } bool ChatHandler::HandleGuildUninviteCommand(char* args) { Player* target; ObjectGuid target_guid; if (!ExtractPlayerTarget(&args, &target, &target_guid)) { return false; } uint32 glId = target ? target->GetGuildId() : Player::GetGuildIdFromDB(target_guid); if (!glId) { return false; } Guild* targetGuild = sGuildMgr.GetGuildById(glId); if (!targetGuild) { return false; } if (targetGuild->DelMember(target_guid)) { targetGuild->Disband(); delete targetGuild; } return true; } bool ChatHandler::HandleGuildRankCommand(char* args) { char* nameStr = ExtractOptNotLastArg(&args); Player* target; ObjectGuid target_guid; std::string target_name; if (!ExtractPlayerTarget(&nameStr, &target, &target_guid, &target_name)) { return false; } uint32 glId = target ? target->GetGuildId() : Player::GetGuildIdFromDB(target_guid); if (!glId) { return false; } Guild* targetGuild = sGuildMgr.GetGuildById(glId); if (!targetGuild) { return false; } uint32 newrank; if (!ExtractUInt32(&args, newrank)) { return false; } if (newrank > targetGuild->GetLowestRank()) { return false; } MemberSlot* slot = targetGuild->GetMemberSlot(target_guid); if (!slot) { return false; } slot->ChangeRank(newrank); return true; } bool ChatHandler::HandleGuildDeleteCommand(char* args) { if (!*args) { return false; } char* guildStr = ExtractQuotedArg(&args); if (!guildStr) { return false; } std::string gld = guildStr; Guild* targetGuild = sGuildMgr.GetGuildByName(gld); if (!targetGuild) { return false; } targetGuild->Disband(); delete targetGuild; return true; } bool ChatHandler::HandleGetDistanceCommand(char* args) { WorldObject* obj = NULL; if (*args) { if (ObjectGuid guid = ExtractGuidFromLink(&args)) { obj = (WorldObject*)m_session->GetPlayer()->GetObjectByTypeMask(guid, TYPEMASK_CREATURE_OR_GAMEOBJECT); } if (!obj) { SendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } } else { obj = getSelectedUnit(); if (!obj) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } } Player* player = m_session->GetPlayer(); // Calculate point-to-point distance float dx, dy, dz; dx = player->GetPositionX() - obj->GetPositionX(); dy = player->GetPositionY() - obj->GetPositionY(); dz = player->GetPositionZ() - obj->GetPositionZ(); PSendSysMessage(LANG_DISTANCE, player->GetDistance(obj), player->GetDistance2d(obj), sqrt(dx * dx + dy * dy + dz * dz)); return true; } bool ChatHandler::HandleDieCommand(char* /*args*/) { Player* player = m_session->GetPlayer(); Unit* target = getSelectedUnit(); if (!target || !player->GetSelectionGuid()) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } if (target->GetTypeId() == TYPEID_PLAYER) { if (HasLowerSecurity((Player*)target, ObjectGuid(), false)) { return false; } } if (target->IsAlive()) { player->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); } return true; } bool ChatHandler::HandleDamageCommand(char* args) { if (!*args) { return false; } Unit* target = getSelectedUnit(); Player* player = m_session->GetPlayer(); if (!target || !player->GetSelectionGuid()) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } if (!target->IsAlive()) { return true; } int32 damage_int; if (!ExtractInt32(&args, damage_int)) { return false; } if (damage_int <= 0) { return true; } uint32 damage = damage_int; // flat melee damage without resistance/etc reduction if (!*args) { player->DealDamage(target, damage, NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); if (target != player) { player->SendAttackStateUpdate(HITINFO_NORMALSWING2, target, SPELL_SCHOOL_MASK_NORMAL, damage, 0, 0, VICTIMSTATE_NORMAL, 0); } return true; } uint32 school; if (!ExtractUInt32(&args, school)) { return false; } if (school >= MAX_SPELL_SCHOOL) { return false; } SpellSchoolMask schoolmask = SpellSchoolMask(1 << school); if (schoolmask & SPELL_SCHOOL_MASK_NORMAL) { damage = player->CalcArmorReducedDamage(target, damage); } // melee damage by specific school if (!*args) { uint32 absorb = 0; uint32 resist = 0; target->CalculateDamageAbsorbAndResist(player, schoolmask, SPELL_DIRECT_DAMAGE, damage, &absorb, &resist); if (damage <= absorb + resist) { return true; } damage -= absorb + resist; player->DealDamageMods(target, damage, &absorb); player->DealDamage(target, damage, NULL, DIRECT_DAMAGE, schoolmask, NULL, false); player->SendAttackStateUpdate(HITINFO_NORMALSWING2, target, schoolmask, damage, absorb, resist, VICTIMSTATE_NORMAL, 0); return true; } // non-melee damage // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spellid = ExtractSpellIdFromLink(&args); if (!spellid || !sSpellStore.LookupEntry(spellid)) { return false; } player->SpellNonMeleeDamageLog(target, spellid, damage); return true; } bool ChatHandler::HandleModifyArenaCommand(char* args) { if (!*args) return false; Player* target = getSelectedPlayer(); if (!target) { SendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } int32 amount = (int32)atoi(args); target->ModifyArenaPoints(amount); PSendSysMessage(LANG_COMMAND_MODIFY_ARENA, GetNameLink(target).c_str(), target->GetArenaPoints()); return true; } bool ChatHandler::HandleReviveCommand(char* args) { Player* target; ObjectGuid target_guid; if (!ExtractPlayerTarget(&args, &target, &target_guid)) { return false; } if (target) { target->ResurrectPlayer(0.5f); target->SpawnCorpseBones(); } else // will resurrected at login without corpse { sObjectAccessor.ConvertCorpseForPlayer(target_guid); } return true; } bool ChatHandler::HandleAuraCommand(char* args) { Unit* target = getSelectedUnit(); if (!target) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spellID = ExtractSpellIdFromLink(&args); SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellID); if (!spellInfo) { return false; } if (!IsSpellAppliesAura(spellInfo) && !IsSpellHaveEffect(spellInfo, SPELL_EFFECT_PERSISTENT_AREA_AURA)) { PSendSysMessage(LANG_SPELL_NO_HAVE_AURAS, spellID); SetSentErrorMessage(true); return false; } SpellAuraHolder* holder = CreateSpellAuraHolder(spellInfo, target, m_session->GetPlayer()); for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i) { uint8 eff = spellInfo->Effect[i]; if (eff >= TOTAL_SPELL_EFFECTS) { continue; } if (IsAreaAuraEffect(eff) || eff == SPELL_EFFECT_APPLY_AURA || eff == SPELL_EFFECT_PERSISTENT_AREA_AURA) { Aura* aur = CreateAura(spellInfo, SpellEffectIndex(i), NULL, holder, target); holder->AddAura(aur, SpellEffectIndex(i)); } } target->AddSpellAuraHolder(holder); return true; } bool ChatHandler::HandleUnAuraCommand(char* args) { Unit* target = getSelectedUnit(); if (!target) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } std::string argstr = args; if (argstr == "all") { target->RemoveAllAuras(); return true; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spellID = ExtractSpellIdFromLink(&args); if (!spellID) { return false; } target->RemoveAurasDueToSpell(spellID); return true; } bool ChatHandler::HandleLinkGraveCommand(char* args) { uint32 g_id; if (!ExtractUInt32(&args, g_id)) { return false; } char* teamStr = ExtractLiteralArg(&args); Team g_team; if (!teamStr) { g_team = TEAM_BOTH_ALLOWED; } else if (strncmp(teamStr, "horde", strlen(teamStr)) == 0) { g_team = HORDE; } else if (strncmp(teamStr, "alliance", strlen(teamStr)) == 0) { g_team = ALLIANCE; } else { return false; } WorldSafeLocsEntry const* graveyard = sWorldSafeLocsStore.LookupEntry(g_id); if (!graveyard) { PSendSysMessage(LANG_COMMAND_GRAVEYARDNOEXIST, g_id); SetSentErrorMessage(true); return false; } Player* player = m_session->GetPlayer(); uint32 zoneId = player->GetZoneId(); AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(zoneId); if (!areaEntry || areaEntry->zone != 0) { PSendSysMessage(LANG_COMMAND_GRAVEYARDWRONGZONE, g_id, zoneId); SetSentErrorMessage(true); return false; } if (sObjectMgr.AddGraveYardLink(g_id, zoneId, g_team)) { PSendSysMessage(LANG_COMMAND_GRAVEYARDLINKED, g_id, zoneId); } else { PSendSysMessage(LANG_COMMAND_GRAVEYARDALRLINKED, g_id, zoneId); } return true; } bool ChatHandler::HandleNearGraveCommand(char* args) { Team g_team; size_t argslen = strlen(args); if (!*args) { g_team = TEAM_BOTH_ALLOWED; } else if (strncmp(args, "horde", argslen) == 0) { g_team = HORDE; } else if (strncmp(args, "alliance", argslen) == 0) { g_team = ALLIANCE; } else { return false; } Player* player = m_session->GetPlayer(); uint32 zone_id = player->GetZoneId(); WorldSafeLocsEntry const* graveyard = sObjectMgr.GetClosestGraveYard(player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), player->GetMapId(), g_team); if (graveyard) { uint32 g_id = graveyard->ID; GraveYardData const* data = sObjectMgr.FindGraveYardData(g_id, zone_id); if (!data) { PSendSysMessage(LANG_COMMAND_GRAVEYARDERROR, g_id); SetSentErrorMessage(true); return false; } std::string team_name; if (data->team == TEAM_BOTH_ALLOWED) { team_name = GetMangosString(LANG_COMMAND_GRAVEYARD_ANY); } else if (data->team == HORDE) { team_name = GetMangosString(LANG_COMMAND_GRAVEYARD_HORDE); } else if (data->team == ALLIANCE) { team_name = GetMangosString(LANG_COMMAND_GRAVEYARD_ALLIANCE); } else // Actually, this case can not happen { team_name = GetMangosString(LANG_COMMAND_GRAVEYARD_NOTEAM); } PSendSysMessage(LANG_COMMAND_GRAVEYARDNEAREST, g_id, team_name.c_str(), zone_id); } else { std::string team_name; if (g_team == TEAM_BOTH_ALLOWED) { team_name = GetMangosString(LANG_COMMAND_GRAVEYARD_ANY); } else if (g_team == HORDE) { team_name = GetMangosString(LANG_COMMAND_GRAVEYARD_HORDE); } else if (g_team == ALLIANCE) { team_name = GetMangosString(LANG_COMMAND_GRAVEYARD_ALLIANCE); } if (g_team == TEAM_BOTH_ALLOWED) { PSendSysMessage(LANG_COMMAND_ZONENOGRAVEYARDS, zone_id); } else { PSendSysMessage(LANG_COMMAND_ZONENOGRAFACTION, zone_id, team_name.c_str()); } } return true; } //-----------------------Npc Commands----------------------- bool ChatHandler::HandleNpcAllowMovementCommand(char* /*args*/) { if (sWorld.getAllowMovement()) { sWorld.SetAllowMovement(false); SendSysMessage(LANG_CREATURE_MOVE_DISABLED); } else { sWorld.SetAllowMovement(true); SendSysMessage(LANG_CREATURE_MOVE_ENABLED); } return true; } bool ChatHandler::HandleNpcChangeEntryCommand(char* args) { if (!*args) { return false; } uint32 newEntryNum = atoi(args); if (!newEntryNum) { return false; } Unit* unit = getSelectedUnit(); if (!unit || unit->GetTypeId() != TYPEID_UNIT) { SendSysMessage(LANG_SELECT_CREATURE); SetSentErrorMessage(true); return false; } Creature* creature = (Creature*)unit; if (creature->UpdateEntry(newEntryNum)) { SendSysMessage(LANG_DONE); } else { SendSysMessage(LANG_ERROR); } return true; } bool ChatHandler::HandleNpcInfoCommand(char* /*args*/) { Creature* target = getSelectedCreature(); if (!target) { SendSysMessage(LANG_SELECT_CREATURE); SetSentErrorMessage(true); return false; } uint32 faction = target->getFaction(); uint32 npcflags = target->GetUInt32Value(UNIT_NPC_FLAGS); uint32 displayid = target->GetDisplayId(); uint32 nativeid = target->GetNativeDisplayId(); uint32 Entry = target->GetEntry(); CreatureInfo const* cInfo = target->GetCreatureInfo(); time_t curRespawnDelay = target->GetRespawnTimeEx() - time(NULL); if (curRespawnDelay < 0) { curRespawnDelay = 0; } std::string curRespawnDelayStr = secsToTimeString(curRespawnDelay, true); std::string defRespawnDelayStr = secsToTimeString(target->GetRespawnDelay(), true); // Send information dependend on difficulty mode CreatureInfo const* baseInfo = ObjectMgr::GetCreatureTemplate(Entry); uint32 diff = 1; for (; diff < MAX_DIFFICULTY; ++diff) if (baseInfo->DifficultyEntry[diff - 1] == target->GetCreatureInfo()->Entry) break; if (diff < MAX_DIFFICULTY) PSendSysMessage(LANG_NPCINFO_CHAR_DIFFICULTY, target->GetGuidStr().c_str(), faction, npcflags, Entry, target->GetCreatureInfo()->Entry, diff, displayid, nativeid); else PSendSysMessage(LANG_NPCINFO_CHAR, target->GetGuidStr().c_str(), faction, npcflags, Entry, displayid, nativeid); PSendSysMessage(LANG_NPCINFO_LEVEL, target->getLevel()); PSendSysMessage(LANG_NPCINFO_HEALTH, target->GetCreateHealth(), target->GetMaxHealth(), target->GetHealth()); PSendSysMessage(LANG_NPCINFO_FLAGS, target->GetUInt32Value(UNIT_FIELD_FLAGS), target->GetUInt32Value(UNIT_DYNAMIC_FLAGS), target->getFaction()); PSendSysMessage(LANG_COMMAND_RAWPAWNTIMES, defRespawnDelayStr.c_str(), curRespawnDelayStr.c_str()); PSendSysMessage(LANG_NPCINFO_LOOT, cInfo->LootId, cInfo->PickpocketLootId, cInfo->SkinningLootId); PSendSysMessage(LANG_NPCINFO_DUNGEON_ID, target->GetInstanceId()); PSendSysMessage(LANG_NPCINFO_POSITION, float(target->GetPositionX()), float(target->GetPositionY()), float(target->GetPositionZ())); if ((npcflags & UNIT_NPC_FLAG_VENDOR)) { SendSysMessage(LANG_NPCINFO_VENDOR); } if ((npcflags & UNIT_NPC_FLAG_TRAINER)) { SendSysMessage(LANG_NPCINFO_TRAINER); } ShowNpcOrGoSpawnInformation<Creature>(target->GetGUIDLow()); return true; } // play npc emote bool ChatHandler::HandleNpcPlayEmoteCommand(char* args) { uint32 emote = atoi(args); Creature* target = getSelectedCreature(); if (!target) { SendSysMessage(LANG_SELECT_CREATURE); SetSentErrorMessage(true); return false; } target->HandleEmote(emote); return true; } // TODO: NpcCommands that needs to be fixed : bool ChatHandler::HandleNpcAddWeaponCommand(char* /*args*/) { /*if (!*args) return false; ObjectGuid guid = m_session->GetPlayer()->GetSelectionGuid(); if (guid.IsEmpty()) { SendSysMessage(LANG_NO_SELECTION); return true; } Creature *pCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(), guid); if(!pCreature) { SendSysMessage(LANG_SELECT_CREATURE); return true; } char* pSlotID = strtok((char*)args, " "); if (!pSlotID) return false; char* pItemID = strtok(NULL, " "); if (!pItemID) return false; uint32 ItemID = atoi(pItemID); uint32 SlotID = atoi(pSlotID); ItemPrototype* tmpItem = ObjectMgr::GetItemPrototype(ItemID); bool added = false; if(tmpItem) { switch(SlotID) { case 1: pCreature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY, ItemID); added = true; break; case 2: pCreature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY_01, ItemID); added = true; break; case 3: pCreature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY_02, ItemID); added = true; break; default: PSendSysMessage(LANG_ITEM_SLOT_NOT_EXIST,SlotID); added = false; break; } if(added) PSendSysMessage(LANG_ITEM_ADDED_TO_SLOT,ItemID,tmpItem->Name1,SlotID); } else { PSendSysMessage(LANG_ITEM_NOT_FOUND,ItemID); return true; } */ return true; } //---------------------------------------------------------- bool ChatHandler::HandleExploreCheatCommand(char* args) { if (!*args) { return false; } int flag = atoi(args); Player* chr = getSelectedPlayer(); if (chr == NULL) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } if (flag != 0) { PSendSysMessage(LANG_YOU_SET_EXPLORE_ALL, GetNameLink(chr).c_str()); if (needReportToTarget(chr)) { ChatHandler(chr).PSendSysMessage(LANG_YOURS_EXPLORE_SET_ALL, GetNameLink().c_str()); } } else { PSendSysMessage(LANG_YOU_SET_EXPLORE_NOTHING, GetNameLink(chr).c_str()); if (needReportToTarget(chr)) { ChatHandler(chr).PSendSysMessage(LANG_YOURS_EXPLORE_SET_NOTHING, GetNameLink().c_str()); } } for (uint8 i = 0; i < PLAYER_EXPLORED_ZONES_SIZE; ++i) { if (flag != 0) { m_session->GetPlayer()->SetFlag(PLAYER_EXPLORED_ZONES_1 + i, 0xFFFFFFFF); } else { m_session->GetPlayer()->SetFlag(PLAYER_EXPLORED_ZONES_1 + i, 0); } } return true; } void ChatHandler::HandleCharacterLevel(Player* player, ObjectGuid player_guid, uint32 oldlevel, uint32 newlevel) { if (player) { player->GiveLevel(newlevel); player->InitTalentForLevel(); player->SetUInt32Value(PLAYER_XP, 0); if (needReportToTarget(player)) { if (oldlevel == newlevel) { ChatHandler(player).PSendSysMessage(LANG_YOURS_LEVEL_PROGRESS_RESET, GetNameLink().c_str()); } else if (oldlevel < newlevel) { ChatHandler(player).PSendSysMessage(LANG_YOURS_LEVEL_UP, GetNameLink().c_str(), newlevel); } else // if(oldlevel > newlevel) { ChatHandler(player).PSendSysMessage(LANG_YOURS_LEVEL_DOWN, GetNameLink().c_str(), newlevel); } } } else { // update level and XP at level, all other will be updated at loading CharacterDatabase.PExecute("UPDATE characters SET level = '%u', xp = 0 WHERE guid = '%u'", newlevel, player_guid.GetCounter()); } } bool ChatHandler::HandleCharacterLevelCommand(char* args) { char* nameStr = ExtractOptNotLastArg(&args); int32 newlevel; bool nolevel = false; // exception opt second arg: .character level $name if (!ExtractInt32(&args, newlevel)) { if (!nameStr) { nameStr = ExtractArg(&args); if (!nameStr) { return false; } nolevel = true; } else { return false; } } Player* target; ObjectGuid target_guid; std::string target_name; if (!ExtractPlayerTarget(&nameStr, &target, &target_guid, &target_name)) { return false; } int32 oldlevel = target ? target->getLevel() : Player::GetLevelFromDB(target_guid); if (nolevel) { newlevel = oldlevel; } if (newlevel < 1) { return false; } // invalid level if (newlevel > STRONG_MAX_LEVEL) // hardcoded maximum level { newlevel = STRONG_MAX_LEVEL; } HandleCharacterLevel(target, target_guid, oldlevel, newlevel); if (!m_session || m_session->GetPlayer() != target) // including player==NULL { std::string nameLink = playerLink(target_name); PSendSysMessage(LANG_YOU_CHANGE_LVL, nameLink.c_str(), newlevel); } return true; } bool ChatHandler::HandleLevelUpCommand(char* args) { int32 addlevel = 1; char* nameStr = NULL; if (*args) { nameStr = ExtractOptNotLastArg(&args); // exception opt second arg: .levelup $name if (!ExtractInt32(&args, addlevel)) { if (!nameStr) { nameStr = ExtractArg(&args); } else { return false; } } } Player* target; ObjectGuid target_guid; std::string target_name; if (!ExtractPlayerTarget(&nameStr, &target, &target_guid, &target_name)) { return false; } int32 oldlevel = target ? target->getLevel() : Player::GetLevelFromDB(target_guid); int32 newlevel = oldlevel + addlevel; if (newlevel < 1) { newlevel = 1; } if (newlevel > STRONG_MAX_LEVEL) // hardcoded maximum level { newlevel = STRONG_MAX_LEVEL; } HandleCharacterLevel(target, target_guid, oldlevel, newlevel); if (!m_session || m_session->GetPlayer() != target) // including chr==NULL { std::string nameLink = playerLink(target_name); PSendSysMessage(LANG_YOU_CHANGE_LVL, nameLink.c_str(), newlevel); } return true; } bool ChatHandler::HandleShowAreaCommand(char* args) { if (!*args) { return false; } Player* chr = getSelectedPlayer(); if (chr == NULL) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } int area = GetAreaFlagByAreaID(atoi(args)); int offset = area / 32; uint32 val = (uint32)(1 << (area % 32)); if (area < 0 || offset >= PLAYER_EXPLORED_ZONES_SIZE) { SendSysMessage(LANG_BAD_VALUE); SetSentErrorMessage(true); return false; } uint32 currFields = chr->GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset); chr->SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val)); SendSysMessage(LANG_EXPLORE_AREA); return true; } bool ChatHandler::HandleHideAreaCommand(char* args) { if (!*args) { return false; } Player* chr = getSelectedPlayer(); if (chr == NULL) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } int area = GetAreaFlagByAreaID(atoi(args)); int offset = area / 32; uint32 val = (uint32)(1 << (area % 32)); if (area < 0 || offset >= PLAYER_EXPLORED_ZONES_SIZE) { SendSysMessage(LANG_BAD_VALUE); SetSentErrorMessage(true); return false; } uint32 currFields = chr->GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset); chr->SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields ^ val)); SendSysMessage(LANG_UNEXPLORE_AREA); return true; } bool ChatHandler::HandleAuctionAllianceCommand(char* /*args*/) { m_session->GetPlayer()->SetAuctionAccessMode(m_session->GetPlayer()->GetTeam() != ALLIANCE ? -1 : 0); m_session->SendAuctionHello(m_session->GetPlayer()); return true; } bool ChatHandler::HandleAuctionHordeCommand(char* /*args*/) { m_session->GetPlayer()->SetAuctionAccessMode(m_session->GetPlayer()->GetTeam() != HORDE ? -1 : 0); m_session->SendAuctionHello(m_session->GetPlayer()); return true; } bool ChatHandler::HandleAuctionGoblinCommand(char* /*args*/) { m_session->GetPlayer()->SetAuctionAccessMode(1); m_session->SendAuctionHello(m_session->GetPlayer()); return true; } bool ChatHandler::HandleAuctionCommand(char* /*args*/) { m_session->GetPlayer()->SetAuctionAccessMode(0); m_session->SendAuctionHello(m_session->GetPlayer()); return true; } bool ChatHandler::HandleAuctionItemCommand(char* args) { // format: (alliance|horde|goblin) item[:count] price [buyout] [short|long|verylong] char* typeStr = ExtractLiteralArg(&args); if (!typeStr) { return false; } uint32 houseid; if (strncmp(typeStr, "alliance", strlen(typeStr)) == 0) { houseid = 1; } else if (strncmp(typeStr, "horde", strlen(typeStr)) == 0) { houseid = 6; } else if (strncmp(typeStr, "goblin", strlen(typeStr)) == 0) { houseid = 7; } else { return false; } // parse item str char* itemStr = ExtractArg(&args); if (!itemStr) { return false; } uint32 item_id = 0; uint32 item_count = 1; if (sscanf(itemStr, "%u:%u", &item_id, &item_count) != 2) if (sscanf(itemStr, "%u", &item_id) != 1) { return false; } uint32 price; if (!ExtractUInt32(&args, price)) { return false; } uint32 buyout; if (!ExtractOptUInt32(&args, buyout, 0)) { return false; } uint32 etime = 4 * MIN_AUCTION_TIME; if (char* timeStr = ExtractLiteralArg(&args)) { if (strncmp(timeStr, "short", strlen(timeStr)) == 0) { etime = 1 * MIN_AUCTION_TIME; } else if (strncmp(timeStr, "long", strlen(timeStr)) == 0) { etime = 2 * MIN_AUCTION_TIME; } else if (strncmp(timeStr, "verylong", strlen(timeStr)) == 0) { etime = 4 * MIN_AUCTION_TIME; } else { return false; } } AuctionHouseEntry const* auctionHouseEntry = sAuctionHouseStore.LookupEntry(houseid); AuctionHouseObject* auctionHouse = sAuctionMgr.GetAuctionsMap(auctionHouseEntry); if (!item_id) { PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, item_id); SetSentErrorMessage(true); return false; } ItemPrototype const* item_proto = ObjectMgr::GetItemPrototype(item_id); if (!item_proto) { PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, item_id); SetSentErrorMessage(true); return false; } if (item_count < 1 || (item_proto->MaxCount > 0 && item_count > uint32(item_proto->MaxCount))) { PSendSysMessage(LANG_COMMAND_INVALID_ITEM_COUNT, item_count, item_id); SetSentErrorMessage(true); return false; } do { uint32 item_stack = item_count > item_proto->GetMaxStackSize() ? item_proto->GetMaxStackSize() : item_count; item_count -= item_stack; Item* newItem = Item::CreateItem(item_id, item_stack); MANGOS_ASSERT(newItem); auctionHouse->AddAuction(auctionHouseEntry, newItem, etime, price, buyout); } while (item_count); return true; } bool ChatHandler::HandleBankCommand(char* /*args*/) { m_session->SendShowBank(m_session->GetPlayer()->GetObjectGuid()); return true; } bool ChatHandler::HandleMailBoxCommand(char* /*args*/) { m_session->SendShowMailBox(m_session->GetPlayer()->GetObjectGuid()); return true; } bool ChatHandler::HandleStableCommand(char* /*args*/) { m_session->SendStablePet(m_session->GetPlayer()->GetObjectGuid()); return true; } bool ChatHandler::HandleChangeWeatherCommand(char* args) { // Weather is OFF if (!sWorld.getConfig(CONFIG_BOOL_WEATHER)) { SendSysMessage(LANG_WEATHER_DISABLED); SetSentErrorMessage(true); return false; } uint32 type; if (!ExtractUInt32(&args, type)) { return false; } // see enum WeatherType if (!Weather::IsValidWeatherType(type)) { return false; } float grade; if (!ExtractFloat(&args, grade)) { return false; } // 0 to 1, sending -1 is instant good weather if (grade < 0.0f || grade > 1.0f) { return false; } Player* player = m_session->GetPlayer(); uint32 zoneId = player->GetZoneId(); if (!sWeatherMgr.GetWeatherChances(zoneId)) { SendSysMessage(LANG_NO_WEATHER); SetSentErrorMessage(true); } player->GetMap()->SetWeather(zoneId, (WeatherType)type, grade, false); return true; } bool ChatHandler::HandleTeleAddCommand(char* args) { if (!*args) { return false; } Player* player = m_session->GetPlayer(); if (!player) { return false; } std::string name = args; if (sObjectMgr.GetGameTele(name)) { SendSysMessage(LANG_COMMAND_TP_ALREADYEXIST); SetSentErrorMessage(true); return false; } GameTele tele; tele.position_x = player->GetPositionX(); tele.position_y = player->GetPositionY(); tele.position_z = player->GetPositionZ(); tele.orientation = player->GetOrientation(); tele.mapId = player->GetMapId(); tele.name = name; if (sObjectMgr.AddGameTele(tele)) { SendSysMessage(LANG_COMMAND_TP_ADDED); } else { SendSysMessage(LANG_COMMAND_TP_ADDEDERR); SetSentErrorMessage(true); return false; } return true; } bool ChatHandler::HandleTeleDelCommand(char* args) { if (!*args) { return false; } std::string name = args; if (!sObjectMgr.DeleteGameTele(name)) { SendSysMessage(LANG_COMMAND_TELE_NOTFOUND); SetSentErrorMessage(true); return false; } SendSysMessage(LANG_COMMAND_TP_DELETED); return true; } bool ChatHandler::HandleListAurasCommand(char* /*args*/) { Unit* unit = getSelectedUnit(); if (!unit) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } char const* talentStr = GetMangosString(LANG_TALENT); char const* passiveStr = GetMangosString(LANG_PASSIVE); Unit::SpellAuraHolderMap const& uAuras = unit->GetSpellAuraHolderMap(); PSendSysMessage(LANG_COMMAND_TARGET_LISTAURAS, uAuras.size()); for (Unit::SpellAuraHolderMap::const_iterator itr = uAuras.begin(); itr != uAuras.end(); ++itr) { bool talent = GetTalentSpellCost(itr->second->GetId()) > 0; SpellAuraHolder* holder = itr->second; char const* name = holder->GetSpellProto()->SpellName[GetSessionDbcLocale()]; for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { Aura* aur = holder->GetAuraByEffectIndex(SpellEffectIndex(i)); if (!aur) { continue; } if (m_session) { std::ostringstream ss_name; ss_name << "|cffffffff|Hspell:" << itr->second->GetId() << "|h[" << name << "]|h|r"; PSendSysMessage(LANG_COMMAND_TARGET_AURADETAIL, holder->GetId(), aur->GetEffIndex(), aur->GetModifier()->m_auraname, aur->GetAuraDuration(), aur->GetAuraMaxDuration(), ss_name.str().c_str(), (holder->IsPassive() ? passiveStr : ""), (talent ? talentStr : ""), holder->GetCasterGuid().GetString().c_str()); } else { PSendSysMessage(LANG_COMMAND_TARGET_AURADETAIL, holder->GetId(), aur->GetEffIndex(), aur->GetModifier()->m_auraname, aur->GetAuraDuration(), aur->GetAuraMaxDuration(), name, (holder->IsPassive() ? passiveStr : ""), (talent ? talentStr : ""), holder->GetCasterGuid().GetString().c_str()); } } } for (int i = 0; i < TOTAL_AURAS; ++i) { Unit::AuraList const& uAuraList = unit->GetAurasByType(AuraType(i)); if (uAuraList.empty()) { continue; } PSendSysMessage(LANG_COMMAND_TARGET_LISTAURATYPE, uAuraList.size(), i); for (Unit::AuraList::const_iterator itr = uAuraList.begin(); itr != uAuraList.end(); ++itr) { bool talent = GetTalentSpellCost((*itr)->GetId()) > 0; char const* name = (*itr)->GetSpellProto()->SpellName[GetSessionDbcLocale()]; if (m_session) { std::ostringstream ss_name; ss_name << "|cffffffff|Hspell:" << (*itr)->GetId() << "|h[" << name << "]|h|r"; PSendSysMessage(LANG_COMMAND_TARGET_AURASIMPLE, (*itr)->GetId(), (*itr)->GetEffIndex(), ss_name.str().c_str(), ((*itr)->GetHolder()->IsPassive() ? passiveStr : ""), (talent ? talentStr : ""), (*itr)->GetCasterGuid().GetString().c_str()); } else { PSendSysMessage(LANG_COMMAND_TARGET_AURASIMPLE, (*itr)->GetId(), (*itr)->GetEffIndex(), name, ((*itr)->GetHolder()->IsPassive() ? passiveStr : ""), (talent ? talentStr : ""), (*itr)->GetCasterGuid().GetString().c_str()); } } } return true; } bool ChatHandler::HandleListTalentsCommand(char* /*args*/) { Player* player = getSelectedPlayer(); if (!player) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } SendSysMessage(LANG_LIST_TALENTS_TITLE); uint32 count = 0; uint32 cost = 0; PlayerSpellMap const& uSpells = player->GetSpellMap(); for (PlayerSpellMap::const_iterator itr = uSpells.begin(); itr != uSpells.end(); ++itr) { if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.disabled) { continue; } uint32 cost_itr = GetTalentSpellCost(itr->first); if (cost_itr == 0) { continue; } SpellEntry const* spellEntry = sSpellStore.LookupEntry(itr->first); if (!spellEntry) { continue; } ShowSpellListHelper(player, spellEntry, GetSessionDbcLocale()); ++count; cost += cost_itr; } PSendSysMessage(LANG_LIST_TALENTS_COUNT, count, cost); return true; } bool ChatHandler::HandleResetAchievementsCommand(char* args) { Player* target; ObjectGuid target_guid; if (!ExtractPlayerTarget(&args, &target, &target_guid)) return false; if (target) target->GetAchievementMgr().Reset(); else AchievementMgr::DeleteFromDB(target_guid); return true; } bool ChatHandler::HandleResetHonorCommand(char* args) { Player* target; if (!ExtractPlayerTarget(&args, &target)) { return false; } target->SetHonorPoints(0); target->SetUInt32Value(PLAYER_FIELD_KILLS, 0); target->SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0); target->SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0); target->SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0); target->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL); return true; } static bool HandleResetStatsOrLevelHelper(Player* player) { ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(player->getClass()); if (!cEntry) { sLog.outError("Class %u not found in DBC (Wrong DBC files?)", player->getClass()); return false; } uint8 powertype = cEntry->powerType; // reset m_form if no aura if (!player->HasAuraType(SPELL_AURA_MOD_SHAPESHIFT)) { player->SetShapeshiftForm(FORM_NONE); } player->SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE); player->SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f); player->setFactionForRace(player->getRace()); player->SetByteValue(UNIT_FIELD_BYTES_0, 3, powertype); // reset only if player not in some form; if (player->GetShapeshiftForm() == FORM_NONE) { player->InitDisplayIds(); } player->SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP); player->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE); //-1 is default value player->SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, -1); // player->SetUInt32Value(PLAYER_FIELD_BYTES, 0xEEE00000 ); return true; } bool ChatHandler::HandleResetLevelCommand(char* args) { Player* target; if (!ExtractPlayerTarget(&args, &target)) { return false; } if (!HandleResetStatsOrLevelHelper(target)) { return false; } // set starting level uint32 start_level = target->getClass() != CLASS_DEATH_KNIGHT ? sWorld.getConfig(CONFIG_UINT32_START_PLAYER_LEVEL) : sWorld.getConfig(CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL); target->_ApplyAllLevelScaleItemMods(false); target->SetLevel(start_level); target->InitRunes(); target->InitStatsForLevel(true); target->InitTaxiNodesForLevel(); target->InitGlyphsForLevel(); target->InitTalentForLevel(); target->SetUInt32Value(PLAYER_XP, 0); target->_ApplyAllLevelScaleItemMods(true); // reset level for pet if (Pet* pet = target->GetPet()) { pet->SynchronizeLevelWithOwner(); } return true; } bool ChatHandler::HandleResetStatsCommand(char* args) { Player* target; if (!ExtractPlayerTarget(&args, &target)) { return false; } if (!HandleResetStatsOrLevelHelper(target)) { return false; } target->InitRunes(); target->InitStatsForLevel(true); target->InitTaxiNodesForLevel(); target->InitGlyphsForLevel(); target->InitTalentForLevel(); return true; } bool ChatHandler::HandleResetSpellsCommand(char* args) { Player* target; ObjectGuid target_guid; std::string target_name; if (!ExtractPlayerTarget(&args, &target, &target_guid, &target_name)) { return false; } if (target) { target->resetSpells(); ChatHandler(target).SendSysMessage(LANG_RESET_SPELLS); if (!m_session || m_session->GetPlayer() != target) { PSendSysMessage(LANG_RESET_SPELLS_ONLINE, GetNameLink(target).c_str()); } } else { CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid = '%u'", uint32(AT_LOGIN_RESET_SPELLS), target_guid.GetCounter()); PSendSysMessage(LANG_RESET_SPELLS_OFFLINE, target_name.c_str()); } return true; } bool ChatHandler::HandleResetSpecsCommand(char* args) { Player* target; ObjectGuid target_guid; std::string target_name; if (!ExtractPlayerTarget(&args, &target, &target_guid, &target_name)) { return false; } if (target) { target->resetTalents(true, true); target->SendTalentsInfoData(false); ChatHandler(target).SendSysMessage(LANG_RESET_TALENTS); if (!m_session || m_session->GetPlayer() != target) { PSendSysMessage(LANG_RESET_TALENTS_ONLINE, GetNameLink(target).c_str()); } Pet* pet = target->GetPet(); Pet::resetTalentsForAllPetsOf(target, pet); if (pet) target->SendTalentsInfoData(true); return true; } else if (target_guid) { uint32 at_flags = AT_LOGIN_RESET_TALENTS | AT_LOGIN_RESET_PET_TALENTS; CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid = '%u'", at_flags, target_guid.GetCounter()); std::string nameLink = playerLink(target_name); PSendSysMessage(LANG_RESET_TALENTS_OFFLINE, nameLink.c_str()); return true; } SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } bool ChatHandler::HandleResetTalentsCommand(char* args) { Player* target; std::string target_name; if (!ExtractPlayerTarget(&args, &target, NULL, &target_name)) { // Try reset talents as Hunter Pet Creature* creature = getSelectedCreature(); if (!*args && creature && creature->IsPet()) { Unit* owner = creature->GetOwner(); if (owner && owner->GetTypeId() == TYPEID_PLAYER && ((Pet*)creature)->IsPermanentPetFor((Player*)owner)) { ((Pet*)creature)->resetTalents(true); ((Player*)owner)->SendTalentsInfoData(true); ChatHandler((Player*)owner).SendSysMessage(LANG_RESET_PET_TALENTS); if (!m_session || m_session->GetPlayer() != ((Player*)owner)) PSendSysMessage(LANG_RESET_PET_TALENTS_ONLINE, GetNameLink((Player*)owner).c_str()); } return true; } SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } if (target) { target->resetTalents(true); target->SendTalentsInfoData(false); ChatHandler(target).SendSysMessage(LANG_RESET_TALENTS); if (!m_session || m_session->GetPlayer() != target) PSendSysMessage(LANG_RESET_TALENTS_ONLINE, GetNameLink(target).c_str()); Pet* pet = target->GetPet(); Pet::resetTalentsForAllPetsOf(target, pet); if (pet) target->SendTalentsInfoData(true); return true; } SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } bool ChatHandler::HandleResetAllCommand(char* args) { if (!*args) { return false; } std::string casename = args; AtLoginFlags atLogin; // Command specially created as single command to prevent using short case names if (casename == "spells") { atLogin = AT_LOGIN_RESET_SPELLS; sWorld.SendWorldText(LANG_RESETALL_SPELLS); if (!m_session) { SendSysMessage(LANG_RESETALL_SPELLS); } } else if (casename == "talents") { atLogin = AtLoginFlags(AT_LOGIN_RESET_TALENTS | AT_LOGIN_RESET_PET_TALENTS); sWorld.SendWorldText(LANG_RESETALL_TALENTS); if (!m_session) { SendSysMessage(LANG_RESETALL_TALENTS); } } else { PSendSysMessage(LANG_RESETALL_UNKNOWN_CASE, args); SetSentErrorMessage(true); return false; } CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE (at_login & '%u') = '0'", atLogin, atLogin); HashMapHolder<Player>::MapType const& plist = sObjectAccessor.GetPlayers(); for (HashMapHolder<Player>::MapType::const_iterator itr = plist.begin(); itr != plist.end(); ++itr) { itr->second->SetAtLoginFlag(atLogin); } return true; } bool ChatHandler::HandleServerShutDownCancelCommand(char* /*args*/) { sWorld.ShutdownCancel(); return true; } bool ChatHandler::HandleServerShutDownCommand(char* args) { uint32 delay; if (!ExtractUInt32(&args, delay)) return false; uint32 exitcode; if (!ExtractOptUInt32(&args, exitcode, SHUTDOWN_EXIT_CODE)) return false; // Exit code should be in range of 0-125, 126-255 is used // in many shells for their own return codes and code > 255 // is not supported in many others if (exitcode > 125) return false; sWorld.ShutdownServ(delay, 0, exitcode); return true; } bool ChatHandler::HandleServerRestartCommand(char* args) { uint32 delay; if (!ExtractUInt32(&args, delay)) { return false; } uint32 exitcode; if (!ExtractOptUInt32(&args, exitcode, RESTART_EXIT_CODE)) { return false; } // Exit code should be in range of 0-125, 126-255 is used // in many shells for their own return codes and code > 255 // is not supported in many others if (exitcode > 125) { return false; } sWorld.ShutdownServ(delay, SHUTDOWN_MASK_RESTART, exitcode); return true; } bool ChatHandler::HandleServerIdleRestartCommand(char* args) { uint32 delay; if (!ExtractUInt32(&args, delay)) return false; uint32 exitcode; if (!ExtractOptUInt32(&args, exitcode, RESTART_EXIT_CODE)) return false; // Exit code should be in range of 0-125, 126-255 is used // in many shells for their own return codes and code > 255 // is not supported in many others if (exitcode > 125) return false; sWorld.ShutdownServ(delay, SHUTDOWN_MASK_RESTART | SHUTDOWN_MASK_IDLE, exitcode); return true; } bool ChatHandler::HandleServerIdleShutDownCommand(char* args) { uint32 delay; if (!ExtractUInt32(&args, delay)) return false; uint32 exitcode; if (!ExtractOptUInt32(&args, exitcode, SHUTDOWN_EXIT_CODE)) return false; // Exit code should be in range of 0-125, 126-255 is used // in many shells for their own return codes and code > 255 // is not supported in many others if (exitcode > 125) return false; sWorld.ShutdownServ(delay, SHUTDOWN_MASK_IDLE, exitcode); return true; } bool ChatHandler::HandleQuestAddCommand(char* args) { Player* player = getSelectedPlayer(); if (!player) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } // .addquest #entry' // number or [name] Shift-click form |color|Hquest:quest_id:quest_level|h[name]|h|r uint32 entry; if (!ExtractUint32KeyFromLink(&args, "Hquest", entry)) { return false; } Quest const* pQuest = sObjectMgr.GetQuestTemplate(entry); if (!pQuest) { PSendSysMessage(LANG_COMMAND_QUEST_NOTFOUND, entry); SetSentErrorMessage(true); return false; } // check item starting quest (it can work incorrectly if added without item in inventory) for (uint32 id = 0; id < sItemStorage.GetMaxEntry(); ++id) { ItemPrototype const* pProto = sItemStorage.LookupEntry<ItemPrototype>(id); if (!pProto) { continue; } if (pProto->StartQuest == entry) { PSendSysMessage(LANG_COMMAND_QUEST_STARTFROMITEM, entry, pProto->ItemId); SetSentErrorMessage(true); return false; } } // ok, normal (creature/GO starting) quest if (player->CanAddQuest(pQuest, true)) { player->AddQuest(pQuest, NULL); if (player->CanCompleteQuest(entry)) { player->CompleteQuest(entry); } } return true; } bool ChatHandler::HandleQuestRemoveCommand(char* args) { Player* player = getSelectedPlayer(); if (!player) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } // .removequest #entry' // number or [name] Shift-click form |color|Hquest:quest_id:quest_level|h[name]|h|r uint32 entry; if (!ExtractUint32KeyFromLink(&args, "Hquest", entry)) { return false; } Quest const* pQuest = sObjectMgr.GetQuestTemplate(entry); if (!pQuest) { PSendSysMessage(LANG_COMMAND_QUEST_NOTFOUND, entry); SetSentErrorMessage(true); return false; } // remove all quest entries for 'entry' from quest log for (uint8 slot = 0; slot < MAX_QUEST_LOG_SIZE; ++slot) { uint32 quest = player->GetQuestSlotQuestId(slot); if (quest == entry) { player->SetQuestSlot(slot, 0); // we ignore unequippable quest items in this case, its' still be equipped player->TakeQuestSourceItem(quest, false); } } // set quest status to not started (will updated in DB at next save) player->SetQuestStatus(entry, QUEST_STATUS_NONE); // reset rewarded for restart repeatable quest player->getQuestStatusMap()[entry].m_rewarded = false; SendSysMessage(LANG_COMMAND_QUEST_REMOVED); return true; } bool ChatHandler::HandleQuestCompleteCommand(char* args) { Player* player = getSelectedPlayer(); if (!player) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } // .quest complete #entry // number or [name] Shift-click form |color|Hquest:quest_id:quest_level|h[name]|h|r uint32 entry; if (!ExtractUint32KeyFromLink(&args, "Hquest", entry)) { return false; } Quest const* pQuest = sObjectMgr.GetQuestTemplate(entry); // If player doesn't have the quest if (!pQuest || player->GetQuestStatus(entry) == QUEST_STATUS_NONE) { PSendSysMessage(LANG_COMMAND_QUEST_NOTFOUND, entry); SetSentErrorMessage(true); return false; } // Add quest items for quests that require items for (uint8 x = 0; x < QUEST_ITEM_OBJECTIVES_COUNT; ++x) { uint32 id = pQuest->ReqItemId[x]; uint32 count = pQuest->ReqItemCount[x]; if (!id || !count) { continue; } uint32 curItemCount = player->GetItemCount(id, true); ItemPosCountVec dest; uint8 msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, id, count - curItemCount); if (msg == EQUIP_ERR_OK) { Item* item = player->StoreNewItem(dest, id, true); player->SendNewItem(item, count - curItemCount, true, false); } } // All creature/GO slain/casted (not required, but otherwise it will display "Creature slain 0/10") for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i) { int32 creature = pQuest->ReqCreatureOrGOId[i]; uint32 creaturecount = pQuest->ReqCreatureOrGOCount[i]; if (uint32 spell_id = pQuest->ReqSpell[i]) { for (uint16 z = 0; z < creaturecount; ++z) { player->CastedCreatureOrGO(creature, ObjectGuid(), spell_id); } } else if (creature > 0) { if (CreatureInfo const* cInfo = ObjectMgr::GetCreatureTemplate(creature)) for (uint16 z = 0; z < creaturecount; ++z) { player->KilledMonster(cInfo, ObjectGuid()); } } else if (creature < 0) { for (uint16 z = 0; z < creaturecount; ++z) { player->CastedCreatureOrGO(-creature, ObjectGuid(), 0); } } } // If the quest requires reputation to complete if (uint32 repFaction = pQuest->GetRepObjectiveFaction()) { uint32 repValue = pQuest->GetRepObjectiveValue(); uint32 curRep = player->GetReputationMgr().GetReputation(repFaction); if (curRep < repValue) if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(repFaction)) { player->GetReputationMgr().SetReputation(factionEntry, repValue); } } // If the quest requires money int32 ReqOrRewMoney = pQuest->GetRewOrReqMoney(); if (ReqOrRewMoney < 0) { player->ModifyMoney(-ReqOrRewMoney); } player->CompleteQuest(entry); return true; } bool ChatHandler::HandleBanAccountCommand(char* args) { return HandleBanHelper(BAN_ACCOUNT, args); } bool ChatHandler::HandleBanCharacterCommand(char* args) { return HandleBanHelper(BAN_CHARACTER, args); } bool ChatHandler::HandleBanIPCommand(char* args) { return HandleBanHelper(BAN_IP, args); } bool ChatHandler::HandleBanHelper(BanMode mode, char* args) { if (!*args) { return false; } char* cnameOrIP = ExtractArg(&args); if (!cnameOrIP) { return false; } std::string nameOrIP = cnameOrIP; char* duration = ExtractArg(&args); // time string if (!duration) { return false; } uint32 duration_secs = TimeStringToSecs(duration); char* reason = ExtractArg(&args); if (!reason) { return false; } switch (mode) { case BAN_ACCOUNT: if (!AccountMgr::normalizeString(nameOrIP)) { PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, nameOrIP.c_str()); SetSentErrorMessage(true); return false; } break; case BAN_CHARACTER: if (!normalizePlayerName(nameOrIP)) { SendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } break; case BAN_IP: if (!IsIPAddress(nameOrIP.c_str())) { return false; } break; } switch (sWorld.BanAccount(mode, nameOrIP, duration_secs, reason, m_session ? m_session->GetPlayerName() : "")) { case BAN_SUCCESS: if (duration_secs > 0) { PSendSysMessage(LANG_BAN_YOUBANNED, nameOrIP.c_str(), secsToTimeString(duration_secs, true).c_str(), reason); } else { PSendSysMessage(LANG_BAN_YOUPERMBANNED, nameOrIP.c_str(), reason); } break; case BAN_SYNTAX_ERROR: return false; case BAN_NOTFOUND: switch (mode) { default: PSendSysMessage(LANG_BAN_NOTFOUND, "account", nameOrIP.c_str()); break; case BAN_CHARACTER: PSendSysMessage(LANG_BAN_NOTFOUND, "character", nameOrIP.c_str()); break; case BAN_IP: PSendSysMessage(LANG_BAN_NOTFOUND, "ip", nameOrIP.c_str()); break; } SetSentErrorMessage(true); return false; } return true; } bool ChatHandler::HandleUnBanAccountCommand(char* args) { return HandleUnBanHelper(BAN_ACCOUNT, args); } bool ChatHandler::HandleUnBanCharacterCommand(char* args) { return HandleUnBanHelper(BAN_CHARACTER, args); } bool ChatHandler::HandleUnBanIPCommand(char* args) { return HandleUnBanHelper(BAN_IP, args); } bool ChatHandler::HandleUnBanHelper(BanMode mode, char* args) { if (!*args) { return false; } char* cnameOrIP = ExtractArg(&args); if (!cnameOrIP) { return false; } std::string nameOrIP = cnameOrIP; switch (mode) { case BAN_ACCOUNT: if (!AccountMgr::normalizeString(nameOrIP)) { PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, nameOrIP.c_str()); SetSentErrorMessage(true); return false; } break; case BAN_CHARACTER: if (!normalizePlayerName(nameOrIP)) { SendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } break; case BAN_IP: if (!IsIPAddress(nameOrIP.c_str())) { return false; } break; } if (sWorld.RemoveBanAccount(mode, nameOrIP)) { PSendSysMessage(LANG_UNBAN_UNBANNED, nameOrIP.c_str()); } else { PSendSysMessage(LANG_UNBAN_ERROR, nameOrIP.c_str()); } return true; } bool ChatHandler::HandleBanInfoAccountCommand(char* args) { if (!*args) { return false; } std::string account_name; uint32 accountid = ExtractAccountId(&args, &account_name); if (!accountid) { return false; } return HandleBanInfoHelper(accountid, account_name.c_str()); } bool ChatHandler::HandleBanInfoCharacterCommand(char* args) { Player* target; ObjectGuid target_guid; if (!ExtractPlayerTarget(&args, &target, &target_guid)) { return false; } uint32 accountid = target ? target->GetSession()->GetAccountId() : sObjectMgr.GetPlayerAccountIdByGUID(target_guid); std::string accountname; if (!sAccountMgr.GetName(accountid, accountname)) { PSendSysMessage(LANG_BANINFO_NOCHARACTER); return true; } return HandleBanInfoHelper(accountid, accountname.c_str()); } bool ChatHandler::HandleBanInfoHelper(uint32 accountid, char const* accountname) { QueryResult* result = LoginDatabase.PQuery("SELECT FROM_UNIXTIME(bandate), unbandate-bandate, active, unbandate,banreason,bannedby FROM account_banned WHERE id = '%u' ORDER BY bandate ASC", accountid); if (!result) { PSendSysMessage(LANG_BANINFO_NOACCOUNTBAN, accountname); return true; } PSendSysMessage(LANG_BANINFO_BANHISTORY, accountname); do { Field* fields = result->Fetch(); time_t unbandate = time_t(fields[3].GetUInt64()); bool active = false; if (fields[2].GetBool() && (fields[1].GetUInt64() == (uint64)0 || unbandate >= time(NULL))) { active = true; } bool permanent = (fields[1].GetUInt64() == (uint64)0); std::string bantime = permanent ? GetMangosString(LANG_BANINFO_INFINITE) : secsToTimeString(fields[1].GetUInt64(), true); PSendSysMessage(LANG_BANINFO_HISTORYENTRY, fields[0].GetString(), bantime.c_str(), active ? GetMangosString(LANG_BANINFO_YES) : GetMangosString(LANG_BANINFO_NO), fields[4].GetString(), fields[5].GetString()); } while (result->NextRow()); delete result; return true; } bool ChatHandler::HandleBanInfoIPCommand(char* args) { if (!*args) { return false; } char* cIP = ExtractQuotedOrLiteralArg(&args); if (!cIP) { return false; } if (!IsIPAddress(cIP)) { return false; } std::string IP = cIP; LoginDatabase.escape_string(IP); QueryResult* result = LoginDatabase.PQuery("SELECT ip, FROM_UNIXTIME(bandate), FROM_UNIXTIME(unbandate), unbandate-UNIX_TIMESTAMP(), banreason,bannedby,unbandate-bandate FROM ip_banned WHERE ip = '%s'", IP.c_str()); if (!result) { PSendSysMessage(LANG_BANINFO_NOIP); return true; } Field* fields = result->Fetch(); bool permanent = !fields[6].GetUInt64(); PSendSysMessage(LANG_BANINFO_IPENTRY, fields[0].GetString(), fields[1].GetString(), permanent ? GetMangosString(LANG_BANINFO_NEVER) : fields[2].GetString(), permanent ? GetMangosString(LANG_BANINFO_INFINITE) : secsToTimeString(fields[3].GetUInt64(), true).c_str(), fields[4].GetString(), fields[5].GetString()); delete result; return true; } bool ChatHandler::HandleBanListCharacterCommand(char* args) { LoginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate"); char* cFilter = ExtractLiteralArg(&args); if (!cFilter) { return false; } std::string filter = cFilter; LoginDatabase.escape_string(filter); QueryResult* result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'"), filter.c_str()); if (!result) { PSendSysMessage(LANG_BANLIST_NOCHARACTER); return true; } return HandleBanListHelper(result); } bool ChatHandler::HandleBanListAccountCommand(char* args) { LoginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate"); char* cFilter = ExtractLiteralArg(&args); std::string filter = cFilter ? cFilter : ""; LoginDatabase.escape_string(filter); QueryResult* result; if (filter.empty()) { result = LoginDatabase.Query("SELECT account.id, username FROM account, account_banned" " WHERE account.id = account_banned.id AND active = 1 GROUP BY account.id"); } else { result = LoginDatabase.PQuery("SELECT account.id, username FROM account, account_banned" " WHERE account.id = account_banned.id AND active = 1 AND username " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'")" GROUP BY account.id", filter.c_str()); } if (!result) { PSendSysMessage(LANG_BANLIST_NOACCOUNT); return true; } return HandleBanListHelper(result); } bool ChatHandler::HandleBanListHelper(QueryResult* result) { PSendSysMessage(LANG_BANLIST_MATCHINGACCOUNT); // Chat short output if (m_session) { do { Field* fields = result->Fetch(); uint32 accountid = fields[0].GetUInt32(); QueryResult* banresult = LoginDatabase.PQuery("SELECT account.username FROM account,account_banned WHERE account_banned.id='%u' AND account_banned.id=account.id", accountid); if (banresult) { Field* fields2 = banresult->Fetch(); PSendSysMessage("%s", fields2[0].GetString()); delete banresult; } } while (result->NextRow()); } // Console wide output else { SendSysMessage(LANG_BANLIST_ACCOUNTS); SendSysMessage("==============================================================================="); SendSysMessage(LANG_BANLIST_ACCOUNTS_HEADER); do { SendSysMessage("-------------------------------------------------------------------------------"); Field* fields = result->Fetch(); uint32 account_id = fields[0].GetUInt32(); std::string account_name; // "account" case, name can be get in same query if (result->GetFieldCount() > 1) { account_name = fields[1].GetCppString(); } // "character" case, name need extract from another DB else { sAccountMgr.GetName(account_id, account_name); } // No SQL injection. id is uint32. QueryResult* banInfo = LoginDatabase.PQuery("SELECT bandate,unbandate,bannedby,banreason FROM account_banned WHERE id = %u ORDER BY unbandate", account_id); if (banInfo) { Field* fields2 = banInfo->Fetch(); do { time_t t_ban = fields2[0].GetUInt64(); tm* aTm_ban = localtime(&t_ban); if (fields2[0].GetUInt64() == fields2[1].GetUInt64()) { PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d| permanent |%-15.15s|%-15.15s|", account_name.c_str(), aTm_ban->tm_year % 100, aTm_ban->tm_mon + 1, aTm_ban->tm_mday, aTm_ban->tm_hour, aTm_ban->tm_min, fields2[2].GetString(), fields2[3].GetString()); } else { time_t t_unban = fields2[1].GetUInt64(); tm* aTm_unban = localtime(&t_unban); PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d|%02d-%02d-%02d %02d:%02d|%-15.15s|%-15.15s|", account_name.c_str(), aTm_ban->tm_year % 100, aTm_ban->tm_mon + 1, aTm_ban->tm_mday, aTm_ban->tm_hour, aTm_ban->tm_min, aTm_unban->tm_year % 100, aTm_unban->tm_mon + 1, aTm_unban->tm_mday, aTm_unban->tm_hour, aTm_unban->tm_min, fields2[2].GetString(), fields2[3].GetString()); } } while (banInfo->NextRow()); delete banInfo; } } while (result->NextRow()); SendSysMessage("==============================================================================="); } delete result; return true; } bool ChatHandler::HandleBanListIPCommand(char* args) { LoginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate"); char* cFilter = ExtractLiteralArg(&args); std::string filter = cFilter ? cFilter : ""; LoginDatabase.escape_string(filter); QueryResult* result; if (filter.empty()) { result = LoginDatabase.Query("SELECT ip,bandate,unbandate,bannedby,banreason FROM ip_banned" " WHERE (bandate=unbandate OR unbandate>UNIX_TIMESTAMP())" " ORDER BY unbandate"); } else { result = LoginDatabase.PQuery("SELECT ip,bandate,unbandate,bannedby,banreason FROM ip_banned" " WHERE (bandate=unbandate OR unbandate>UNIX_TIMESTAMP()) AND ip " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'") " ORDER BY unbandate", filter.c_str()); } if (!result) { PSendSysMessage(LANG_BANLIST_NOIP); return true; } PSendSysMessage(LANG_BANLIST_MATCHINGIP); // Chat short output if (m_session) { do { Field* fields = result->Fetch(); PSendSysMessage("%s", fields[0].GetString()); } while (result->NextRow()); } // Console wide output else { SendSysMessage(LANG_BANLIST_IPS); SendSysMessage("==============================================================================="); SendSysMessage(LANG_BANLIST_IPS_HEADER); do { SendSysMessage("-------------------------------------------------------------------------------"); Field* fields = result->Fetch(); time_t t_ban = fields[1].GetUInt64(); tm* aTm_ban = localtime(&t_ban); if (fields[1].GetUInt64() == fields[2].GetUInt64()) { PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d| permanent |%-15.15s|%-15.15s|", fields[0].GetString(), aTm_ban->tm_year % 100, aTm_ban->tm_mon + 1, aTm_ban->tm_mday, aTm_ban->tm_hour, aTm_ban->tm_min, fields[3].GetString(), fields[4].GetString()); } else { time_t t_unban = fields[2].GetUInt64(); tm* aTm_unban = localtime(&t_unban); PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d|%02d-%02d-%02d %02d:%02d|%-15.15s|%-15.15s|", fields[0].GetString(), aTm_ban->tm_year % 100, aTm_ban->tm_mon + 1, aTm_ban->tm_mday, aTm_ban->tm_hour, aTm_ban->tm_min, aTm_unban->tm_year % 100, aTm_unban->tm_mon + 1, aTm_unban->tm_mday, aTm_unban->tm_hour, aTm_unban->tm_min, fields[3].GetString(), fields[4].GetString()); } } while (result->NextRow()); SendSysMessage("==============================================================================="); } delete result; return true; } bool ChatHandler::HandleRespawnCommand(char* /*args*/) { Player* pl = m_session->GetPlayer(); // accept only explicitly selected target (not implicitly self targeting case) Unit* target = getSelectedUnit(); if (pl->GetSelectionGuid() && target) { if (target->GetTypeId() != TYPEID_UNIT) { SendSysMessage(LANG_SELECT_CREATURE); SetSentErrorMessage(true); return false; } if (target->IsDead()) { ((Creature*)target)->Respawn(); } return true; } MaNGOS::RespawnDo u_do; MaNGOS::WorldObjectWorker<MaNGOS::RespawnDo> worker(pl, u_do); Cell::VisitGridObjects(pl, worker, pl->GetMap()->GetVisibilityDistance()); return true; } bool ChatHandler::HandleGMFlyCommand(char* args) { bool value; if (!ExtractOnOff(&args, value)) { SendSysMessage(LANG_USE_BOL); SetSentErrorMessage(true); return false; } Player* target = getSelectedPlayer(); if (!target) { target = m_session->GetPlayer(); } target->SetCanFly(value); PSendSysMessage(LANG_COMMAND_FLYMODE_STATUS, GetNameLink(target).c_str(), args); return true; } bool ChatHandler::HandlePDumpLoadCommand(char* args) { char* file = ExtractQuotedOrLiteralArg(&args); if (!file) { return false; } std::string account_name; uint32 account_id = ExtractAccountId(&args, &account_name); if (!account_id) { return false; } char* name_str = ExtractLiteralArg(&args); uint32 lowguid = 0; std::string name; if (name_str) { name = name_str; // normalize the name if specified and check if it exists if (!normalizePlayerName(name)) { PSendSysMessage(LANG_INVALID_CHARACTER_NAME); SetSentErrorMessage(true); return false; } if (ObjectMgr::CheckPlayerName(name, true) != CHAR_NAME_SUCCESS) { PSendSysMessage(LANG_INVALID_CHARACTER_NAME); SetSentErrorMessage(true); return false; } if (*args) { if (!ExtractUInt32(&args, lowguid)) { return false; } if (!lowguid) { PSendSysMessage(LANG_INVALID_CHARACTER_GUID); SetSentErrorMessage(true); return false; } ObjectGuid guid = ObjectGuid(HIGHGUID_PLAYER, lowguid); if (sObjectMgr.GetPlayerAccountIdByGUID(guid)) { PSendSysMessage(LANG_CHARACTER_GUID_IN_USE, lowguid); SetSentErrorMessage(true); return false; } } } switch (PlayerDumpReader().LoadDump(file, account_id, name, lowguid)) { case DUMP_SUCCESS: PSendSysMessage(LANG_COMMAND_IMPORT_SUCCESS); break; case DUMP_FILE_OPEN_ERROR: PSendSysMessage(LANG_FILE_OPEN_FAIL, file); SetSentErrorMessage(true); return false; case DUMP_FILE_BROKEN: PSendSysMessage(LANG_DUMP_BROKEN, file); SetSentErrorMessage(true); return false; case DUMP_TOO_MANY_CHARS: PSendSysMessage(LANG_ACCOUNT_CHARACTER_LIST_FULL, account_name.c_str(), account_id); SetSentErrorMessage(true); return false; default: PSendSysMessage(LANG_COMMAND_IMPORT_FAILED); SetSentErrorMessage(true); return false; } return true; } bool ChatHandler::HandlePDumpWriteCommand(char* args) { if (!*args) { return false; } char* file = ExtractQuotedOrLiteralArg(&args); if (!file) { return false; } char* p2 = ExtractLiteralArg(&args); uint32 lowguid; ObjectGuid guid; // character name can't start from number if (!ExtractUInt32(&p2, lowguid)) { std::string name = ExtractPlayerNameFromLink(&p2); if (name.empty()) { SendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } guid = sObjectMgr.GetPlayerGuidByName(name); if (!guid) { PSendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } lowguid = guid.GetCounter(); } else { guid = ObjectGuid(HIGHGUID_PLAYER, lowguid); } if (!sObjectMgr.GetPlayerAccountIdByGUID(guid)) { PSendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } switch (PlayerDumpWriter().WriteDump(file, lowguid)) { case DUMP_SUCCESS: PSendSysMessage(LANG_COMMAND_EXPORT_SUCCESS); break; case DUMP_FILE_OPEN_ERROR: PSendSysMessage(LANG_FILE_OPEN_FAIL, file); SetSentErrorMessage(true); return false; default: PSendSysMessage(LANG_COMMAND_EXPORT_FAILED); SetSentErrorMessage(true); return false; } return true; } bool ChatHandler::HandleMovegensCommand(char* /*args*/) { Unit* unit = getSelectedUnit(); if (!unit) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } PSendSysMessage(LANG_MOVEGENS_LIST, (unit->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), unit->GetGUIDLow()); MotionMaster* mm = unit->GetMotionMaster(); float x, y, z; mm->GetDestination(x, y, z); for (MotionMaster::const_iterator itr = mm->begin(); itr != mm->end(); ++itr) { switch ((*itr)->GetMovementGeneratorType()) { case IDLE_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_IDLE); break; case RANDOM_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_RANDOM); break; case WAYPOINT_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_WAYPOINT); break; case CONFUSED_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_CONFUSED); break; case CHASE_MOTION_TYPE: { Unit* target = NULL; if (unit->GetTypeId() == TYPEID_PLAYER) { target = static_cast<ChaseMovementGenerator<Player> const*>(*itr)->GetTarget(); } else { target = static_cast<ChaseMovementGenerator<Creature> const*>(*itr)->GetTarget(); } if (!target) { SendSysMessage(LANG_MOVEGENS_CHASE_NULL); } else if (target->GetTypeId() == TYPEID_PLAYER) { PSendSysMessage(LANG_MOVEGENS_CHASE_PLAYER, target->GetName(), target->GetGUIDLow()); } else { PSendSysMessage(LANG_MOVEGENS_CHASE_CREATURE, target->GetName(), target->GetGUIDLow()); } break; } case FOLLOW_MOTION_TYPE: { Unit* target = NULL; if (unit->GetTypeId() == TYPEID_PLAYER) { target = static_cast<FollowMovementGenerator<Player> const*>(*itr)->GetTarget(); } else { target = static_cast<FollowMovementGenerator<Creature> const*>(*itr)->GetTarget(); } if (!target) { SendSysMessage(LANG_MOVEGENS_FOLLOW_NULL); } else if (target->GetTypeId() == TYPEID_PLAYER) { PSendSysMessage(LANG_MOVEGENS_FOLLOW_PLAYER, target->GetName(), target->GetGUIDLow()); } else { PSendSysMessage(LANG_MOVEGENS_FOLLOW_CREATURE, target->GetName(), target->GetGUIDLow()); } break; } case HOME_MOTION_TYPE: if (unit->GetTypeId() == TYPEID_UNIT) { PSendSysMessage(LANG_MOVEGENS_HOME_CREATURE, x, y, z); } else { SendSysMessage(LANG_MOVEGENS_HOME_PLAYER); } break; case FLIGHT_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_FLIGHT); break; case POINT_MOTION_TYPE: { PSendSysMessage(LANG_MOVEGENS_POINT, x, y, z); break; } case FLEEING_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_FEAR); break; case DISTRACT_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_DISTRACT); break; case EFFECT_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_EFFECT); break; default: PSendSysMessage(LANG_MOVEGENS_UNKNOWN, (*itr)->GetMovementGeneratorType()); break; } } return true; } bool ChatHandler::HandleServerPLimitCommand(char* args) { if (*args) { char* param = ExtractLiteralArg(&args); if (!param) { return false; } int l = strlen(param); int val; if (strncmp(param, "player", l) == 0) { sWorld.SetPlayerLimit(-SEC_PLAYER); } else if (strncmp(param, "moderator", l) == 0) { sWorld.SetPlayerLimit(-SEC_MODERATOR); } else if (strncmp(param, "gamemaster", l) == 0) { sWorld.SetPlayerLimit(-SEC_GAMEMASTER); } else if (strncmp(param, "administrator", l) == 0) { sWorld.SetPlayerLimit(-SEC_ADMINISTRATOR); } else if (strncmp(param, "reset", l) == 0) { sWorld.SetPlayerLimit(sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT)); } else if (ExtractInt32(&param, val)) { if (val < -SEC_ADMINISTRATOR) { val = -SEC_ADMINISTRATOR; } sWorld.SetPlayerLimit(val); } else { return false; } // kick all low security level players if (sWorld.GetPlayerAmountLimit() > SEC_PLAYER) { sWorld.KickAllLess(sWorld.GetPlayerSecurityLimit()); } } uint32 pLimit = sWorld.GetPlayerAmountLimit(); AccountTypes allowedAccountType = sWorld.GetPlayerSecurityLimit(); char const* secName = ""; switch (allowedAccountType) { case SEC_PLAYER: secName = "Player"; break; case SEC_MODERATOR: secName = "Moderator"; break; case SEC_GAMEMASTER: secName = "Gamemaster"; break; case SEC_ADMINISTRATOR: secName = "Administrator"; break; default: secName = "<unknown>"; break; } PSendSysMessage("Player limits: amount %u, min. security level %s.", pLimit, secName); return true; } bool ChatHandler::HandleCastCommand(char* args) { if (!*args) { return false; } Unit* target = getSelectedUnit(); if (!target) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spell = ExtractSpellIdFromLink(&args); if (!spell) { return false; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell); if (!spellInfo) { return false; } if (!SpellMgr::IsSpellValid(spellInfo, m_session->GetPlayer())) { PSendSysMessage(LANG_COMMAND_SPELL_BROKEN, spell); SetSentErrorMessage(true); return false; } bool triggered = ExtractLiteralArg(&args, "triggered") != NULL; if (!triggered && *args) // can be fail also at syntax error { return false; } m_session->GetPlayer()->CastSpell(target, spell, triggered); return true; } bool ChatHandler::HandleCastBackCommand(char* args) { Creature* caster = getSelectedCreature(); if (!caster) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spell = ExtractSpellIdFromLink(&args); if (!spell || !sSpellStore.LookupEntry(spell)) { return false; } bool triggered = ExtractLiteralArg(&args, "triggered") != NULL; if (!triggered && *args) // can be fail also at syntax error { return false; } caster->SetFacingToObject(m_session->GetPlayer()); caster->CastSpell(m_session->GetPlayer(), spell, triggered); return true; } bool ChatHandler::HandleCastDistCommand(char* args) { if (!*args) { return false; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spell = ExtractSpellIdFromLink(&args); if (!spell) { return false; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell); if (!spellInfo) { return false; } if (!SpellMgr::IsSpellValid(spellInfo, m_session->GetPlayer())) { PSendSysMessage(LANG_COMMAND_SPELL_BROKEN, spell); SetSentErrorMessage(true); return false; } float dist; if (!ExtractFloat(&args, dist)) { return false; } bool triggered = ExtractLiteralArg(&args, "triggered") != NULL; if (!triggered && *args) // can be fail also at syntax error { return false; } float x, y, z; m_session->GetPlayer()->GetClosePoint(x, y, z, dist); m_session->GetPlayer()->CastSpell(x, y, z, spell, triggered); return true; } bool ChatHandler::HandleCastTargetCommand(char* args) { Creature* caster = getSelectedCreature(); if (!caster) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } if (!caster->getVictim()) { SendSysMessage(LANG_SELECTED_TARGET_NOT_HAVE_VICTIM); SetSentErrorMessage(true); return false; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spell = ExtractSpellIdFromLink(&args); if (!spell || !sSpellStore.LookupEntry(spell)) { return false; } bool triggered = ExtractLiteralArg(&args, "triggered") != NULL; if (!triggered && *args) // can be fail also at syntax error { return false; } caster->SetFacingToObject(m_session->GetPlayer()); caster->CastSpell(caster->getVictim(), spell, triggered); return true; } /* ComeToMe command REQUIRED for 3rd party scripting library to have access to PointMovementGenerator Without this function 3rd party scripting library will get linking errors (unresolved external) when attempting to use the PointMovementGenerator */ bool ChatHandler::HandleComeToMeCommand(char* /*args*/) { Creature* caster = getSelectedCreature(); if (!caster) { SendSysMessage(LANG_SELECT_CREATURE); SetSentErrorMessage(true); return false; } Player* pl = m_session->GetPlayer(); caster->GetMotionMaster()->MovePoint(0, pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ()); return true; } bool ChatHandler::HandleCastSelfCommand(char* args) { if (!*args) { return false; } Unit* target = getSelectedUnit(); if (!target) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spell = ExtractSpellIdFromLink(&args); if (!spell) { return false; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell); if (!spellInfo) { return false; } if (!SpellMgr::IsSpellValid(spellInfo, m_session->GetPlayer())) { PSendSysMessage(LANG_COMMAND_SPELL_BROKEN, spell); SetSentErrorMessage(true); return false; } bool triggered = ExtractLiteralArg(&args, "triggered") != NULL; if (!triggered && *args) // can be fail also at syntax error { return false; } target->CastSpell(target, spell, triggered); return true; } bool ChatHandler::HandleInstanceListBindsCommand(char* /*args*/) { Player* player = getSelectedPlayer(); if (!player) { player = m_session->GetPlayer(); } uint32 counter = 0; for (uint8 i = 0; i < MAX_DIFFICULTY; ++i) { Player::BoundInstancesMap& binds = player->GetBoundInstances(Difficulty(i)); for (Player::BoundInstancesMap::const_iterator itr = binds.begin(); itr != binds.end(); ++itr) { DungeonPersistentState* state = itr->second.state; std::string timeleft = secsToTimeString(state->GetResetTime() - time(NULL), true); if (const MapEntry* entry = sMapStore.LookupEntry(itr->first)) { PSendSysMessage("map: %d (%s) inst: %d perm: %s diff: %d canReset: %s TTR: %s", itr->first, entry->name[GetSessionDbcLocale()], state->GetInstanceId(), itr->second.perm ? "yes" : "no", state->GetDifficulty(), state->CanReset() ? "yes" : "no", timeleft.c_str()); } else PSendSysMessage("bound for a nonexistent map %u", itr->first); ++counter; } } PSendSysMessage("player binds: %d", counter); counter = 0; if (Group* group = player->GetGroup()) { for (uint8 i = 0; i < MAX_DIFFICULTY; ++i) { Group::BoundInstancesMap& binds = group->GetBoundInstances(Difficulty(i)); for (Group::BoundInstancesMap::const_iterator itr = binds.begin(); itr != binds.end(); ++itr) { DungeonPersistentState* state = itr->second.state; std::string timeleft = secsToTimeString(state->GetResetTime() - time(NULL), true); if (const MapEntry* entry = sMapStore.LookupEntry(itr->first)) { PSendSysMessage("map: %d (%s) inst: %d perm: %s diff: %d canReset: %s TTR: %s", itr->first, entry->name[GetSessionDbcLocale()], state->GetInstanceId(), itr->second.perm ? "yes" : "no", state->GetDifficulty(), state->CanReset() ? "yes" : "no", timeleft.c_str()); } else PSendSysMessage("bound for a nonexistent map %u", itr->first); ++counter; } } } PSendSysMessage("group binds: %d", counter); return true; } bool ChatHandler::HandleInstanceUnbindCommand(char* args) { if (!*args) { return false; } Player* player = getSelectedPlayer(); if (!player) { player = m_session->GetPlayer(); } uint32 counter = 0; uint32 mapid = 0; bool got_map = false; if (strncmp(args, "all", strlen(args)) != 0) { if (!isNumeric(args[0])) { return false; } got_map = true; mapid = atoi(args); } for (uint8 i = 0; i < MAX_DIFFICULTY; ++i) { Player::BoundInstancesMap& binds = player->GetBoundInstances(Difficulty(i)); for (Player::BoundInstancesMap::iterator itr = binds.begin(); itr != binds.end();) { if (got_map && mapid != itr->first) { ++itr; continue; } if (itr->first != player->GetMapId()) { DungeonPersistentState* save = itr->second.state; std::string timeleft = secsToTimeString(save->GetResetTime() - time(NULL), true); if (const MapEntry* entry = sMapStore.LookupEntry(itr->first)) { PSendSysMessage("unbinding map: %d (%s) inst: %d perm: %s diff: %d canReset: %s TTR: %s", itr->first, entry->name[GetSessionDbcLocale()], save->GetInstanceId(), itr->second.perm ? "yes" : "no", save->GetDifficulty(), save->CanReset() ? "yes" : "no", timeleft.c_str()); } else PSendSysMessage("bound for a nonexistent map %u", itr->first); player->UnbindInstance(itr, Difficulty(i)); ++counter; } else ++itr; } } PSendSysMessage("instances unbound: %d", counter); return true; } bool ChatHandler::HandleInstanceStatsCommand(char* /*args*/) { PSendSysMessage("instances loaded: %d", sMapMgr.GetNumInstances()); PSendSysMessage("players in instances: %d", sMapMgr.GetNumPlayersInInstances()); uint32 numSaves, numBoundPlayers, numBoundGroups; sMapPersistentStateMgr.GetStatistics(numSaves, numBoundPlayers, numBoundGroups); PSendSysMessage("instance saves: %d", numSaves); PSendSysMessage("players bound: %d", numBoundPlayers); PSendSysMessage("groups bound: %d", numBoundGroups); return true; } bool ChatHandler::HandleInstanceSaveDataCommand(char* /*args*/) { Player* pl = m_session->GetPlayer(); Map* map = pl->GetMap(); InstanceData* iData = map->GetInstanceData(); if (!iData) { PSendSysMessage("Map has no instance data."); SetSentErrorMessage(true); return false; } iData->SaveToDB(); return true; } /// Display the list of GMs bool ChatHandler::HandleGMListFullCommand(char* /*args*/) { ///- Get the accounts with GM Level >0 QueryResult* result = LoginDatabase.Query("SELECT username,gmlevel FROM account WHERE gmlevel > 0"); if (result) { SendSysMessage(LANG_GMLIST); SendSysMessage("========================"); SendSysMessage(LANG_GMLIST_HEADER); SendSysMessage("========================"); ///- Circle through them. Display username and GM level do { Field* fields = result->Fetch(); PSendSysMessage("|%15s|%6s|", fields[0].GetString(), fields[1].GetString()); } while (result->NextRow()); PSendSysMessage("========================"); delete result; } else { PSendSysMessage(LANG_GMLIST_EMPTY); } return true; } /// Define the 'Message of the day' for the realm bool ChatHandler::HandleServerSetMotdCommand(char* args) { sWorld.SetMotd(args); PSendSysMessage(LANG_MOTD_NEW, args); return true; } bool ChatHandler::ShowPlayerListHelper(QueryResult* result, uint32* limit, bool title, bool error) { if (!result) { if (error) { PSendSysMessage(LANG_NO_PLAYERS_FOUND); SetSentErrorMessage(true); } return false; } if (!m_session && title) { SendSysMessage(LANG_CHARACTERS_LIST_BAR); SendSysMessage(LANG_CHARACTERS_LIST_HEADER); SendSysMessage(LANG_CHARACTERS_LIST_BAR); } if (result) { ///- Circle through them. Display username and GM level do { // check limit if (limit) { if (*limit == 0) { break; } --*limit; } Field* fields = result->Fetch(); uint32 guid = fields[0].GetUInt32(); std::string name = fields[1].GetCppString(); uint8 race = fields[2].GetUInt8(); uint8 class_ = fields[3].GetUInt8(); uint32 level = fields[4].GetUInt32(); ChrRacesEntry const* raceEntry = sChrRacesStore.LookupEntry(race); ChrClassesEntry const* classEntry = sChrClassesStore.LookupEntry(class_); char const* race_name = raceEntry ? raceEntry->name[GetSessionDbcLocale()] : "<?>"; char const* class_name = classEntry ? classEntry->name[GetSessionDbcLocale()] : "<?>"; if (!m_session) { PSendSysMessage(LANG_CHARACTERS_LIST_LINE_CONSOLE, guid, name.c_str(), race_name, class_name, level); } else { PSendSysMessage(LANG_CHARACTERS_LIST_LINE_CHAT, guid, name.c_str(), name.c_str(), race_name, class_name, level); } } while (result->NextRow()); delete result; } if (!m_session) { SendSysMessage(LANG_CHARACTERS_LIST_BAR); } return true; } /// Output list of character for account bool ChatHandler::HandleAccountCharactersCommand(char* args) { ///- Get the command line arguments std::string account_name; Player* target = NULL; // only for triggering use targeted player account uint32 account_id = ExtractAccountId(&args, &account_name, &target); if (!account_id) { return false; } ///- Get the characters for account id QueryResult* result = CharacterDatabase.PQuery("SELECT guid, name, race, class, level FROM characters WHERE account = %u", account_id); return ShowPlayerListHelper(result); } /// Set/Unset the expansion level for an account bool ChatHandler::HandleAccountSetAddonCommand(char* args) { ///- Get the command line arguments char* accountStr = ExtractOptNotLastArg(&args); std::string account_name; uint32 account_id = ExtractAccountId(&accountStr, &account_name); if (!account_id) { return false; } // Let set addon state only for lesser (strong) security level // or to self account if (GetAccountId() && GetAccountId() != account_id && HasLowerSecurityAccount(NULL, account_id, true)) { return false; } uint32 lev; if (!ExtractUInt32(&args, lev)) { return false; } // No SQL injection LoginDatabase.PExecute("UPDATE account SET expansion = '%u' WHERE id = '%u'", lev, account_id); PSendSysMessage(LANG_ACCOUNT_SETADDON, account_name.c_str(), account_id, lev); return true; } bool ChatHandler::HandleSendMailHelper(MailDraft& draft, char* args) { // format: "subject text" "mail text" char* msgSubject = ExtractQuotedArg(&args); if (!msgSubject) { return false; } char* msgText = ExtractQuotedArg(&args); if (!msgText) { return false; } // msgSubject, msgText isn't NUL after prev. check draft.SetSubjectAndBody(msgSubject, msgText); return true; } bool ChatHandler::HandleSendMassMailCommand(char* args) { // format: raceMask "subject text" "mail text" uint32 raceMask = 0; char const* name = NULL; if (!ExtractRaceMask(&args, raceMask, &name)) { return false; } // need dynamic object because it trasfered to mass mailer MailDraft* draft = new MailDraft; // fill mail if (!HandleSendMailHelper(*draft, args)) { delete draft; return false; } // from console show nonexistent sender MailSender sender(MAIL_NORMAL, m_session ? m_session->GetPlayer()->GetObjectGuid().GetCounter() : 0, MAIL_STATIONERY_GM); sMassMailMgr.AddMassMailTask(draft, sender, raceMask); PSendSysMessage(LANG_MAIL_SENT, name); return true; } bool ChatHandler::HandleSendItemsHelper(MailDraft& draft, char* args) { // format: "subject text" "mail text" item1[:count1] item2[:count2] ... item12[:count12] char* msgSubject = ExtractQuotedArg(&args); if (!msgSubject) { return false; } char* msgText = ExtractQuotedArg(&args); if (!msgText) { return false; } // extract items typedef std::pair<uint32, uint32> ItemPair; typedef std::list< ItemPair > ItemPairs; ItemPairs items; // get from tail next item str while (char* itemStr = ExtractArg(&args)) { // parse item str uint32 item_id = 0; uint32 item_count = 1; if (sscanf(itemStr, "%u:%u", &item_id, &item_count) != 2) if (sscanf(itemStr, "%u", &item_id) != 1) { return false; } if (!item_id) { PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, item_id); SetSentErrorMessage(true); return false; } ItemPrototype const* item_proto = ObjectMgr::GetItemPrototype(item_id); if (!item_proto) { PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, item_id); SetSentErrorMessage(true); return false; } if (item_count < 1 || (item_proto->MaxCount > 0 && item_count > uint32(item_proto->MaxCount))) { PSendSysMessage(LANG_COMMAND_INVALID_ITEM_COUNT, item_count, item_id); SetSentErrorMessage(true); return false; } while (item_count > item_proto->GetMaxStackSize()) { items.push_back(ItemPair(item_id, item_proto->GetMaxStackSize())); item_count -= item_proto->GetMaxStackSize(); } items.push_back(ItemPair(item_id, item_count)); if (items.size() > MAX_MAIL_ITEMS) { PSendSysMessage(LANG_COMMAND_MAIL_ITEMS_LIMIT, MAX_MAIL_ITEMS); SetSentErrorMessage(true); return false; } } // fill mail draft.SetSubjectAndBody(msgSubject, msgText); for (ItemPairs::const_iterator itr = items.begin(); itr != items.end(); ++itr) { if (Item* item = Item::CreateItem(itr->first, itr->second, m_session ? m_session->GetPlayer() : 0)) { item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted draft.AddItem(item); } } return true; } bool ChatHandler::HandleSendItemsCommand(char* args) { // format: name "subject text" "mail text" item1[:count1] item2[:count2] ... item12[:count12] Player* receiver; ObjectGuid receiver_guid; std::string receiver_name; if (!ExtractPlayerTarget(&args, &receiver, &receiver_guid, &receiver_name)) { return false; } MailDraft draft; // fill mail if (!HandleSendItemsHelper(draft, args)) { return false; } // from console show nonexistent sender MailSender sender(MAIL_NORMAL, m_session ? m_session->GetPlayer()->GetObjectGuid().GetCounter() : 0, MAIL_STATIONERY_GM); draft.SendMailTo(MailReceiver(receiver, receiver_guid), sender); std::string nameLink = playerLink(receiver_name); PSendSysMessage(LANG_MAIL_SENT, nameLink.c_str()); return true; } bool ChatHandler::HandleSendMassItemsCommand(char* args) { // format: racemask "subject text" "mail text" item1[:count1] item2[:count2] ... item12[:count12] uint32 raceMask = 0; char const* name = NULL; if (!ExtractRaceMask(&args, raceMask, &name)) { return false; } // need dynamic object because it trasfered to mass mailer MailDraft* draft = new MailDraft; // fill mail if (!HandleSendItemsHelper(*draft, args)) { delete draft; return false; } // from console show nonexistent sender MailSender sender(MAIL_NORMAL, m_session ? m_session->GetPlayer()->GetObjectGuid().GetCounter() : 0, MAIL_STATIONERY_GM); sMassMailMgr.AddMassMailTask(draft, sender, raceMask); PSendSysMessage(LANG_MAIL_SENT, name); return true; } bool ChatHandler::HandleSendMoneyHelper(MailDraft& draft, char* args) { /// format: "subject text" "mail text" money char* msgSubject = ExtractQuotedArg(&args); if (!msgSubject) { return false; } char* msgText = ExtractQuotedArg(&args); if (!msgText) { return false; } uint32 money; if (!ExtractUInt32(&args, money)) { return false; } if (money <= 0) { return false; } // msgSubject, msgText isn't NUL after prev. check draft.SetSubjectAndBody(msgSubject, msgText).SetMoney(money); return true; } bool ChatHandler::HandleSendMoneyCommand(char* args) { /// format: name "subject text" "mail text" money Player* receiver; ObjectGuid receiver_guid; std::string receiver_name; if (!ExtractPlayerTarget(&args, &receiver, &receiver_guid, &receiver_name)) { return false; } MailDraft draft; // fill mail if (!HandleSendMoneyHelper(draft, args)) { return false; } // from console show nonexistent sender MailSender sender(MAIL_NORMAL, m_session ? m_session->GetPlayer()->GetObjectGuid().GetCounter() : 0, MAIL_STATIONERY_GM); draft.SendMailTo(MailReceiver(receiver, receiver_guid), sender); std::string nameLink = playerLink(receiver_name); PSendSysMessage(LANG_MAIL_SENT, nameLink.c_str()); return true; } bool ChatHandler::HandleSendMassMoneyCommand(char* args) { /// format: raceMask "subject text" "mail text" money uint32 raceMask = 0; char const* name = NULL; if (!ExtractRaceMask(&args, raceMask, &name)) { return false; } // need dynamic object because it trasfered to mass mailer MailDraft* draft = new MailDraft; // fill mail if (!HandleSendMoneyHelper(*draft, args)) { delete draft; return false; } // from console show nonexistent sender MailSender sender(MAIL_NORMAL, m_session ? m_session->GetPlayer()->GetObjectGuid().GetCounter() : 0, MAIL_STATIONERY_GM); sMassMailMgr.AddMassMailTask(draft, sender, raceMask); PSendSysMessage(LANG_MAIL_SENT, name); return true; } /// Send a message to a player in game bool ChatHandler::HandleSendMessageCommand(char* args) { ///- Find the player Player* rPlayer; if (!ExtractPlayerTarget(&args, &rPlayer)) { return false; } ///- message if (!*args) { return false; } WorldSession* rPlayerSession = rPlayer->GetSession(); ///- Check that he is not logging out. if (rPlayerSession->isLogingOut()) { SendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } ///- Send the message // Use SendAreaTriggerMessage for fastest delivery. rPlayerSession->SendAreaTriggerMessage("%s", args); rPlayerSession->SendAreaTriggerMessage("|cffff0000[Message from administrator]:|r"); // Confirmation message std::string nameLink = GetNameLink(rPlayer); PSendSysMessage(LANG_SENDMESSAGE, nameLink.c_str(), args); return true; } bool ChatHandler::HandleFlushArenaPointsCommand(char* /*args*/) { sBattleGroundMgr.DistributeArenaPoints(); return true; } bool ChatHandler::HandleModifyGenderCommand(char* args) { if (!*args) { return false; } Player* player = getSelectedPlayer(); if (!player) { PSendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } PlayerInfo const* info = sObjectMgr.GetPlayerInfo(player->getRace(), player->getClass()); if (!info) { return false; } char* gender_str = args; int gender_len = strlen(gender_str); Gender gender; if (!strncmp(gender_str, "male", gender_len)) // MALE { if (player->getGender() == GENDER_MALE) { return true; } gender = GENDER_MALE; } else if (!strncmp(gender_str, "female", gender_len)) // FEMALE { if (player->getGender() == GENDER_FEMALE) { return true; } gender = GENDER_FEMALE; } else { SendSysMessage(LANG_MUST_MALE_OR_FEMALE); SetSentErrorMessage(true); return false; } // Set gender player->SetByteValue(UNIT_FIELD_BYTES_0, 2, gender); player->SetUInt16Value(PLAYER_BYTES_3, 0, uint16(gender) | (player->GetDrunkValue() & 0xFFFE)); // Change display ID player->InitDisplayIds(); char const* gender_full = gender ? "female" : "male"; PSendSysMessage(LANG_YOU_CHANGE_GENDER, player->GetName(), gender_full); if (needReportToTarget(player)) { ChatHandler(player).PSendSysMessage(LANG_YOUR_GENDER_CHANGED, gender_full, GetNameLink().c_str()); } return true; } bool ChatHandler::HandleShowGearScoreCommand(char* args) { Player* player = getSelectedPlayer(); if (!player) { PSendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } uint32 withBags, withBank; if (!ExtractOptUInt32(&args, withBags, 1)) return false; if (!ExtractOptUInt32(&args, withBank, 0)) return false; // always recalculate gear score for display player->ResetCachedGearScore(); uint32 gearScore = player->GetEquipGearScore(withBags != 0, withBank != 0); PSendSysMessage(LANG_GEARSCORE, GetNameLink(player).c_str(), gearScore); return true; } bool ChatHandler::HandleMmap(char* args) { bool on; if (ExtractOnOff(&args, on)) { if (on) { sWorld.setConfig(CONFIG_BOOL_MMAP_ENABLED, true); SendSysMessage("WORLD: mmaps are now ENABLED (individual map settings still in effect)"); } else { sWorld.setConfig(CONFIG_BOOL_MMAP_ENABLED, false); SendSysMessage("WORLD: mmaps are now DISABLED"); } return true; } on = sWorld.getConfig(CONFIG_BOOL_MMAP_ENABLED); PSendSysMessage("mmaps are %sabled", on ? "en" : "dis"); return true; } bool ChatHandler::HandleMmapTestArea(char* args) { float radius = 40.0f; ExtractFloat(&args, radius); std::list<Creature*> creatureList; MaNGOS::AnyUnitInObjectRangeCheck go_check(m_session->GetPlayer(), radius); MaNGOS::CreatureListSearcher<MaNGOS::AnyUnitInObjectRangeCheck> go_search(creatureList, go_check); // Get Creatures Cell::VisitGridObjects(m_session->GetPlayer(), go_search, radius); if (!creatureList.empty()) { PSendSysMessage("Found " SIZEFMTD " Creatures.", creatureList.size()); uint32 paths = 0; uint32 uStartTime = WorldTimer::getMSTime(); float gx, gy, gz; m_session->GetPlayer()->GetPosition(gx, gy, gz); for (std::list<Creature*>::iterator itr = creatureList.begin(); itr != creatureList.end(); ++itr) { PathFinder path(*itr); path.calculate(gx, gy, gz); ++paths; } uint32 uPathLoadTime = WorldTimer::getMSTimeDiff(uStartTime, WorldTimer::getMSTime()); PSendSysMessage("Generated %i paths in %i ms", paths, uPathLoadTime); } else { PSendSysMessage("No creatures in %f yard range.", radius); } return true; } // use ".mmap testheight 10" selecting any creature/player bool ChatHandler::HandleMmapTestHeight(char* args) { float radius = 0.0f; ExtractFloat(&args, radius); if (radius > 40.0f) radius = 40.0f; Unit* unit = getSelectedUnit(); Player* player = m_session->GetPlayer(); if (!unit) unit = player; if (unit->GetTypeId() == TYPEID_UNIT) { if (radius < 0.1f) radius = static_cast<Creature*>(unit)->GetRespawnRadius(); } else { if (unit->GetTypeId() != TYPEID_PLAYER) { PSendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); return false; } } if (radius < 0.1f) { PSendSysMessage("Provided spawn radius for %s is too small. Using 5.0f instead.", unit->GetGuidStr().c_str()); radius = 5.0f; } float gx, gy, gz; unit->GetPosition(gx, gy, gz); Creature* summoned = unit->SummonCreature(VISUAL_WAYPOINT, gx, gy, gz + 0.5f, 0, TEMPSUMMON_TIMED_DESPAWN, 20000); summoned->CastSpell(summoned, 8599, false); uint32 tries = 1; uint32 successes = 0; uint32 startTime = WorldTimer::getMSTime(); for (; tries < 500; ++tries) { unit->GetPosition(gx, gy, gz); if (unit->GetMap()->GetReachableRandomPosition(unit, gx, gy, gz, radius)) { unit->SummonCreature(VISUAL_WAYPOINT, gx, gy, gz, 0, TEMPSUMMON_TIMED_DESPAWN, 15000); ++successes; if (successes >= 100) break; } } uint32 genTime = WorldTimer::getMSTimeDiff(startTime, WorldTimer::getMSTime()); PSendSysMessage("Generated %u valid points for %u try in %ums.", successes, tries, genTime); return true; } bool ChatHandler::HandleServerResetAllRaidCommand(char* args) { PSendSysMessage("Global raid instances reset, all players in raid instances will be teleported to homebind!"); sMapPersistentStateMgr.GetScheduler().ResetAllRaid(); return true; }
30.282516
249
0.609542
tbayart
b43b885f4f8a57b490612b28ca9653a7e08aa96f
9,255
cpp
C++
src/graphic/oni-graphic-renderer-ogl-quad.cpp
sina-/granite
95b873bc545cd4925b5cea8c632a82f2d815be6e
[ "MIT" ]
2
2019-08-01T09:18:49.000Z
2020-03-26T05:59:52.000Z
src/graphic/oni-graphic-renderer-ogl-quad.cpp
sina-/granite
95b873bc545cd4925b5cea8c632a82f2d815be6e
[ "MIT" ]
null
null
null
src/graphic/oni-graphic-renderer-ogl-quad.cpp
sina-/granite
95b873bc545cd4925b5cea8c632a82f2d815be6e
[ "MIT" ]
1
2020-03-26T05:59:53.000Z
2020-03-26T05:59:53.000Z
#include <oni-core/graphic/oni-graphic-renderer-ogl-quad.h> #include <cassert> #include <GL/glew.h> #include <oni-core/graphic/buffer/oni-graphic-buffer-data.h> #include <oni-core/graphic/buffer/oni-graphic-index-buffer.h> #include <oni-core/graphic/buffer/oni-graphic-frame-buffer.h> #include <oni-core/graphic/buffer/oni-graphic-vertex-array.h> #include <oni-core/graphic/oni-graphic-shader.h> #include <oni-core/component/oni-component-geometry.h> #include <oni-core/component/oni-component-visual.h> #include <oni-core/math/oni-math-function.h> namespace oni { Renderer_OpenGL_Quad::Renderer_OpenGL_Quad(oniGLsizei maxPrimitiveCount, TextureManager &tm) : Renderer_OpenGL(PrimitiveType::TRIANGLES, tm), mMaxPrimitiveCount(maxPrimitiveCount) { mMaxIndicesCount = mMaxPrimitiveCount * 6; oniGLsizei vertexSize = sizeof(QuadVertex); oniGLsizei primitiveSize = vertexSize * 4; assert(mMaxIndicesCount < std::numeric_limits<i32>::max()); oniGLsizei maxBufferSize{primitiveSize * mMaxPrimitiveCount}; auto vertShader = std::string_view("oni-resources/shaders/quad.vert"); auto geomShader = std::string_view(""); auto fragShader = std::string_view("oni-resources/shaders/quad.frag"); mShader = std::make_unique<Shader>(vertShader, geomShader, fragShader); auto program = mShader->getProgram(); auto positionIndex = glGetAttribLocation(program, "position"); auto colorIndex = glGetAttribLocation(program, "color"); auto uvIndex = glGetAttribLocation(program, "uv"); auto samplerFrontIndex = glGetAttribLocation(program, "samplerFront"); auto samplerBackIndex = glGetAttribLocation(program, "samplerBack"); if (positionIndex == -1 || uvIndex == -1 || colorIndex == -1 || samplerFrontIndex == -1 || samplerBackIndex == -1) { assert(false); } BufferStructure samplerFront; samplerFront.index = static_cast<oniGLuint>(samplerFrontIndex); samplerFront.componentCount = 1; samplerFront.componentType = GL_FLOAT; samplerFront.normalized = GL_FALSE; samplerFront.stride = vertexSize; samplerFront.offset = static_cast<const oniGLvoid *>(nullptr); BufferStructure samplerBack; samplerBack.index = static_cast<oniGLuint>(samplerBackIndex); samplerBack.componentCount = 1; samplerBack.componentType = GL_FLOAT; samplerBack.normalized = GL_FALSE; samplerBack.stride = vertexSize; samplerBack.offset = reinterpret_cast<const oniGLvoid *>(offsetof(QuadVertex, samplerBack)); BufferStructure color; color.index = static_cast<oniGLuint>(colorIndex); color.componentCount = 4; color.componentType = GL_FLOAT; color.normalized = GL_TRUE; color.stride = vertexSize; color.offset = reinterpret_cast<const oniGLvoid *>(offsetof(QuadVertex, color)); BufferStructure uv; uv.index = static_cast<oniGLuint>(uvIndex); uv.componentCount = 2; uv.componentType = GL_FLOAT; uv.normalized = GL_TRUE; uv.stride = vertexSize; uv.offset = reinterpret_cast<const oniGLvoid *>(offsetof(QuadVertex, uv)); BufferStructure position; position.index = static_cast<oniGLuint>(positionIndex); position.componentCount = 3; position.componentType = GL_FLOAT; position.normalized = GL_FALSE; position.stride = vertexSize; position.offset = reinterpret_cast<const oniGLvoid *>(offsetof(QuadVertex, pos)); std::vector<BufferStructure> bufferStructures; bufferStructures.push_back(samplerFront); bufferStructures.push_back(samplerBack); bufferStructures.push_back(color); bufferStructures.push_back(uv); bufferStructures.push_back(position); mVertexArray = std::make_unique<VertexArray>(bufferStructures, maxBufferSize); if (mMaxIndicesCount > mMaxPrimitiveCount) { mIndexBuffer = std::make_unique<IndexBuffer>(mMaxIndicesCount); } std::vector<GLint> samplers; for (i8 i = 0; i < mMaxNumTextureSamplers; ++i) { samplers.push_back(i); } mShader->enable(); mShader->setUniformiv("samplers", samplers); mShader->disable(); } Renderer_OpenGL_Quad::~Renderer_OpenGL_Quad() = default; void Renderer_OpenGL_Quad::submit(const Quad &quad, const Color &color, const Texture *texture) { assert(mIndexCount + 6 < mMaxIndicesCount); auto buffer = static_cast<QuadVertex *>(mBuffer); auto samplerFront = -1.f; auto samplerBack = -1.f; auto uv0 = vec2{}; auto uv1 = vec2{}; auto uv2 = vec2{}; auto uv3 = vec2{}; if (texture) { samplerFront = getSamplerID(texture->id); uv0 = texture->uv.values[0]; uv1 = texture->uv.values[1]; uv2 = texture->uv.values[2]; uv3 = texture->uv.values[3]; } auto c = color.rgba(); // a. buffer->pos = quad.a.value; buffer->color = c; buffer->uv = uv0; buffer->samplerFront = samplerFront; buffer->samplerBack = samplerBack; ++buffer; // b. buffer->pos = quad.b.value; buffer->color = c; buffer->uv = uv1; buffer->samplerFront = samplerFront; buffer->samplerBack = samplerBack; ++buffer; // c. buffer->pos = quad.c.value; buffer->color = c; buffer->uv = uv2; buffer->samplerFront = samplerFront; buffer->samplerBack = samplerBack; ++buffer; // d. buffer->pos = quad.d.value; buffer->color = c; buffer->uv = uv3; buffer->samplerFront = samplerFront; buffer->samplerBack = samplerBack; ++buffer; // Update the mBuffer to point to the head. mBuffer = static_cast<void *>(buffer); // +6 as there are 6 vertices that makes up two adjacent triangles but those triangles are // defined by 4 vertices only. /** * 1 +---+ 2 * | /| * |/ | * 0 +---+ 3 **/ mIndexCount += 6; } void Renderer_OpenGL_Quad::submit(const Quad &quad, const Color &color, const Texture &front, const Texture &back) { assert(mIndexCount + 6 < mMaxIndicesCount); assert(front.id); assert(back.id); assert(almost_Equal(front.uv.values[0].x, back.uv.values[0].x)); assert(almost_Equal(front.uv.values[1].x, back.uv.values[1].x)); assert(almost_Equal(front.uv.values[2].x, back.uv.values[2].x)); assert(almost_Equal(front.uv.values[3].x, back.uv.values[3].x)); assert(almost_Equal(front.uv.values[0].y, back.uv.values[0].y)); assert(almost_Equal(front.uv.values[1].y, back.uv.values[1].y)); assert(almost_Equal(front.uv.values[2].y, back.uv.values[2].y)); assert(almost_Equal(front.uv.values[3].y, back.uv.values[3].y)); auto buffer = static_cast<QuadVertex *>(mBuffer); auto samplerFront = getSamplerID(front.id); auto samplerBack = getSamplerID(back.id); auto c = color.rgba(); buffer->pos = quad.a.value; buffer->color = c; buffer->uv = front.uv.values[0]; buffer->samplerFront = samplerFront; buffer->samplerBack = samplerBack; ++buffer; buffer->pos = quad.b.value; buffer->color = c; buffer->uv = front.uv.values[1]; buffer->samplerFront = samplerFront; buffer->samplerBack = samplerBack; ++buffer; buffer->pos = quad.c.value; buffer->color = c; buffer->uv = front.uv.values[2]; buffer->samplerFront = samplerFront; buffer->samplerBack = samplerBack; ++buffer; buffer->pos = quad.d.value; buffer->color = c; buffer->uv = front.uv.values[3]; buffer->samplerFront = samplerFront; buffer->samplerBack = samplerBack; ++buffer; mBuffer = static_cast<void *>(buffer); mIndexCount += 6; } void Renderer_OpenGL_Quad::submit(const Renderable &renderable) { // TODO: Implement assert(false); } void Renderer_OpenGL_Quad::enableShader(const RenderSpec &spec) { mShader->enable(); mShader->setUniformMat4("model", spec.model); mShader->setUniformMat4("view", spec.view); mShader->setUniformMat4("proj", spec.proj); } oniGLsizei Renderer_OpenGL_Quad::getIndexCount() { return mIndexCount; } void Renderer_OpenGL_Quad::resetIndexCount() { mIndexCount = 0; } }
33.532609
98
0.596002
sina-
b43d3e527520ce9b211eda35514afe356721df04
760
cpp
C++
src/powercycle.cpp
raghu-veer/powercycle-mgr
955e806538560575078aaee261149d8b04ee07f3
[ "MIT" ]
null
null
null
src/powercycle.cpp
raghu-veer/powercycle-mgr
955e806538560575078aaee261149d8b04ee07f3
[ "MIT" ]
null
null
null
src/powercycle.cpp
raghu-veer/powercycle-mgr
955e806538560575078aaee261149d8b04ee07f3
[ "MIT" ]
null
null
null
#include <cstdlib> #include <cstdint> #include <string> #include <vector> #include <chrono> #include <ctime> #include <fstream> #include <unistd.h> #include <sys/reboot.h> #include "powercycle.hpp" Powercycle::Powercycle(const uint32_t& wakeupTime) : wakeupTime_(wakeupTime) { execute(); } void Powercycle::execute() { invokeRTC(); shutdown(); } void Powercycle::invokeRTC() { time_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); std::ofstream rtcStream; rtcStream.open(RTC_WAKEALARM); rtcStream << time(&currentTime) + (wakeupTime_ * SECONDS); rtcStream.close(); } /* using reboot(2) to shutdown immediately, see man reboot(2) */ void Powercycle::shutdown() { reboot(RB_POWER_OFF); }
19.487179
94
0.703947
raghu-veer
b43eacc0c960cc5807ad6e737a95394d19b99747
47,347
cpp
C++
src/qsa/src/engine/qsclass.cpp
hackbinary/pdfedit
5efb58265d0b86c2786d7b218aa0d6f895b926d3
[ "CECILL-B" ]
13
2015-10-15T01:26:37.000Z
2019-11-18T21:50:46.000Z
src/qsa/src/engine/qsclass.cpp
mmoselhy/PDF-X
b72597bbb0c6c86d99e44cf18f7b46d5175a7bfa
[ "CECILL-B" ]
1
2020-03-28T23:06:53.000Z
2020-04-08T03:24:06.000Z
src/qsa/src/engine/qsclass.cpp
mmoselhy/PDF-X
b72597bbb0c6c86d99e44cf18f7b46d5175a7bfa
[ "CECILL-B" ]
14
2016-01-31T10:54:56.000Z
2020-08-31T11:08:42.000Z
/**************************************************************************** ** $Id$ ** ** Copyright (C) 2001-2006 Trolltech AS. All rights reserved. ** ** This file is part of the Qt Script for Applications framework (QSA). ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** Licensees holding a valid Qt Script for Applications license may use ** this file in accordance with the Qt Script for Applications License ** Agreement provided with the Software. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for ** information about QSA Commercial License Agreements. ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** *****************************************************************************/ #include "qsclass.h" #include "qsenv.h" #include "qsoperations.h" #include "qstypes.h" #include "qsnodes.h" #include "qsfuncref.h" #include <stdlib.h> #if defined(Q_OS_WIN32) #include <qt_windows.h> #endif using namespace QS; QSClass::QSClass( QSEnv *e, int a ) : en( e ), bclass( 0 ), encClass( 0 ), attrs( a ) { Q_ASSERT( e ); init(); } QSClass::QSClass( QSClass *b, int a ) : bclass( b ), encClass( 0 ), attrs( a ) { Q_ASSERT( b && b->env() ); en = b->env(); init(); } QSClass::~QSClass() { } void QSClass::clear() { for (QSMemberMap::ConstIterator it = mmap->begin(); it!=mmap->end(); ++it) { if ((*it).type() == QSMember::ScriptFunction) { if ((*it).scriptFunction->deref()) { delete (*it).scriptFunction; } } } delete mmap; mmap = 0; staticMembers.clear(); } void QSClass::init() { mmap = new QSMemberMap(); numVars = base() ? base()->numVariables() : 0; numStaticVars = 0; en->registerClass( this ); } /*! Checks if the two objects are equal. Returns positive if equal, 0 if not equal and negative if the class is unable to determine. */ QSEqualsResult QSClass::isEqual( const QSObject &a, const QSObject &/*b*/ ) const { Q_ASSERT( a.isA( this ) ); // qDebug( "QSClass::isEqual( %s, %s )", // a.typeName().ascii(), b.typeName().ascii() ); return EqualsUndefined; } /*! Checks if two objects are strictly equal, meaning that they are exactly the same object. */ QSEqualsResult QSClass::isStrictEqual( const QSObject &a, const QSObject &b ) const { Q_ASSERT( a.isA( this ) ); if ( a.objectType() != b.objectType() ) return EqualsNotEqual; if ( a.isUndefined() || a.isNull() ) return EqualsIsEqual; if ( a.isNumber() ) { double doubA = a.toNumber(); if ( isNaN( doubA ) ) return EqualsNotEqual; double doubB = b.toNumber(); if ( isNaN( doubB ) ) return EqualsNotEqual; if ( doubA == doubB || ( doubA==0 && doubB==-0 ) || ( doubA==-0 && doubB==0 ) ) return EqualsIsEqual; return EqualsNotEqual; } else if ( a.isString() ) { return (QSEqualsResult) (a.toString() == b.toString() || (a.sVal().isEmpty() && b.sVal().isEmpty())); } else if ( a.isBoolean() ) { return ( QSEqualsResult ) ( a.toBoolean() == b.toBoolean() ); } return ( QSEqualsResult ) ( a.shVal() == b.shVal() ); } QSCompareResult QSClass::compare( const QSObject &a, const QSObject &b ) const { // qDebug( "\nQSClass::compare" ); // qDebug( "a: %s\nb: %s", a.toString().latin1(), b.toString().latin1() ); QSObject primA = a.toPrimitive( env()->numberClass() ); QSObject primB = b.toPrimitive( env()->numberClass() ); if( primA.isString() && primB.isString() ) { QString strA = primA.toString(); QString strB = primB.toString(); if (strA.isEmpty() && strB.isEmpty()) return CompareEqual; int ret = QString::compare(strA, strB); if( ret==0 ) return CompareEqual; else if( ret<0 ) return CompareLess; else return CompareGreater; } double doubA = primA.toNumber(); double doubB = primB.toNumber(); // qDebug( "a=%f, b=%f", doubA, doubB ); if( isNaN( doubA ) || isNaN( doubB ) ) { return CompareUndefined; } // ### +0 vs -0 cases... if( doubA==doubB ) { return CompareEqual; } else if( doubA < doubB ) { return CompareLess; } else { return CompareGreater; } return CompareUndefined; } void QSClass::finalize() { #if 0 // ### required to avoid double deletions QSObjectList::iterator it = staticMembers.begin(); QSObjectList::iterator end = staticMembers.end(); while ( it != end ) { (*it).invalidate(); ++it; } #else staticMembers.clear(); #endif for (QSMemberMap::ConstIterator it = mmap->begin(); it!=mmap->end(); ++it) if ((*it).type() == QSMember::ScriptFunction) { if ((*it).scriptFunction->scopeDefinition()) (*it).scriptFunction->scopeDefinition()->setFunctionBodyNode(0); (*it).scriptFunction->setScopeDefinition(0); } } QSClassClass* QSClass::asClass() const { return name() == QString::fromLatin1("Class") ? (QSClassClass*)this : 0; } QSObject QSClass::execute( const QSObject *, QSObject *, const QSList & ) const { throwError( TypeError, QString::fromLatin1("Cannot invoke objects of type %1 as function").arg(name()) ); return createUndefined(); } /*! Returns TRUE if this class is a subclass of \c; FALSE otherwise. A class is defined to be a subclass of itself. */ bool QSClass::inherits( const QSClass *c ) const { const QSClass *b = this; while ( b && b != c ) b = b->base(); return b == c; } /*! * Mark \a o and its sub-properties as referenced. This is used * for the mark & sweep garbage collection. * * The default implementation does nothing but you should reimplement * this function if objects of this class contain other objects * or references to them. */ void QSClass::mark( QSObject * /*o*/ ) const { // do nothing } void QSClass::ref( QSObject * /*o*/ ) const { } void QSClass::deref( QSObject * /*o*/ ) const { } /*! * Returns \a obj converted to a boolean value. * * The default implementation returns TRUE. */ bool QSClass::toBoolean( const QSObject * /*obj*/ ) const { return TRUE; } /*! * Return \a obj converted to a floating point number; NaN if * the conversion failed. * * The default implementation returns NaN. */ double QSClass::toNumber( const QSObject * ) const { return NaN; } /*! * Return \a obj converted to a string. * * The default implementation returns "[object N]" where N is * the name of this class as retrieved by name(). */ QString QSClass::toString( const QSObject * ) const { return QString::fromLatin1("[object ") + name() + QString::fromLatin1("]"); } QSObject QSClass::toPrimitive( const QSObject *obj, const QSClass *preferred ) const { if( preferred != env()->numberClass() ) return createString( toString( obj ) ); else return createNumber( toNumber( obj ) ); } /*! Convert \a obj to an equivalent QVariant. The default implementation returns in invalid QVariant which may also be the case where no mapping for an equivalent type exists. */ QVariant QSClass::toVariant( const QSObject * /*obj*/, QVariant::Type ) const { // ### how about respecting the prefered type ? return QVariant(); } #if QS_MAX_STACK>0 static int debugStringRecursionDepth = 0; #endif QString QSClass::debugString( const QSObject *obj ) const { #if QS_MAX_STACK>0 if( ++debugStringRecursionDepth==QS_MAX_STACK ) { Q_ASSERT( obj->isValid() ); obj->env()->throwError( RangeError, QString::fromLatin1("Internal recursion level maxed out in: " "QSArrayClass::joinInternal"), -1 ); --debugStringRecursionDepth; return QString::null; } #endif QString retVal = QString::null; if ( obj->isPrimitive() ) { retVal = toString( obj ) + QString::fromLatin1(":") + name(); } else { QSMemberMap m = members( obj ); if ( m.isEmpty() ) { retVal = toString( obj ) + QString::fromLatin1(":") + name(); } else { QSMemberMap::ConstIterator it = m.begin(); retVal = "{"; for ( ;; ) { QSObject p = env()->resolveValue( it.key() ); if ( !p.isValid() ) { // ### should never happen (but sometimes does) ++it; if ( it == m.end() ) break; else continue; } retVal += it.key() + QString::fromLatin1("=") + p.debugString(); ++it; if ( it == m.end() ) break; else retVal += QString::fromLatin1(","); } retVal += QString::fromLatin1("}:") + identifier(); } } #if QS_MAX_STACK>0 --debugStringRecursionDepth; #endif return retVal; } bool QSClass::deleteProperty( QSObject *, const QSMember & ) const { return FALSE; } /*! Retrieves a pointer to the class member \a n; 0 if no such member exists. */ bool QSClass::member( const QSObject *, const QString &n, QSMember *m ) const { // qDebug( "QSClass::member() class = %s, name = %s", name().latin1(), n.latin1() ); Q_ASSERT( !n.isEmpty() ); Q_ASSERT( m ); Q_ASSERT( mmap ); QSMemberMap::Iterator it = mmap->find( n ); if( it == mmap->end() ) { return FALSE; } else { *m = it.data(); return TRUE; } } QSObject QSClass::fetchValue( const QSObject *objPtr, const QSMember &mem ) const { // qDebug( "fetching from: " + identifier() + ", " + mem ); if( !mem.isReadable() ) { qDebug( "QSClass:fetchValue() - not readable: %s", mem.name().latin1() ); return createUndefined(); } if( mem.type()==QSMember::Variable ) { if ( !mem.isStatic() ) { QSInstanceData *data = (QSInstanceData*)objPtr->shVal(); if ( mem.idx >= data->size() ) { // ### could throw error in member() // qWarning( "QSClass::fetchValue: non-resized array access" ); return createUndefined(); } QSObject * ptr = data->value( mem.idx ); if ( !ptr->isValid() ) { // qWarning( "QSMember::fetch: Accessed uninitialized variable" ); return createUndefined(); } return *ptr; } else { return staticMember( mem.idx ); } } else if ( mem.isExecutable() ) { return env()->funcRefClass()->createReference( *objPtr, mem ); } return createUndefined(); } void QSClass::write( QSObject *objPtr, const QSMember &mem, const QSObject &val ) const { Q_ASSERT( mem.isWritable() ); if (mem.type() != QSMember::Variable) { env()->throwError(ReferenceError, QString::fromLatin1("Member '%1' cannot be overwritten in '%2'") .arg(mem.name()).arg(name())); return; } if ( mem.isWritable() && mem.type()==QSMember::Variable ) { if ( !mem.isStatic() ) { QSInstanceData *data = (QSInstanceData*)objPtr->shVal(); if ( mem.idx >= data->size() ) { qWarning( "QSClass::write(), index=%d greater than array size=%d", mem.idx, data->size() ); // ### could throw error in member() return; } data->setValue( mem.idx, val ); } else { QSClass * cl = (QSClass*) this; cl->setStaticMember( mem.idx, val ); } } } /*! Only use for objPtr's that absolutly have QSInstanceData */ void QSClass::write( QSObject * objPtr, int index, const QSObject &val ) const { QSInstanceData *idata = (QSInstanceData*)objPtr->shVal(); idata->setValue( index, val ); } void QSClass::setStaticMember( int idx, const QSObject &val ) { Q_ASSERT( idx>=0 && idx<numStaticVars ); staticMembers[idx] = val; } QSObject QSClass::staticMember( int idx ) const { Q_ASSERT( idx>=0 && idx<numStaticVars ); return staticMembers[idx]; } static bool compareScopes( const QSObject &a, const QSObject &b ) { return a.objectType()==b.objectType() && a.shVal()==b.shVal(); } QSObject QSClass::invoke( QSObject * objPtr, const QSMember &mem ) const { Q_ASSERT( mem.isExecutable() ); Q_ASSERT( objPtr->objectType() == this ); switch( mem.type() ) { case QSMember::NativeFunction: return (*mem.nativeFunction)( env() ); case QSMember::NativeVoidFunction: (*mem.nativeVoidFunction)( env() ); return createUndefined(); case QSMember::NativeMemberFunction: Q_ASSERT( !mem.isStatic() ); qWarning( "This should never be called!!" ); return createUndefined(); case QSMember::ScriptFunction: { Q_ASSERT( mem.scriptFunction ); const QSList *args = env()->arguments(); #ifdef QSDEBUGGER Debugger *dbg = env()->engine()->debugger(); // arguments as string for call stack info QString argStr = QString::fromLatin1(""); for ( int j = 0; j < args->size(); j++ ) { if ( j > 0 ) argStr += QString::fromLatin1(", "); QSObject a = args->at( j ); argStr += a.toString() + QString::fromLatin1(" : ") + a.typeName(); } QString n = mem.scriptFunction->scopeDefinition()->identifier(); if( dbg ) dbg->callEvent( n, argStr ); // debugger has to be told that we are potentially // jumping to script code in a different source unit int oldSourceId = -1; if ( dbg ) { oldSourceId = dbg->sourceId(); dbg->setSourceId( mem.scriptFunction->sourceId() ); } #endif QSFunctionScopeClass *scopeDef = mem.scriptFunction->scopeDefinition(); // qDebug( "Calling function: " + scopeDef->identifier() ); // qDebug( "objPtr is: " + objPtr->objectType()->identifier() ); // qDebug( "currentScope is: " + env()->currentScope().objectType()->identifier() ); // env()->printScopeChain(); // Use invalid object for scopes that don't have variables.. QSObject scope = scopeDef->construct( *args ); QSObject returnValue; if ( compareScopes( *objPtr, env()->currentScope() ) ) { // qDebug( "Push scope type 1" ); env()->pushScope( scope ); returnValue = mem.scriptFunction->execute( env() ); env()->popScope(); } else if( objPtr->objectType()->enclosingClass()==env()->currentScope().objectType() ) { // qDebug( "Push scope type 1b" ); env()->pushScope( *objPtr ); env()->pushScope( scope ); returnValue = mem.scriptFunction->execute( env() ); env()->popScope(); env()->popScope(); } else if ( objPtr->objectType()->enclosingClass() == 0 ) { // qDebug( "Push scope type 1c" ); env()->pushScopeBlock(); env()->pushScope( env()->globalObject() ); env()->pushScope( *objPtr ); env()->pushScope( scope ); // env()->printScopeChain(); returnValue = mem.scriptFunction->execute( env() ); env()->popScopeBlock(); } else if ( env()->currentScope().objectType() == env()->globalObject().objectType() ) { // object has an enclosing class, but current scope is only global // qDebug( "Push scope type 1d" ); env()->pushScopeBlock(); env()->pushScope( env()->globalObject() ); env()->pushScope( *objPtr ); env()->pushScope( scope ); returnValue = mem.scriptFunction->execute( env() ); env()->popScopeBlock(); } else { // qDebug( "Push scope type 2" ); // ### This loop is a duplicate of the one already done in resolvenode ScopeChain chain = env()->scope(); ScopeChain::Iterator it = chain.begin(); bool pushObj = FALSE; while( it!=chain.end() ) { if( compareScopes( *it, *objPtr ) ) { break; } else if ( (*it).objectType() == objPtr->objectType()->enclosingClass() ) { pushObj = TRUE; break; } else { it = chain.remove( it ); } } env()->pushScopeBlock(); while( chain.size()>0 ) { env()->pushScope( chain.back() ); chain.pop_back(); } if( pushObj ) env()->pushScope( *objPtr ); env()->pushScope( scope ); // env()->printScopeChain(); returnValue = mem.scriptFunction->execute( env() ); env()->popScopeBlock(); } #ifdef QSDEBUGGER if ( dbg ) dbg->returnEvent(); // restore previous source id if (dbg) dbg->setSourceId(oldSourceId); #endif return env()->isReturnValueMode() ? returnValue : createUndefined(); } case QSMember::Variable: { QSObject o = fetchValue( objPtr, mem ); if ( o.objectType()->valueType() == TypeClass ) return QSTypeClass::classValue(&o)->cast( *env()->arguments() ); qFatal( "QSClass::invoke: Unhandled variable type" ); break; } default: qFatal( "QSClass::invoke: Unhandled switch case %d", mem.type() ); } return createUndefined(); } void QSClass::addFunctionMember( const QString &n, QSFunctionBodyNode * f, int attributes ) { addMember( n, QSMember( f, attributes ), createUndefined() ); } int QSClass::addVariableMember( const QString &n, int attributes ) { addMember( n, QSMember( QSMember::Variable, attributes ), createUndefined() ); return attributes & AttributeStatic ? numStaticVars - 1 : numVars-1; } void QSClass::addStaticVariableMember( const QString &name, const QSObject &value, int attr ) { addMember( name, QSMember( QSMember::Variable, attr | AttributeStatic ), value ); } /*! Add member \a member with name \a n to this class. \stVal contains the value if the member is a static variable. */ void QSClass::addMember( const QString &n, const QSMember &member, const QSObject &stVal ) { Q_ASSERT( !mmap->contains( n ) ); QSMember m = member; m.setName( n ); m.setOwner( this ); switch (m.type()) { case QSMember::Variable: if( m.isStatic() ) { m.setIndex( numStaticVars++ ); staticMembers.append( stVal ); } else { m.setIndex( numVars++ ); } break; case QSMember::ScriptFunction: m.scriptFunction->ref(); // Since it is stored by member. break; default: break; } mmap->insert( n, m ); } /* Factored out from replace member */ void QSClass::removeStaticVar( const QSMember &old ) { staticMembers.remove( staticMembers.at(old.idx) ); QSMemberMap::iterator it = mmap->begin(); while( it!=mmap->end() ) { QSMember &cur = *it; if( cur.type()==QSMember::Variable && cur.isStatic() && cur.idx>old.idx ) cur.idx--; it++; } numStaticVars--; } /* Factored out from replaceMember */ void QSClass::fillMemberVarIndex( QSMember *member ) { if( !replacedVars.isEmpty() ) { // Reuse old varspace if possible. member->idx = replacedVars[0]; replacedVars.pop_front(); } else { member->idx = numVars++; } } /*! Replaces the member \name with \member. \stVal can contain the value if the member is a static variable. */ void QSClass::replaceMember( const QString &name, QSMember *member, const QSObject &stVal ) { // qDebug( "QSClass::replaceMember(%s)", name.latin1() ); Q_ASSERT( mmap->contains( name ) ); QSMember old = *(mmap->find( name )); QSMember &m = *member; m.setName( name ); m.setOwner( this ); // Delete old function implementation. if (old.type() == QSMember::ScriptFunction) { if (old.scriptFunction->deref()) { // will delete delete old.scriptFunction; old.scriptFunction = 0; } else { if (old.scriptFunction->scopeDefinition()) old.scriptFunction->setScopeDefinition(0); old.scriptFunction->setScopeDefinition(0); } } // Ref new one... if (m.type() == QSMember::ScriptFunction) m.scriptFunction->ref(); if( old.type()==QSMember::Variable && m.type()==QSMember::Variable ) { if( old.isStatic() == m.isStatic() ) { // both static or both nonstatic m.idx = old.idx; if( old.isStatic() ) // replace value if static staticMembers[m.idx] = stVal; } else if( old.isStatic() ) { removeStaticVar( old ); fillMemberVarIndex( &m ); } else if( m.isStatic() ) { m.idx = numStaticVars++; staticMembers.append( stVal ); replacedVars.append( old.idx ); } } else if( (old.type()==QSMember::ScriptFunction || old.type()==QSMember::NativeFunction || old.type()==QSMember::NativeMemberFunction) && (m.type()==QSMember::ScriptFunction || m.type()==QSMember::NativeFunction || m.type()==QSMember::NativeMemberFunction) ) { // Replace only... } else if ( old.type()==QSMember::Variable ) { // Variable -> function if( old.isStatic() ) { // Delete and update member indexes removeStaticVar( old ); } else { // Store index for reuse later. replacedVars.append( old.idx ); } } else if ( m.type()==QSMember::Variable ) { if( m.isStatic() ) { m.idx = numStaticVars++; staticMembers.append( stVal ); } else { fillMemberVarIndex( &m ); } } else { qFatal( "QSClass::replaceMember() -- Unhandled case" ); } mmap->replace( name, m ); } /*! Deletes the member under name \name. If deletion was not possible, FALSE is returned */ bool QSClass::deleteMember( const QString &name ) { if( !mmap->contains( name ) ) { return FALSE; } // ### What do we do about variable indexes?? mmap->remove( name ); return TRUE; } bool QSClass::hasProperty( const QSObject *obj, const QString &p ) const { // standard class property ? QSMember m; if ( member( obj, p, &m ) && m.type() != QSMember::Identifier ) return TRUE; // // dynamic property // return data( obj )->hasProperty( p ); return FALSE; } QSObject QSClass::get( const QSObject *objPtr, const QString &p ) const { QSMember mem; if ( !member( objPtr, p, &mem ) || mem.type() == QSMember::Identifier ) return createUndefined(); return fetchValue( objPtr, mem ); } void QSClass::put( QSObject *objPtr, const QString &p, const QSObject &v ) const { QSMember mem; if ( !member( objPtr, p, &mem ) && mem.type() != QSMember::Identifier ) { qWarning( "QSClass::put: refused write of %s", p.ascii() ); return; } mem.setName( p ); write( objPtr, mem, v ); } QSObject QSClass::construct( const QSList & /* args */ ) const { return createUndefined(); } QSObject QSClass::cast( const QSList &args ) const { return args.size() > 0 ? args[0] : createUndefined() ; } /*! Returns the map of members of \a obj or class members if \a obj is 0. The default implementation will list all members pre-defined via the addMember() function or one of its specializations. Class inherting from QSClass can reimplement this function to also give information about custom properties. */ QSMemberMap QSClass::members( const QSObject *obj ) const { Q_ASSERT( mmap ); if ( obj ) return *mmap; QSMemberMap m; QSMemberMap::const_iterator it = mmap->begin(); for ( ; it != mmap->end(); ++it ) if ( (*it).isStatic() ) m.insert( it.key(), it.data() ); return m; } /*! Convenience function to throw an error of type \a a with the user visible message \a msg. */ void QSClass::throwError( ErrorType e, const QString &msg ) const { (void)env()->throwError( e, msg, -1 ); } QSObject QSClass::createString( const QString &s ) const { return en->createString( s ); } QSObject QSClass::createNumber( double d ) const { return en->createNumber( d ); } QSObject QSClass::createBoolean( bool b ) const { return en->createBoolean( b ); } QSObject QSClass::createUndefined() const { return en->createUndefined(); } QSObject QSClass::createNull() const { return en->createNull(); } bool QSUndefinedClass::toBoolean( const QSObject * ) const { return FALSE; } double QSUndefinedClass::toNumber( const QSObject * ) const { return NaN; } QString QSUndefinedClass::toString( const QSObject * ) const { return QString::fromLatin1("undefined"); } QSObject QSUndefinedClass::toPrimitive( const QSObject *obj, const QSClass * ) const { return *obj; } QSEqualsResult QSUndefinedClass::isEqual( const QSObject &a, const QSObject &b ) const { Q_ASSERT( a.isA( this ) ); if ( b.isUndefined() || b.isNull() ) return EqualsIsEqual; else return EqualsUndefined; } bool QSNullClass::toBoolean( const QSObject * ) const { return FALSE; } double QSNullClass::toNumber( const QSObject * ) const { return 0.0; } QString QSNullClass::toString( const QSObject * ) const { return QString::fromLatin1("null"); } QSObject QSNullClass::toPrimitive( const QSObject *obj, const QSClass * ) const { return *obj; } QSEqualsResult QSNullClass::isEqual( const QSObject &a, const QSObject &b ) const { Q_ASSERT( a.isA( this ) ); if( b.isNull() || b.isUndefined() ) return EqualsIsEqual; return EqualsUndefined; } bool QSCharacterClass::toBoolean( const QSObject *obj ) const { return !obj->sVal()[0].isNull(); } double QSCharacterClass::toNumber( const QSObject *obj ) const { return QSString::toDouble( obj->sVal() ); } QString QSCharacterClass::toString( const QSObject *obj ) const { return obj->sVal(); } void QSSharedClass::ref( QSObject * o ) const { #ifndef QS_LEAK o->shVal()->ref(); #endif } void QSSharedClass::deref( QSObject * o ) const { #ifndef QS_LEAK o->shVal()->deref(); if( o->shVal()->count==0 ) { env()->removeShared( o->shVal() ); delete o->shVal(); o->setVal( (QSShared*)0 ); // for debugging purposes only } #endif } QSClassClass::QSClassClass( QSClass *b, int a, const QString &n ) : QSSharedClass( b, a ), cname( n ), defaultCtor( FALSE ), bodyNode( 0 ), clDefNode(0) { memberInit = new QSNodeList(); staticInit = new QSNodeList(); } QSClassClass::~QSClassClass() { // If shut down, we cannot allow other classes to be deleted as this will // mess up the iterators calling finalize, clear and delete in QSEnv::clear(). if (env()->isShuttingDown()) { if (bodyNode->scopeDefinition()) bodyNode->scopeDefinition()->setFunctionBodyNode(0); bodyNode->setScopeDefinition(0); } clDefNode->setClassDefinition(0); if (clDefNode->deref()) { delete clDefNode; bodyNode = 0; clDefNode = 0; } delete memberInit; delete staticInit; } bool QSClassClass::toBoolean( const QSObject * ) const { return TRUE; } double QSClassClass::toNumber( const QSObject * ) const { return NaN; } QString QSClassClass::toString( const QSObject * ) const { return QString::fromLatin1("[class ") + cname + QString::fromLatin1("]"); } QSInstanceData* QSClassClass::data( QSObject *obj ) { return (QSInstanceData*)obj->shVal(); } const QSInstanceData* QSClassClass::data( const QSObject *obj ) { return (const QSInstanceData*)obj->shVal(); } /*! \reimp Construct an instance of the class described by this object. */ QSObject QSClassClass::construct( const QSList &args ) const { /* Look for non QSClassClass in parent chain. Can only be object class. If anything else, it must be a QSAbstractBaseClass, which is an error at this point. */ QSClass *baseChain = base(); while (baseChain && baseChain->asClass()) baseChain = baseChain->base(); if (baseChain && baseChain->name() == QString::fromLatin1("AbstractBase")) { return env()->throwError(QString(QString::fromLatin1("class '%1' is %2derived from undefined class '%3'")) .arg(cname) .arg(baseChain == base() ? QString::fromLatin1("") : QString::fromLatin1("indirectly ")) .arg(baseChain->identifier())); } // Initialize all entries to undefined QSInstanceData *data = new QSInstanceData( numVariables(), createUndefined() ); for( int i=0; i < numVariables(); i++ ) data->setValue( i, createUndefined() ); QSObject inst = env()->createShared( this, data ); // Set up scope ScopeChain chain = env()->scope(); ScopeChain::Iterator sit = chain.begin(); while( sit!=chain.end() ) { if( (*sit).objectType()==enclosingClass() ) { break; } sit = chain.remove( sit ); } // Fill up scope chain. env()->pushScopeBlock(); while( chain.size()>0 ) { env()->pushScope( chain.back() ); chain.pop_back(); } env()->pushScope( inst ); initVariables( data ); // Clean up scope env()->popScopeBlock(); if ( hasDefaultConstructor() && !env()->isExceptionMode() ) { QSObject ctor = get( &inst, cname ); Q_ASSERT( ctor.isExecutable() ); ctor.invoke( QSMember(), args ); // ### do something with the return value/type ? } return inst; } QSEqualsResult QSClassClass::isEqual( const QSObject &a, const QSObject &b ) const { if( b.objectType() == this ) { return ( QSEqualsResult ) ( b.shVal() == a.shVal() ); } return EqualsNotEqual; } void QSClassClass::addMemberInitializer( QSNode * node ) { memberInit->append( node ); } void QSClassClass::addStaticInitializer( QSNode * node ) { staticInit->append( node ); } void QSClassClass::setClassBodyNode( QSFunctionBodyNode * node ) { bodyNode = node; } /*! Execute statements contained in this class' block. */ void QSClassClass::executeBlock( QSEnv *env ) { // Set up scope ScopeChain chain = env->scope(); ScopeChain::Iterator sit = chain.begin(); while( sit!=chain.end() ) { if( (*sit).objectType()==enclosingClass() ) { break; } sit = chain.remove( sit ); } // Fill up scope chain. env->pushScopeBlock(); while( chain.size()>0 ) { env->pushScope( chain.back() ); chain.pop_back(); } // Push the type object... env->pushScope( env->globalObject().get(cname) ); // Call initializers QPtrListIterator<QSNode> it( *staticInit ); for ( uint j = 0; j<staticInit->count(); j++ ) { QSNode *init = it(); if ( init ) { setStaticMember( j, init->rhs( env ) ); // abort if init code caused an error if ( env->isExceptionMode() ) break; } } if( bodyNode ) bodyNode->execute( env ); // Clean up scope env->popScopeBlock(); } /*! \internal Runs the initializers on the variables declared in this class. This function assumes that scopes are set up correctly and can only be called from within the QSClassClass::construct function. */ int QSClassClass::initVariables( QSInstanceData * data ) const { int offset = 0; QSClassClass *cl = base() ? base()->asClass() : 0; if( cl ) offset = cl->initVariables( data ); // Call initializers QPtrListIterator<QSNode> it( *memberInit ); for ( uint j = 0; j<memberInit->count(); j++ ) { QSNode *init = it(); if ( init ) { data->setValue( offset + j, init->rhs( env() ) ); // abort if init code caused an error if ( env()->isExceptionMode() ) break; } } return offset + memberInit->count(); } /*! \reimp */ void QSWritableClass::mark( QSObject * /*o*/ ) const { } bool QSWritableClass::member( const QSObject *o, const QString &n, QSMember *m ) const { // qDebug( "QSWritableClass::member() class = %s, name = %s", name().latin1(), n.latin1() ); Q_ASSERT( /* o &&*/ !n.isEmpty() ); Q_ASSERT( m ); if( !o || !o->isDefined() ) { return QSClass::member( o, n, m ); } if( !o->shVal() ) { return QSClass::member( 0, n, m ); } // The error here is that the object is a dummy!!! const QSWritable *w = (QSWritable*) o->shVal(); //data( o ); if ( !w->hasProperty( n ) ) { if ( QSClass::member( o, n, m ) ) return TRUE; // property doesn't exit, yet. We'll offer to create a new one m->setType( QSMember::Identifier ); m->setName( n ); m->setOwner( this ); return FALSE; } m->setType( QSMember::Object ); m->obj = &w->reference( n )->object; m->setName( n ); m->setOwner( this ); return TRUE; } QSObject QSWritableClass::fetchValue( const QSObject *objPtr, const QSMember &mem ) const { // qDebug( "QSWritableClass::fetchValue() -> mem.type = %s", mem.typeName().latin1() ); if( mem.type()==QSMember::Object ) { return *mem.obj; } return QSClass::fetchValue( objPtr, mem ); } void QSWritableClass::write( QSObject *objPtr, const QSMember &mem, const QSObject &val ) const { // qDebug( "QSWritableClass::write() -> mem.type = %s", mem.typeName().latin1() ); if( mem.type()==QSMember::Object ) { *mem.obj = val; } else if( mem.type()==QSMember::Identifier ) { // qDebug( "Writing to QSMember::Identifier: name = %s", mem.str.latin1() ); data( objPtr )->setProperty( mem.name(), QSProperty( val ) ); } else { QSClass::write( objPtr, mem, val ); } } bool QSWritableClass::deleteProperty( QSObject *obj, const QSMember &mem ) const { if ( mem.type()==QSMember::Object ) { properties( obj )->remove( mem.name() ); return TRUE; } return FALSE; } QSObject QSWritableClass::invoke( QSObject * objPtr, const QSMember &mem ) const { if( mem.type()==QSMember::Object ) { Q_ASSERT( mem.obj->isValid() ); return objPtr->invoke( mem, *env()->arguments() ); } return QSClass::invoke( objPtr, mem ); } QSWritable *QSWritableClass::data( QSObject *obj ) { return (QSWritable*)obj->shVal(); } const QSWritable *QSWritableClass::data( const QSObject *obj ) { return (const QSWritable*)obj->shVal(); } /*! Create an empty, writable object of this class. */ QSObject QSWritableClass::createWritable() const { return QSObject( this, new QSWritable() ); } QSPropertyMap *QSWritableClass::properties( const QSObject *obj ) const { return data( obj )->properties(); } /*! \reimp Returns the pre-defined members plus dynamic properties of \a obj. */ QSMemberMap QSWritableClass::members( const QSObject *obj ) const { QSMemberMap map = QSClass::members( obj ); if ( obj ) { QSPropertyMap *pmap = properties( obj ); if ( pmap ) { QSPropertyMap::ConstIterator it = pmap->begin(); while ( it != pmap->end() ) { QSMember mem( QSMember::Object, AttributeEnumerable ); mem.setName( it.key() ); mem.setExecutable( it.data().object.isExecutable() ); map.insert( it.key(), mem ); ++it; } } } return map; } QSEqualsResult QSWritableClass::isEqual( const QSObject &a, const QSObject &b ) const { if( b.objectType() == this ) { return ( QSEqualsResult ) ( b.shVal() == a.shVal() ); } return EqualsNotEqual; } QSFunctionScopeClass::QSFunctionScopeClass( QSClass *b, QSFuncDeclNode * func ) : QSWritableClass( b ), ident(func->identifier()), numArgs( 0 ), body_node(0) { } QString QSFunctionScopeClass::identifier() const { return ident.isNull() ? QString(QString::fromLatin1("[anonymous]")) : ident; } void QSFunctionScopeClass::clear() { if (body_node) body_node->setScopeDefinition(0); body_node = 0; QSWritableClass::clear(); } QSObject QSFunctionScopeClass::construct( const QSList &args ) const { // qDebug( "Creating functions scope for: " + identifier() + ", %d", numVariables() ); QSInstanceData *dat = new QSInstanceData( numVariables(), createUndefined() ); QSObject scope = env()->createShared( this, dat ); // fill slots for passed arguments QSListIterator it = args.begin(); int i = 0; while ( it != args.end() && i < numArguments() ) { dat->setValue( i, *it ); it++; i++; } // intialize remaining ones with "undefined" while ( i < numArguments() ) dat->setValue( i++, createUndefined() ); QSArray argObj( env() ); it = args.begin(); for ( i = 0; it != args.end(); ++i, ++it ) argObj.put( QString::number( i ), *it ); scope.put( QString::fromLatin1("arguments"), argObj ); return scope; } QSObject QSEvalScopeClass::construct( const QSList & ) const { return env()->createShared( this, new QSInstanceData( numVariables(), createUndefined() ) ); } void QSBlockScopeClass::activateScope() const { QSObject scope( this ); scope.setVal( env()->currentScope().shVal() ); ref( &scope ); env()->pushScope( scope ); } void QSBlockScopeClass::deactivateScope() const { env()->popScope(); } QSMemberMap QSBlockScopeClass::members( const QSObject *obj ) const { QSMemberMap newMap( *definedMembers() ); QSMemberMap encMap = enclosingClass()->members( obj ); QSMemberMap::ConstIterator it = encMap.begin(); while( it!=encMap.end() ) { newMap[ it.key() ] = it.data(); it++; } return newMap; } class QSTypeClassShared : public QSShared { public: QSTypeClassShared(QSClass *cl) : classValue(cl) { } ~QSTypeClassShared() { // Delete the class when it is cleared. if (!classValue->env()->isShuttingDown()) { classValue->env()->unregisterClass(classValue); classValue->clear(); delete classValue; } } QSClass *classValue; }; QSShared *QSTypeClass::createTypeShared(QSClass *cl) const { return new QSTypeClassShared(cl); } QSObject QSTypeClass::createType(QSClass *cl) const { return QSObject(this, new QSTypeClassShared(cl)); } QSClass *QSTypeClass::classValue(const QSObject *obj) { Q_ASSERT(obj->objectType()->inherits(obj->objectType()->env()->typeClass())); return ((QSTypeClassShared *)obj->shVal())->classValue; } bool QSTypeClass::member( const QSObject *o, const QString &n, QSMember *m ) const { if( !o ) return FALSE; Q_ASSERT( o->isA( this ) ); QSClass *tcl = classValue(o); return tcl->member( 0, n, m ); } QSMemberMap QSTypeClass::members( const QSObject *obj ) const { Q_ASSERT( obj->isA( this ) ); if ( ( ( const QSClass * ) classValue(obj) ) == this ) return QSClass::members( obj ); else return classValue(obj)->members( 0 ); } QSMemberMap QSTypeClass::allMembers( const QSObject *obj ) const { Q_ASSERT( obj->isA( this ) ); if ( ( ( const QSClass * ) classValue(obj) ) == this ) return QSClass::members( obj ); else return *( classValue(obj)->definedMembers() ); } QSObject QSTypeClass::fetchValue( const QSObject *o, const QSMember &mem ) const { Q_ASSERT( o->isA( this ) ); if ( !mem.hasAttribute( AttributeStatic ) ) { throwError( ReferenceError, QString::fromLatin1("Cannot access a non-static member " "without an object reference") ); return createUndefined(); } QSClass *tcl = classValue(o); return tcl->fetchValue( o, mem ); } QSObject QSTypeClass::invoke( QSObject *o, const QSMember &mem ) const { Q_ASSERT( o->objectType()==this ); // we are not interested in static functions if ( mem.isStatic() ) return QSClass::invoke( o, mem ); else if( mem.type()==QSMember::Variable ) // Indirect casting. return classValue(o)->cast( *env()->arguments() ); throwError( ReferenceError, QString::fromLatin1("Cannot invoke a non-static function " "without an object reference") ); return createUndefined(); } void QSTypeClass::write( QSObject *objPtr, const QSMember &mem, const QSObject &val ) const { Q_ASSERT( mem.isWritable() ); // Q_ASSERT( mem.type()==QSMember::Variable ); if ( !mem.hasAttribute( AttributeStatic ) ) { throwError( ReferenceError, QString::fromLatin1("Cannot access a non-static member " "without an object reference") ); return; } QSClass * cl = classValue(objPtr); if( mem.type()==QSMember::Variable ) { cl->setStaticMember( mem.idx, val ); } else { throwError( ReferenceError, QString::fromLatin1("Trying to write to a nonvariable") ); return; } } QSEqualsResult QSTypeClass::isEqual( const QSObject &a, const QSObject &b ) const { if( b.objectType()==this ) { return ( QSEqualsResult ) ( classValue(&a) == classValue(&b) ); } return EqualsUndefined; } static void qs_dumpclass( const QSClass *cl ) { printf( "class %s", cl->identifier().latin1() ); printf( " - %s\n", cl->isExecutable() ? "executable" : "not executable" ); printf( " - %s\n", cl->isFinal() ? "final" : "not final" ); QSMemberMap::Iterator it = cl->definedMembers()->begin(); for( ; it!=cl->definedMembers()->end(); it++ ) { QSMember mem = *it; QString line = QString(QString::fromLatin1(" ")) + mem; printf( "%s\n", line.latin1() ); } if( cl->enclosingClass() ) qs_dumpclass( cl->enclosingClass() ); if( cl->base() ) qs_dumpclass( cl->base() ); } static void qs_dumptype( const QSList &args ) { if ( args.size()>=1 && args[0].objectType()==args[0].objectType()->env()->typeClass() ) { printf( "DUMP TYPE::\n" ); QSObject arg0 = args[0]; QSClass *cl = QSTypeClass::classValue(&arg0); qs_dumpclass( cl ); } printf( "\n" ); } static void qs_dumpobject( const QSObject &obj ) { const QSClass * cl = obj.objectType(); printf( "DUMP OBJECT:: %p\n", obj.shVal() ); printf( "class %s :: %s\n", cl->name().latin1(), cl->identifier().latin1() ); QSMemberMap::Iterator it = cl->definedMembers()->begin(); for( ; it!=cl->definedMembers()->end(); it++ ) { QSMember mem = *it; if( mem.isReadable() ) { QSObject value = cl->fetchValue( &obj, mem ); if( mem.type()==QSMember::Variable ) printf( " %2d: %s = %s\n", mem.index(), mem.name().latin1(), value.toString().latin1() ); else printf( " %s = %s\n", mem.name().latin1(), value.toString().latin1() ); } } } QSDebugClass::QSDebugClass( QSClass *base ) : QSClass( base, AttributeAbstract ) { addMember( QString::fromLatin1("dumpObject"), QSMember( &dumpObject, AttributeNonWritable|AttributeStatic ) ); addMember( QString::fromLatin1("dumpScope"), QSMember( &dumpScope, AttributeNonWritable|AttributeStatic ) ); addMember( QString::fromLatin1("dumpType"), QSMember( &dumpType, AttributeNonWritable|AttributeStatic ) ); } void QSDebugClass::dumpObject( QSEnv * env ) { qs_dumpobject( ( env->numArgs() > 0 ? env->arg( 0 ) : env->createUndefined() ) ); } void QSDebugClass::dumpScope( QSEnv * env ) { ScopeChain chain = env->scope(); ScopeChain::ConstIterator it = chain.begin(); qDebug( "\n---------- DUMP SCOPE ----------" ); while( it!=chain.end() ) { qs_dumpobject( *it ); if( (*it).objectType() == env->typeClass() ) { QSList itList( *it ); qs_dumptype( itList ); } it++; } qDebug( "---------- DUMP COMPLETE ----------" ); } void QSDebugClass::dumpType( QSEnv * env ) { qs_dumptype( *env->arguments() ); } QSSystemClass::QSSystemClass( QSClass *base ) : QSClass( base, AttributeAbstract ) { addMember( QString::fromLatin1("print"), QSMember( &print, AttributeNonWritable | AttributeStatic ) ); addMember( QString::fromLatin1("println"), QSMember( &println, AttributeNonWritable | AttributeStatic ) ); addMember( QString::fromLatin1("getenv"), QSMember( &getenv, AttributeNonWritable | AttributeStatic ) ); addMember( QString::fromLatin1("setenv"), QSMember( &setenv, AttributeNonWritable | AttributeStatic ) ); } void QSSystemClass::println( QSEnv *env ) { printf( "%s\n", env->arg( 0 ).toString().latin1() ); } void QSSystemClass::print( QSEnv *env ) { printf( "%s", env->arg( 0 ).toString().latin1() ); } QSObject QSSystemClass::getenv( QSEnv *env ) { return env->createString( QString::fromLatin1(::getenv( env->arg( 0 ).toString().latin1() )) ); } void QSSystemClass::setenv( QSEnv *env ) { #if defined(Q_OS_HPUX) || defined(Q_OS_IRIX) || defined(Q_OS_SOLARIS) || defined( Q_CC_BOR ) putenv( (char*)( env->arg( 0 ).toString() + "=" + env->arg( 1 ).toString() ).latin1() ); // char* on Solaris #elif defined(Q_OS_WIN32) _putenv( QString::fromLatin1("%1=%2") .arg(env->arg( 0 ).toString()) .arg(env->arg( 1 ).toString() ).latin1() ); #else ::setenv( (char *)env->arg( 0 ).toString().latin1(), (char *)env->arg( 1 ).toString().latin1(), 1 ); #endif } /* Implementation of the QSAbstractBaseClass. * Used primarly to support cross referencing of class between files, e.g. * declaring a class in one file and deriving from it in another. */ void QSAbstractBaseClass::replace(QSClassClass *newBase) { QPtrList<QSClassClass> userClasses; QPtrList<QSClass> allClasses = env()->classes(); // Build a list of the user classes, excluding this one. QPtrListIterator<QSClass> it(allClasses); QSClass *tmp; while ((tmp = it())) if (tmp->asClass() && tmp != newBase) userClasses.append((QSClassClass*)tmp); // Check if userclasses have this abstract class definition as parent and update // member table if so. QPtrListIterator<QSClassClass> userIt(userClasses); QPtrList<QSClassClass> directChildren; QSClassClass *userClass; while ((userClass = userIt())) { QSClass *baseClass = userClass->base(); // Directly derived, base pointer must be updated later if (userClass->base() == this) directChildren.append(userClass); while (baseClass && baseClass != this) baseClass = baseClass->base(); // update offsets in member table... if (baseClass == this) { userClass->setNumVariables(newBase->numVariables() + userClass->numVariables()); QSMemberMap *mems = userClass->definedMembers(); for (QSMemberMap::Iterator it = mems->begin(); it != mems->end(); ++it) { QSMember &m = (*it); if (m.type() == QSMember::Variable && !m.isStatic()) m.setIndex(m.index()+newBase->numVariables()); } } } userIt = QPtrListIterator<QSClassClass>(directChildren); while ((userClass = userIt())) userClass->setBase(newBase); // We no longer serve any purpose, so we disappear... env()->unregisterClass(this); clear(); delete this; }; QSInstanceData::QSInstanceData( int count, const QSObject &def ) { vals = new QSObject[count]; sz = count; for( int i=0; i<count; i++ ) vals[i] = def; } void QSInstanceData::resize( int count, const QSObject &def ) { QSObject *tmp = vals; vals = new QSObject[count]; for( int i=0; i<sz; i++ ) { vals[i] = tmp[i]; } for( int j=sz; j<count; j++ ) vals[j] = def; delete [] tmp; sz = count; } /*! Insure that this object has enough space for \a count objects. If that is already the case the array won't be resized. */ void QSInstanceData::ensureSize( int count, const QSObject &def ) { if ( count > sz ) resize( count, def ); } /*! Invalidates all the objects in this instance data so that it can be destroyed at a later time without any problems without further reference counting. */ void QSInstanceData::invalidate() { for( int i=0; i<sz; i++ ) { vals[i].invalidate(); } QSWritable::invalidate(); } QString operator+( const QString &a, const QSMember &b ) { QString s; s.sprintf( "QSMember(%s.%s, %s, %x)", b.owner() ? b.owner()->identifier().latin1() : "(no owner)", b.name().latin1(), b.typeName().latin1(), b.attributes() ); return a + s; } bool operator==( const QSMember &a, const QSMember &b ) { return a.type() == b.type() && a.owner() == b.owner() && !a.name().isEmpty() && a.name() == b.name(); }
26.810306
109
0.622215
hackbinary
b43ec0380d4b35390ef75f81a83167bf90a6fc1e
15,264
cpp
C++
addons/ofxUI/example-AllWidgets/src/ofApp.cpp
k4rm/AscoGraph
9038ae785b6f4f144a3ab5c4c5520761c0cd08f2
[ "MIT" ]
18
2015-01-18T22:34:22.000Z
2020-09-06T20:30:30.000Z
addons/ofxUI/example-AllWidgets/src/ofApp.cpp
k4rm/AscoGraph
9038ae785b6f4f144a3ab5c4c5520761c0cd08f2
[ "MIT" ]
2
2015-08-04T00:07:46.000Z
2017-05-10T15:53:51.000Z
addons/ofxUI/example-AllWidgets/src/ofApp.cpp
k4rm/AscoGraph
9038ae785b6f4f144a3ab5c4c5520761c0cd08f2
[ "MIT" ]
10
2015-01-18T23:46:10.000Z
2019-08-25T12:10:04.000Z
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetCircleResolution(120); red = 233; blue = 233; green = 233; hideGUI = false; bdrawGrid = false; bdrawPadding = false; ddl = NULL; textInput = NULL; img = new ofImage(); img->loadImage("nerd_me.png"); buffer = new float[256]; for(int i = 0; i < 256; i++) { buffer[i] = ofNoise(i/100.0); } setGUI1(); setGUI2(); setGUI3(); setGUI4(); setGUI5(); gui1->loadSettings("gui1Settings.xml"); gui2->loadSettings("gui2Settings.xml"); gui3->loadSettings("gui3Settings.xml"); gui4->loadSettings("gui4Settings.xml"); gui5->loadSettings("gui5Settings.xml"); } //-------------------------------------------------------------- void ofApp::update(){ mg->addPoint(buffer[0]); for(int i = 0; i < 256; i++) { buffer[i] = ofNoise(i/100.0, ofGetElapsedTimef()); } } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(red, green, blue, 255); ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_ALPHA); if(bdrawGrid) { ofSetColor(255, 255, 255, 25); drawGrid(8,8); } ofPopStyle(); ofSetRectMode(OF_RECTMODE_CENTER); } void ofApp::guiEvent(ofxUIEventArgs &e) { string name = e.getName(); int kind = e.getKind(); cout << "got event from: " << name << endl; if(kind == OFX_UI_WIDGET_NUMBERDIALER) { ofxUINumberDialer *n = (ofxUINumberDialer *) e.widget; cout << n->getValue() << endl; } if(name == "SAMPLER") { ofxUIImageSampler *is = (ofxUIImageSampler *) e.widget; ofColor clr = is->getColor(); red = clr.r; blue = clr.b; green = clr.g; } else if(name == "BUTTON") { ofxUIButton *button = (ofxUIButton *) e.getButton(); bdrawGrid = button->getValue(); } else if(name == "TOGGLE") { ofxUIToggle *toggle = (ofxUIToggle *) e.getToggle(); bdrawGrid = toggle->getValue(); if(textInput != NULL) { textInput->setFocus(bdrawGrid); } } else if(name == "RADIO VERTICAL") { ofxUIRadio *radio = (ofxUIRadio *) e.widget; cout << radio->getName() << " value: " << radio->getValue() << " active name: " << radio->getActiveName() << endl; } else if(name == "TEXT INPUT") { ofxUITextInput *ti = (ofxUITextInput *) e.widget; if(ti->getInputTriggerType() == OFX_UI_TEXTINPUT_ON_ENTER) { cout << "ON ENTER: "; } else if(ti->getInputTriggerType() == OFX_UI_TEXTINPUT_ON_FOCUS) { cout << "ON FOCUS: "; } else if(ti->getInputTriggerType() == OFX_UI_TEXTINPUT_ON_UNFOCUS) { cout << "ON BLUR: "; } string output = ti->getTextString(); cout << output << endl; } } //-------------------------------------------------------------- void ofApp::exit() { gui1->saveSettings("gui1Settings.xml"); gui2->saveSettings("gui2Settings.xml"); gui3->saveSettings("gui3Settings.xml"); gui4->saveSettings("gui4Settings.xml"); gui5->saveSettings("gui5Settings.xml"); delete gui1; delete gui2; delete gui3; delete gui4; delete gui5; delete[] buffer; delete img; delete env; } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ if(gui2->hasKeyboardFocus()) { return; } switch (key) { case 't': { if(textInput != NULL) { textInput->setTextString(ofGetTimestampString()); } } break; case 'T': { if(tm != NULL) { int cols = tm->getColumnCount(); int rows = tm->getRowCount(); for(int row = 0; row < rows; row++) { for(int col = 0; col < cols; col++) { cout << tm->getState(row, col) << "\t"; } cout << endl; } } } break; case 'd': { if(ddl != NULL) { vector<ofxUIWidget *> selected = ddl->getSelected(); for(vector<ofxUIWidget *>::iterator it = selected.begin(); it != selected.end(); ++it) { ofxUILabelToggle *lt = (ofxUILabelToggle *) (*it); cout << lt->getName() << endl; } } } break; case 'D': { if(ddl != NULL) { vector<string> names = ddl->getSelectedNames(); for(vector<string>::iterator it = names.begin(); it != names.end(); ++it) { cout << (*it) << endl; } } } break; case 'r': { if(textInput != NULL) { textInput->setFocus(!textInput->isFocused()); } } break; case 'f': ofToggleFullscreen(); break; case 'F': { if(tm != NULL) { tm->setDrawOutlineHighLight(!tm->getDrawOutlineHighLight()); // tm->setDrawPaddingOutline(!tm->getDrawPaddingOutline()); } } break; case 'h': gui1->toggleVisible(); gui2->toggleVisible(); gui3->toggleVisible(); gui4->toggleVisible(); gui5->toggleVisible(); break; case 'p': bdrawPadding = !bdrawPadding; gui1->setDrawWidgetPaddingOutline(bdrawPadding); gui2->setDrawWidgetPaddingOutline(bdrawPadding); gui3->setDrawWidgetPaddingOutline(bdrawPadding); gui4->setDrawWidgetPaddingOutline(bdrawPadding); gui5->setDrawWidgetPaddingOutline(bdrawPadding); break; case '[': gui1->setDrawWidgetPadding(false); gui2->setDrawWidgetPadding(false); gui3->setDrawWidgetPadding(false); gui4->setDrawWidgetPadding(false); gui5->setDrawWidgetPadding(false); break; case ']': gui1->setDrawWidgetPadding(true); gui2->setDrawWidgetPadding(true); gui3->setDrawWidgetPadding(true); gui4->setDrawWidgetPadding(true); gui5->setDrawWidgetPadding(true); break; case '1': gui1->toggleVisible(); break; case '2': gui2->toggleVisible(); break; case '3': gui3->toggleVisible(); break; case '4': gui4->toggleVisible(); break; case '5': gui5->toggleVisible(); break; default: break; } } void ofApp::drawGrid(float x, float y) { float w = ofGetWidth(); float h = ofGetHeight(); for(int i = 0; i < h; i+=y) { ofLine(0,i,w,i); } for(int j = 0; j < w; j+=x) { ofLine(j,0,j,h); } } void ofApp::setGUI1() { vector<string> names; names.push_back("RAD1"); names.push_back("RAD2"); names.push_back("RAD3"); gui1 = new ofxUISuperCanvas("PANEL 1: BASICS"); gui1->addSpacer(); gui1->addLabel("Press 'h' to Hide GUIs", OFX_UI_FONT_SMALL); gui1->addSpacer(); gui1->addLabel("H SLIDERS"); gui1->addSlider("RED", 0.0, 255.0, &red)->setTriggerType(OFX_UI_TRIGGER_ALL); gui1->addSlider("GREEN", 0.0, 255.0, &green)->setTriggerType(OFX_UI_TRIGGER_BEGIN|OFX_UI_TRIGGER_CHANGE|OFX_UI_TRIGGER_END); gui1->addSlider("BLUE", 0.0, 255.0, &blue)->setTriggerType(OFX_UI_TRIGGER_BEGIN|OFX_UI_TRIGGER_CHANGE); gui1->addSpacer(); gui1->addLabel("V SLIDERS"); gui1->addSlider("0", 0.0, 255.0, 150, 17, 160); gui1->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT); gui1->addSlider("1", 0.0, 255.0, 150, 17, 160); gui1->addSlider("2", 0.0, 255.0, 150, 17, 160); gui1->addSlider("3", 0.0, 255.0, 150, 17, 160); gui1->addSlider("4", 0.0, 255.0, 150, 17, 160); gui1->addSlider("5", 0.0, 255.0, 150, 17, 160); gui1->addSlider("6", 0.0, 255.0, 150, 17, 160); gui1->addSlider("7", 0.0, 255.0, 150, 17, 160); gui1->addSlider("8", 0.0, 255.0, 150, 17, 160); gui1->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN); gui1->addSpacer(); gui1->addRadio("RADIO HORIZONTAL", names, OFX_UI_ORIENTATION_HORIZONTAL); gui1->addRadio("RADIO VERTICAL", names, OFX_UI_ORIENTATION_VERTICAL); gui1->addSpacer(); gui1->setWidgetFontSize(OFX_UI_FONT_SMALL); gui1->addButton("BUTTON", false); gui1->addToggle( "TOGGLE", false); gui1->addSpacer(); gui1->addLabel("RANGE SLIDER"); gui1->addRangeSlider("RSLIDER", 0.0, 255.0, 50.0, 100.0); string textString = "This widget is a text area widget. Use this when you need to display a paragraph of text. It takes care of formatting the text to fit the block."; gui1->addSpacer(); gui1->addTextArea("textarea", textString, OFX_UI_FONT_SMALL); gui1->autoSizeToFitWidgets(); ofAddListener(gui1->newGUIEvent,this,&ofApp::guiEvent); } void ofApp::setGUI2() { gui2 = new ofxUISuperCanvas("PANEL 2: ADVANCED"); gui2->addSpacer(); gui2->setWidgetFontSize(OFX_UI_FONT_MEDIUM); textInput = gui2->addTextInput("TEXT INPUT", "Input Text"); textInput->setAutoUnfocus(false); gui2->addLabel("AUTO CLEAR DISABLED", OFX_UI_FONT_SMALL); gui2->addTextInput("TEXT INPUT2", "Input Text")->setAutoClear(false); gui2->setWidgetFontSize(OFX_UI_FONT_MEDIUM); gui2->addSpacer(); gui2->addLabel("WAVEFORM DISPLAY"); gui2->addWaveform("WAVEFORM", buffer, 256, 0.0, 1.0); gui2->addLabel("SPECTRUM DISPLAY"); gui2->addSpectrum("SPECTRUM", buffer, 256, 0.0, 1.0); vector<float> buffer; for(int i = 0; i < 256; i++) { buffer.push_back(0.0); } gui2->addLabel("MOVING GRAPH", OFX_UI_FONT_MEDIUM); mg = gui2->addMovingGraph("MOVING", buffer, 256, 0.0, 1.0); gui2->addSpacer(); gui2->addLabel("IMAGE DISPLAY"); gui2->addImage("IMAGE CAPTION", img); gui2->addSpacer(); gui2->addLabel("FPS LABEL"); gui2->addFPS(); gui2->setWidgetFontSize(OFX_UI_FONT_SMALL); gui2->addSpacer(); gui2->addLabel("NUMBER DIALER"); gui2->addNumberDialer("DIALER", -10000, 10000, 5000, 3); gui2->addSpacer(); gui2->addLabel("LABEL BUTTON", OFX_UI_FONT_MEDIUM); gui2->addLabelButton("LABEL BTN", false); gui2->addSpacer(); gui2->addLabel("LABEL TOGGLES", OFX_UI_FONT_MEDIUM); gui2->addLabelToggle("LABEL TGL", false)->getLabelWidget()->setColorFill(ofColor(255, 0, 0)); gui2->setPosition(212, 0); gui2->autoSizeToFitWidgets(); ofAddListener(gui2->newGUIEvent,this,&ofApp::guiEvent); } void ofApp::setGUI3() { gui3 = new ofxUISuperCanvas("PANEL 3: ADVANCED"); gui3->addSpacer(); gui3->setGlobalButtonDimension(24); gui3->addLabel("MATRIX", OFX_UI_FONT_MEDIUM); gui3->addToggleMatrix("MATRIX1", 3, 3); tm = gui3->addToggleMatrix("MATRIX2", 3, 6); gui3->addToggleMatrix("MATRIX3", 1, 4); gui3->addSpacer(); gui3->setGlobalButtonDimension(64); gui3->addImageButton("IMAGEBTN", "GUI/images/App.png", false); gui3->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT); gui3->addImageToggle("IMAGETGL", "GUI/images/Preview.png", false); gui3->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN); gui3->addSpacer(); env = new ofxUIEnvelope(); for(float i = 0; i <= 5; i++) { env->addPoint(i/5.0, i/5.0); } gui3->addWidgetDown(new ofxUIEnvelopeEditor("ENV", env, 200, 128)); vector<string> items; items.push_back("FIRST ITEM"); items.push_back("SECOND ITEM"); items.push_back("THIRD ITEM"); items.push_back("FOURTH ITEM"); items.push_back("FIFTH ITEM"); items.push_back("SIXTH ITEM"); gui3->addSpacer(); gui3->setWidgetFontSize(OFX_UI_FONT_SMALL); gui3->addSortableList("SORTABLE LIST", items); gui3->addSpacer(); gui3->setWidgetFontSize(OFX_UI_FONT_MEDIUM); ddl = gui3->addDropDownList("DROP DOWN LIST", items); ddl->setAllowMultiple(true); gui3->setGlobalButtonDimension(OFX_UI_GLOBAL_BUTTON_DIMENSION); gui3->setPosition(212*2, 0); gui3->autoSizeToFitWidgets(); ofAddListener(gui3->newGUIEvent,this,&ofApp::guiEvent); } void ofApp::setGUI4() { gui4 = new ofxUISuperCanvas("PANEL 4: ADVANCED"); gui4->addSpacer(); gui4->addLabel("BILABEL SLIDER"); gui4->addBiLabelSlider("BILABEL", "HOT", "COLD", 0, 100, 50); gui4->addLabel("MINIMAL SLIDER"); gui4->addMinimalSlider("MINIMAL", 0, 100, 50.0)->getLabelWidget()->setColorFill(ofColor(255, 255, 0)); gui4->addSpacer(); gui4->addLabel("FPS SLIDER", OFX_UI_FONT_MEDIUM); gui4->addFPSSlider("FPS SLIDER"); gui4->addSpacer(); gui4->addLabel("IMAGE SAMPLER", OFX_UI_FONT_MEDIUM); gui4->addImageSampler("SAMPLER", img); gui4->setGlobalButtonDimension(64); gui4->addMultiImageButton("IMAGE BUTTON", "GUI/toggle.png", false); gui4->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT); gui4->addMultiImageToggle("IMAGE TOGGLE", "GUI/toggle.png", false); gui4->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN); gui4->addBaseDraws("BASE DRAW", img, true); gui4->addSpacer(); gui4->setGlobalButtonDimension(32); gui4->addButton("BTN", false)->setLabelVisible(false); gui4->addToggle("TGL", false)->setLabelVisible(false); gui4->setPosition(212*3,0); gui4->autoSizeToFitWidgets(); ofAddListener(gui4->newGUIEvent,this,&ofApp::guiEvent); } void ofApp::setGUI5() { gui5 = new ofxUISuperCanvas("PANEL 5: ADVANCED"); gui5->addSpacer(); gui5->addLabel("2D PAD"); gui5->add2DPad("PAD", ofPoint(-100, 100), ofPoint(-100,100), ofPoint(0,0)); gui5->addSpacer(); gui5->addLabel("ROTARY SLIDER", OFX_UI_FONT_MEDIUM); gui5->addRotarySlider("R2SLIDER", 0, 100, 50); gui5->addSpacer(); gui5->addLabel("CIRCLE SLIDER", OFX_UI_FONT_MEDIUM); gui5->addCircleSlider("NORTH SOUTH", 0, 100, 50.0); gui5->setPosition(212*4,0); gui5->autoSizeToFitWidgets(); ofAddListener(gui5->newGUIEvent,this,&ofApp::guiEvent); } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
28.007339
171
0.558831
k4rm
b4408f5060b26eed1b6e0d09c85abd16a62a44ab
7,845
cpp
C++
ctl/source/modes/mirroring/ModeSetState.cpp
TomatoYoung/beegfs
edf287940175ecded493183209719d2d90d45374
[ "BSD-3-Clause" ]
null
null
null
ctl/source/modes/mirroring/ModeSetState.cpp
TomatoYoung/beegfs
edf287940175ecded493183209719d2d90d45374
[ "BSD-3-Clause" ]
null
null
null
ctl/source/modes/mirroring/ModeSetState.cpp
TomatoYoung/beegfs
edf287940175ecded493183209719d2d90d45374
[ "BSD-3-Clause" ]
null
null
null
#include "ModeSetState.h" #include <common/net/message/nodes/SetTargetConsistencyStatesMsg.h> #include <common/net/message/nodes/SetTargetConsistencyStatesRespMsg.h> #include <common/toolkit/MessagingTk.h> #include <common/toolkit/UiTk.h> #include <program/Program.h> #define MODESETSTATE_ARG_TARGETID "--targetid" #define MODESETSTATE_ARG_NODEID "--nodeid" #define MODESETSTATE_ARG_STATE "--state" #define MODESETSTATE_ARG_STATE_GOOD "good" #define MODESETSTATE_ARG_STATE_BAD "bad" #define MODESETSTATE_ARG_FORCE "--force" int ModeSetState::execute() { App* app = Program::getApp(); StringMap* cfg = app->getConfig()->getUnknownConfigArgs(); uint16_t cfgTargetID = 0; TargetConsistencyState cfgState; if (!ModeHelper::checkRootPrivileges()) return APPCODE_RUNTIME_ERROR; nodeType = ModeHelper::nodeTypeFromCfg(cfg); if (this->nodeType != NODETYPE_Meta && this->nodeType != NODETYPE_Storage) { std::cerr << "Invalid or missing node type." << std::endl; return APPCODE_INVALID_CONFIG; } StringMapIter iter = cfg->find(MODESETSTATE_ARG_TARGETID); if(iter != cfg->end() ) { if (nodeType == NODETYPE_Meta) { std::cerr << "TargetIDs are only supported when setting state of storage targets. " "For metadata servers, plase use the --nodeID parameter." << std::endl; return APPCODE_INVALID_CONFIG; } bool isNumericRes = StringTk::isNumeric(iter->second); if(!isNumericRes) { std::cerr << "Invalid targetID given (must be numeric): " << iter->second << std::endl; return APPCODE_INVALID_CONFIG; } cfgTargetID = StringTk::strToUInt(iter->second); cfg->erase(iter); } iter = cfg->find(MODESETSTATE_ARG_NODEID); if (iter != cfg->end()) { if (nodeType == NODETYPE_Storage) { std::cerr << "NodeIDs are only supported when setting state of metadata nodes. " "For storage targets, please use the --targetID parameter." << std::endl; return APPCODE_INVALID_CONFIG; } bool isNumericRes = StringTk::isNumeric(iter->second); if (!isNumericRes) { std::cerr << "Invalid nodeID given (must be numeric): " << iter->second << std::endl; return APPCODE_INVALID_CONFIG; } cfgTargetID = StringTk::strToUInt(iter->second); cfg->erase(iter); } iter = cfg->find(MODESETSTATE_ARG_STATE); if (iter != cfg->end()) { if (iter->second == MODESETSTATE_ARG_STATE_GOOD) { cfg->erase(iter); // erase the "--state" iter = cfg->find(MODESETSTATE_ARG_FORCE); if (iter == cfg->end()) { std::cerr << "If state should be set to \"good\", --force must be given." << std::endl; return APPCODE_INVALID_CONFIG; } cfg->erase(iter); // erase the "--force" cfgState = TargetConsistencyState_GOOD; } else if (iter->second == MODESETSTATE_ARG_STATE_BAD) { cfgState = TargetConsistencyState_BAD; cfg->erase(iter); // erase the "--state" } else { std::cerr << "Invalid state given (must be \"good\" or \"bad\"): " << iter->second << std::endl; return APPCODE_INVALID_CONFIG; } } else { std::cerr << "State must be specified." << std::endl; return APPCODE_INVALID_CONFIG; } if (ModeHelper::checkInvalidArgs(cfg)) return APPCODE_INVALID_CONFIG; if (!uitk::userYNQuestion("WARNING!\n\nThis command is very dangerous and can cause serious data " "loss.\n" "It should not be used under normal circumstances. It is absolutely recommended to contact " "support before proceeding.")) return APPCODE_INVALID_CONFIG; return doSet(cfgTargetID, cfgState); } void ModeSetState::printHelp() { std::cout << "MODE ARGUMENTS:" << std::endl; std::cout << " Mandatory:" << std::endl; std::cout << " --nodetype=<nodetype> The node type (metadata, storage)." << std::endl; std::cout << " --targetid=<targetID> The ID of the target whose state should be" << std::endl; std::cout << " set." << std::endl; std::cout << " (only for nodetype=storage)" << std::endl; std::cout << " --nodeid=<nodeID> The ID of the node whose state should be set." << std::endl; std::cout << " (only for nodetype=metadata)" << std::endl; std::cout << " --state=<state> The state to be set (\"good\" or \"bad\")." << std::endl; std::cout << std::endl; std::cout << "USAGE:" << std::endl; std::cout << " This mode can be used to forcefully set the state of a target or node. This is" << std::endl; std::cout << " useful to manually set a target or node to the state \"bad\", or to resolve a" << std::endl; std::cout << " situation in which both buddies in a buddy mirror group are in the state" << std::endl; std::cout << " \"needs-resync\"." << std::endl; std::cout << std::endl; std::cout << " Example: Set a metadata node to \"bad\"" << std::endl; std::cout << " $ beegfs-ctl --setstate --nodetype=metadata --nodeid=10 --state=bad" << std::endl; } int ModeSetState::doSet(uint16_t targetID, TargetConsistencyState state) { App* app = Program::getApp(); // Send message to mgmtd auto nodes = app->getMgmtNodes(); NodeHandle node = nodes->referenceFirstNode(); UInt16List targetIDs(1, targetID); UInt8List states(1, (uint8_t)state); SetTargetConsistencyStatesMsg msg(nodeType, &targetIDs, &states, false); { const auto respMsgRaw = MessagingTk::requestResponse(*node, msg, NETMSGTYPE_SetTargetConsistencyStatesResp); if (!respMsgRaw) { std::cerr << "Communication with node not successful." << std::endl; return APPCODE_RUNTIME_ERROR; } SetTargetConsistencyStatesRespMsg* respMsgCast = reinterpret_cast<SetTargetConsistencyStatesRespMsg*>(respMsgRaw.get()); if (respMsgCast->getResult() != FhgfsOpsErr_SUCCESS) { std::cerr << "Management host did not accept state change. Error: " << respMsgCast->getResult() << std::endl; return APPCODE_RUNTIME_ERROR; } } // Send message to node if (nodeType == NODETYPE_Storage) { TargetMapper* targetMapper = app->getTargetMapper(); FhgfsOpsErr err; nodes = app->getStorageNodes(); node = nodes->referenceNodeByTargetID(targetID, targetMapper, &err); if (!node) { std::cerr << "Unable to resolve node for target ID " << targetID << ". Error: " << err << std::endl; return APPCODE_RUNTIME_ERROR; } } else { nodes = app->getMetaNodes(); node = nodes->referenceNode(NumNodeID(targetID)); if (!node) { std::cerr << "Unable to resolve node for node ID " << targetID << std::endl; return APPCODE_RUNTIME_ERROR; } } { const auto respMsgRaw = MessagingTk::requestResponse(*node, msg, NETMSGTYPE_SetTargetConsistencyStatesResp); if (!respMsgRaw) { std::cerr << "Communication with node not successful." << std::endl; return APPCODE_RUNTIME_ERROR; } auto respMsgCast = reinterpret_cast<SetTargetConsistencyStatesRespMsg*>(respMsgRaw.get()); if (respMsgCast->getResult() != FhgfsOpsErr_SUCCESS) { std::cerr << "Node did not accept state change. Error: " << respMsgCast->getResult() << std::endl; return APPCODE_RUNTIME_ERROR; } } std::cout << "Successfully set state." << std::endl; return APPCODE_NO_ERROR; }
33.814655
111
0.613384
TomatoYoung
b440d9e6869db0f5da40e6e96e05d7dc26765b8b
629
cpp
C++
acmicpc.net/source/2303.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
7
2019-06-26T07:03:32.000Z
2020-11-21T16:12:51.000Z
acmicpc.net/source/2303.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
null
null
null
acmicpc.net/source/2303.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
9
2019-02-28T03:34:54.000Z
2020-12-18T03:02:40.000Z
// 2303. 숫자 게임 // 2019.10.27 // 구현 #include<iostream> #include<vector> using namespace std; int maxVal; int idx; int check(vector<int>& v) { int val = 0; for (int i = 0; i < 3; i++) { for (int j = i + 1; j < 4; j++) { for (int k = j + 1; k < 5; k++) { int sum = (v[i] + v[j] + v[k]) % 10; val = val > sum ? val : sum; } } } return val; } int main() { int n; cin >> n; for (int i = 0; i < n; i++) { vector<int> v(5); for (int i = 0; i < 5; i++) { cin >> v[i]; } int val = check(v); if (maxVal <= val) { maxVal = val; idx = i + 1; } } cout << idx << endl; return 0; }
12.836735
40
0.45151
tdm1223
b4430917bc5a21408a8e649f6fa76d2e8354ea28
39
cpp
C++
src/task_base_pro/task_group.cpp
maxcong001/task_base_pro
2f309ea790c615389ecce3882cea7cca4aab93e3
[ "MIT" ]
1
2018-03-06T08:37:46.000Z
2018-03-06T08:37:46.000Z
src/task_base_pro/task_group.cpp
maxcong001/task_base_pro
2f309ea790c615389ecce3882cea7cca4aab93e3
[ "MIT" ]
null
null
null
src/task_base_pro/task_group.cpp
maxcong001/task_base_pro
2f309ea790c615389ecce3882cea7cca4aab93e3
[ "MIT" ]
null
null
null
#include "task_base_pro/task_group.hpp"
39
39
0.846154
maxcong001
b443842353cdf7cd048e046f6d894f8de79b98ac
1,446
cpp
C++
escher/src/stack_view.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
1,442
2017-08-28T19:39:45.000Z
2022-03-30T00:56:14.000Z
escher/src/stack_view.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
1,321
2017-08-28T23:03:10.000Z
2022-03-31T19:32:17.000Z
escher/src/stack_view.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
421
2017-08-28T22:02:39.000Z
2022-03-28T20:52:21.000Z
#include <escher/stack_view.h> #include <escher/metric.h> extern "C" { #include <assert.h> } namespace Escher { StackView::StackView() : View(), m_controller(nullptr) { } void StackView::setTextColor(KDColor textColor) { m_textColor = textColor; markRectAsDirty(bounds()); } void StackView::setBackgroundColor(KDColor backgroundColor) { m_backgroundColor = backgroundColor; markRectAsDirty(bounds()); } void StackView::setSeparatorColor(KDColor separatorColor) { m_separatorColor = separatorColor; markRectAsDirty(bounds()); } void StackView::setNamedController(ViewController * controller) { m_controller = controller; markRectAsDirty(bounds()); } void StackView::drawRect(KDContext * ctx, KDRect rect) const { KDRect b = bounds(); drawBorderOfRect(ctx, b, m_separatorColor); drawInnerRect(ctx, b, m_backgroundColor); // Write title const KDFont * font = KDFont::SmallFont; // Add horizontal margins KDPoint point = KDPoint(Metric::CellLeftMargin, 0); KDSize size = KDSize(m_frame.width() - Metric::CellLeftMargin - Metric::CellRightMargin, m_frame.height()); ctx->alignAndDrawString(m_controller->title(), point, size, 0.5f, 0.5f, font, m_textColor, m_backgroundColor); } #if ESCHER_VIEW_LOGGING const char * StackView::className() const { return "StackView"; } void StackView::logAttributes(std::ostream &os) const { View::logAttributes(os); os << " name=\"" << m_name << "\""; } #endif }
24.508475
112
0.728907
VersiraSec
b444253c17b560fbd15ac4a5f17eaaf13fb41b28
9,030
cpp
C++
src/prod/src/Reliability/LoadBalancing/Metric.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/Reliability/LoadBalancing/Metric.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/Reliability/LoadBalancing/Metric.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" #include "Metric.h" using namespace std; using namespace Common; using namespace Reliability::LoadBalancingComponent; Metric::Metric( wstring && name, double weight, double balancingThreshold, DynamicBitSet && blockList, uint activityThreshold, int64 clusterTotalCapacity, int64 clusterBufferedCapacity, int64 clusterLoad, bool isDefrag, int32 defragEmptyNodeCount, size_t defragEmptyNodeLoadThreshold, int64 reservationLoad, DefragDistributionType defragEmptyNodesDistribution, double placementHeuristicIncomingLoadFactor, double placementHeuristicEmptySpacePercent, bool defragmentationScopedAlgorithmEnabled, PlacementStrategy placementStrategy, double defragmentationEmptyNodeWeight, double defragmentationNonEmptyNodeWeight, bool balancingByPercentage) : name_(move(name)), weight_(weight), balancingThreshold_(balancingThreshold), blockList_(move(blockList)), isBalanced_(false), activityThreshold_(activityThreshold), clusterTotalCapacity_(clusterTotalCapacity), clusterBufferedCapacity_(clusterBufferedCapacity), clusterLoad_(clusterLoad), isDefrag_(isDefrag), defragEmptyNodeCount_(defragEmptyNodeCount), defragEmptyNodeLoadThreshold_(defragEmptyNodeLoadThreshold), reservationLoad_(reservationLoad), defragEmptyNodesDistribution_(defragEmptyNodesDistribution), placementHeuristicIncomingLoadFactor_(placementHeuristicIncomingLoadFactor), placementHeuristicEmptySpacePercent_(placementHeuristicEmptySpacePercent), defragmentationScopedAlgorithmEnabled_(defragmentationScopedAlgorithmEnabled), placementStrategy_(placementStrategy), defragmentationEmptyNodeWeight_(defragmentationEmptyNodeWeight), defragmentationNonEmptyNodeWeight_(defragmentationNonEmptyNodeWeight), balancingByPercentage_(balancingByPercentage) { // 1.0 means do balancing for any diff, 0.0 means infinity, e.g. never trigger balancing ASSERT_IFNOT(balancingThreshold >= 1.0 || balancingThreshold == 0.0, "balancingThreshold should >= 1 or == 0, current value is {0}", balancingThreshold); } Metric::Metric(Metric const & other) : name_(other.name_), weight_(other.weight_), balancingThreshold_(other.balancingThreshold_), blockList_(other.blockList_), isBalanced_(other.isBalanced_), activityThreshold_(other.activityThreshold_), clusterTotalCapacity_(other.clusterTotalCapacity_), clusterBufferedCapacity_(other.clusterBufferedCapacity_), clusterLoad_(other.clusterLoad_), isDefrag_(other.isDefrag_), defragEmptyNodeCount_(other.defragEmptyNodeCount_), defragEmptyNodeLoadThreshold_(other.defragEmptyNodeLoadThreshold_), reservationLoad_(other.reservationLoad_), defragEmptyNodesDistribution_(other.defragEmptyNodesDistribution_), placementHeuristicIncomingLoadFactor_(other.placementHeuristicIncomingLoadFactor_), placementHeuristicEmptySpacePercent_(other.placementHeuristicEmptySpacePercent_), defragmentationScopedAlgorithmEnabled_(other.defragmentationScopedAlgorithmEnabled_), placementStrategy_(other.placementStrategy_), defragmentationEmptyNodeWeight_(other.defragmentationEmptyNodeWeight_), defragmentationNonEmptyNodeWeight_(other.defragmentationNonEmptyNodeWeight_), balancingByPercentage_(other.balancingByPercentage_), indexInGlobalDomain_(other.indexInGlobalDomain_), indexInLocalDomain_(other.indexInLocalDomain_), indexInTotalDomain_(other.indexInTotalDomain_) { } Metric::Metric(Metric && other) : name_(move(other.name_)), weight_(other.weight_), balancingThreshold_(other.balancingThreshold_), blockList_(move(other.blockList_)), isBalanced_(other.isBalanced_), activityThreshold_(other.activityThreshold_), clusterTotalCapacity_(other.clusterTotalCapacity_), clusterBufferedCapacity_(other.clusterBufferedCapacity_), clusterLoad_(other.clusterLoad_), isDefrag_(other.isDefrag_), defragEmptyNodeCount_(other.defragEmptyNodeCount_), defragEmptyNodeLoadThreshold_(other.defragEmptyNodeLoadThreshold_), reservationLoad_(other.reservationLoad_), defragEmptyNodesDistribution_(other.defragEmptyNodesDistribution_), placementHeuristicIncomingLoadFactor_(other.placementHeuristicIncomingLoadFactor_), placementHeuristicEmptySpacePercent_(other.placementHeuristicEmptySpacePercent_), defragmentationScopedAlgorithmEnabled_(other.defragmentationScopedAlgorithmEnabled_), placementStrategy_(other.placementStrategy_), defragmentationEmptyNodeWeight_(other.defragmentationEmptyNodeWeight_), defragmentationNonEmptyNodeWeight_(other.defragmentationNonEmptyNodeWeight_), balancingByPercentage_(other.balancingByPercentage_), indexInGlobalDomain_(other.indexInGlobalDomain_), indexInLocalDomain_(other.indexInLocalDomain_), indexInTotalDomain_(other.indexInTotalDomain_) { } Metric & Metric::operator = (Metric && other) { if (this != &other) { name_ = move(other.name_); weight_ = other.weight_; balancingThreshold_ = other.balancingThreshold_; blockList_ = move(other.blockList_); isBalanced_ = other.isBalanced_; activityThreshold_ = other.activityThreshold_; clusterTotalCapacity_ = other.clusterTotalCapacity_; clusterBufferedCapacity_ = other.clusterBufferedCapacity_; clusterLoad_ = other.clusterLoad_; isDefrag_ = other.isDefrag_; defragEmptyNodeCount_ = other.defragEmptyNodeCount_; defragEmptyNodeLoadThreshold_ = other.defragEmptyNodeLoadThreshold_; reservationLoad_ = other.reservationLoad_; defragEmptyNodesDistribution_ = other.defragEmptyNodesDistribution_; placementHeuristicIncomingLoadFactor_ = other.placementHeuristicIncomingLoadFactor_; placementHeuristicEmptySpacePercent_ = other.placementHeuristicEmptySpacePercent_; defragmentationScopedAlgorithmEnabled_ = other.defragmentationScopedAlgorithmEnabled_; placementStrategy_ = other.placementStrategy_; defragmentationEmptyNodeWeight_ = other.defragmentationEmptyNodeWeight_; defragmentationNonEmptyNodeWeight_ = other.defragmentationNonEmptyNodeWeight_; balancingByPercentage_ = other.balancingByPercentage_; indexInGlobalDomain_ = other.indexInGlobalDomain_; indexInLocalDomain_ = other.indexInLocalDomain_; indexInTotalDomain_ = other.indexInTotalDomain_; } return *this; } bool Metric::get_ShouldCalculateBeneficialNodesForPlacement() const { return isDefrag_ && ( placementHeuristicIncomingLoadFactor_ != 0 || placementHeuristicEmptySpacePercent_ != 0 || defragmentationScopedAlgorithmEnabled_ ); } void Metric::WriteTo(TextWriter& writer, FormatOptions const&) const { writer.Write("{0}/{1}/{2}/{3}/{4}/{5}/{6}/{7}/{8}/{9}", name_, weight_, balancingThreshold_, isBalanced_, blockList_, activityThreshold_, clusterTotalCapacity_, clusterBufferedCapacity_, clusterLoad_, balancingByPercentage_); if (isDefrag_) { writer.Write("/{0}/{1}/{2}/{3}/{4}/{5}/{6}/{7}/{8}/{9}/{10}", isDefrag_, defragEmptyNodeLoadThreshold_, reservationLoad_, defragEmptyNodeCount_, defragEmptyNodesDistribution_, placementHeuristicIncomingLoadFactor_, placementHeuristicEmptySpacePercent_, defragmentationScopedAlgorithmEnabled_, defragmentationEmptyNodeWeight_, placementStrategy_, defragmentationNonEmptyNodeWeight_); } } void Reliability::LoadBalancingComponent::WriteToTextWriter(Common::TextWriter & writer, Metric::DefragDistributionType const & val) { switch (val) { case Metric::DefragDistributionType::SpreadAcrossFDs_UDs: writer.Write("SpreadAcrossFDsAndUDs"); break; case Metric::DefragDistributionType::NumberOfEmptyNodes: writer.Write("NoDistribution"); break; } } void Reliability::LoadBalancingComponent::WriteToTextWriter(Common::TextWriter & writer, Metric::PlacementStrategy const & val) { switch (val) { case Metric::PlacementStrategy::Balancing: writer.Write("Balancing"); break; case Metric::PlacementStrategy::ReservationAndBalance: writer.Write("ReservationAndBalance"); break; case Metric::PlacementStrategy::Reservation: writer.Write("Reservation"); break; case Metric::PlacementStrategy::ReservationAndPack: writer.Write("ReservationAndPack"); break; case Metric::PlacementStrategy::Defragmentation: writer.Write("Defragmentation"); break; } }
42.796209
132
0.762348
vishnuk007
b445ca1b1c3a76d2c525278f73a7b90cb909f0e4
1,239
cpp
C++
C++/TICPP-2e-v1/C12/ByteTest.cpp
trammell/test
ccac5e1dac947032e64d813e53cb961417a58d05
[ "Artistic-2.0" ]
null
null
null
C++/TICPP-2e-v1/C12/ByteTest.cpp
trammell/test
ccac5e1dac947032e64d813e53cb961417a58d05
[ "Artistic-2.0" ]
null
null
null
C++/TICPP-2e-v1/C12/ByteTest.cpp
trammell/test
ccac5e1dac947032e64d813e53cb961417a58d05
[ "Artistic-2.0" ]
null
null
null
//: C12:ByteTest.cpp // From Thinking in C++, 2nd Edition // Available at http://www.BruceEckel.com // (c) Bruce Eckel 2000 // Copyright notice in Copyright.txt #include "Byte.h" #include <fstream> using namespace std; ofstream out("ByteTest.out"); void k(Byte& b1, Byte& b2) { b1 = b1 * b2 + b2 % b1; #define TRY2(OP) \ out << "b1 = "; b1.print(out); \ out << ", b2 = "; b2.print(out); \ out << "; b1 " #OP " b2 produces "; \ (b1 OP b2).print(out); \ out << endl; b1 = 9; b2 = 47; TRY2(+) TRY2(-) TRY2(*) TRY2(/) TRY2(%) TRY2(^) TRY2(&) TRY2(|) TRY2(<<) TRY2(>>) TRY2(+=) TRY2(-=) TRY2(*=) TRY2(/=) TRY2(%=) TRY2(^=) TRY2(&=) TRY2(|=) TRY2(>>=) TRY2(<<=) TRY2(=) // Assignment operator // Conditionals: #define TRYC2(OP) \ out << "b1 = "; b1.print(out); \ out << ", b2 = "; b2.print(out); \ out << "; b1 " #OP " b2 produces "; \ out << (b1 OP b2); \ out << endl; b1 = 9; b2 = 47; TRYC2(<) TRYC2(>) TRYC2(==) TRYC2(!=) TRYC2(<=) TRYC2(>=) TRYC2(&&) TRYC2(||) // Chained assignment: Byte b3 = 92; b1 = b2 = b3; } int main() { out << "member functions:" << endl; Byte b1(47), b2(9); k(b1, b2); } ///:~
24.294118
50
0.489104
trammell
b44632d846ffa4a399d02535ab412d6c2efb437e
2,141
hpp
C++
CaWE/ModelEditor/SceneView3D.hpp
dns/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
3
2020-04-11T13:00:31.000Z
2020-12-07T03:19:10.000Z
CaWE/ModelEditor/SceneView3D.hpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
null
null
null
CaWE/ModelEditor/SceneView3D.hpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
1
2020-04-11T13:00:04.000Z
2020-04-11T13:00:04.000Z
/* Cafu Engine, http://www.cafu.de/ Copyright (c) Carsten Fuchs and other contributors. This project is licensed under the terms of the MIT license. */ #ifndef CAFU_MODELEDITOR_SCENE_VIEW_3D_HPP_INCLUDED #define CAFU_MODELEDITOR_SCENE_VIEW_3D_HPP_INCLUDED #include "../Generic3DWindow.hpp" #include "Models/Model_cmdl.hpp" #include "Renderer3D.hpp" namespace MatSys { class RenderMaterialT; } namespace ModelEditor { class ChildFrameT; class SceneView3DT : public Generic3DWindowT { public: SceneView3DT(ChildFrameT* Parent); Vector3fT TraceCameraRay(const wxPoint& RefPtWin, AnimPoseT::TraceResultT& ModelTR) const; private: // Implement virtual methods of Generic3DViewT base class. virtual Vector3fT GetRefPtWorld(const wxPoint& RefPtWin) const; virtual void InfoCameraChanged(); virtual void InfoRightMouseClick(wxMouseEvent& ME); /// Renders the skeleton of the model with the given joints and matrices. void RenderSkeleton(const ArrayT<CafuModelT::JointT>& Joints, const ArrayT<MatrixT>& Matrices, bool IsSubModel) const; /// Renders a single pass of the scene. void RenderPass() const; ChildFrameT* m_Parent; Renderer3DT m_Renderer; ///< Performs the 3D rendering in our window. unsigned long m_TimeOfLastPaint; ///< The time at which the OnPaint() event handler was last called. ArrayT<bool> m_JointSelCache; ///< Stores for each joint whether it is currently selected, updated every frame. // Event handlers. void OnKeyDown (wxKeyEvent& KE); void OnMouseLeftDown(wxMouseEvent& ME); ///< We also handle "double-click" events in this method (use ME.ButtonDClick() for distinction). void OnMouseLeftUp (wxMouseEvent& ME); void OnMouseMove (wxMouseEvent& ME); void OnContextMenu (wxContextMenuEvent& CE); void OnPaint (wxPaintEvent& PE); void OnIdle (wxIdleEvent& IE); DECLARE_EVENT_TABLE() }; } #endif
33.453125
153
0.670715
dns
b4487f0047155b05a081c68c30c33843e90b062e
295,372
cpp
C++
tools/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
opencor/llvm-clang
416d1dd61a1a748e6f20a46e20d0394e252cdbaa
[ "Apache-2.0" ]
605
2019-10-18T01:15:54.000Z
2022-03-31T14:31:04.000Z
tools/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
opencor/llvm-clang
416d1dd61a1a748e6f20a46e20d0394e252cdbaa
[ "Apache-2.0" ]
3,180
2019-10-18T01:21:21.000Z
2022-03-31T23:25:41.000Z
tools/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
opencor/llvm-clang
416d1dd61a1a748e6f20a46e20d0394e252cdbaa
[ "Apache-2.0" ]
275
2019-10-18T05:27:22.000Z
2022-03-30T09:04:21.000Z
//===-- RewriteModernObjC.cpp - Playground for the code rewriter ----------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // Hacks and fun related to the code rewriter. // //===----------------------------------------------------------------------===// #include "clang/Rewrite/Frontend/ASTConsumers.h" #include "clang/AST/AST.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/Attr.h" #include "clang/AST/ParentMap.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Config/config.h" #include "clang/Lex/Lexer.h" #include "clang/Rewrite/Core/Rewriter.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" #include <memory> #if CLANG_ENABLE_OBJC_REWRITER using namespace clang; using llvm::utostr; namespace { class RewriteModernObjC : public ASTConsumer { protected: enum { BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)), block, ... */ BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */ BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the __block variable */ BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy helpers */ BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose support routines */ BLOCK_BYREF_CURRENT_MAX = 256 }; enum { BLOCK_NEEDS_FREE = (1 << 24), BLOCK_HAS_COPY_DISPOSE = (1 << 25), BLOCK_HAS_CXX_OBJ = (1 << 26), BLOCK_IS_GC = (1 << 27), BLOCK_IS_GLOBAL = (1 << 28), BLOCK_HAS_DESCRIPTOR = (1 << 29) }; Rewriter Rewrite; DiagnosticsEngine &Diags; const LangOptions &LangOpts; ASTContext *Context; SourceManager *SM; TranslationUnitDecl *TUDecl; FileID MainFileID; const char *MainFileStart, *MainFileEnd; Stmt *CurrentBody; ParentMap *PropParentMap; // created lazily. std::string InFileName; std::unique_ptr<raw_ostream> OutFile; std::string Preamble; TypeDecl *ProtocolTypeDecl; VarDecl *GlobalVarDecl; Expr *GlobalConstructionExp; unsigned RewriteFailedDiag; unsigned GlobalBlockRewriteFailedDiag; // ObjC string constant support. unsigned NumObjCStringLiterals; VarDecl *ConstantStringClassReference; RecordDecl *NSStringRecord; // ObjC foreach break/continue generation support. int BcLabelCount; unsigned TryFinallyContainsReturnDiag; // Needed for super. ObjCMethodDecl *CurMethodDef; RecordDecl *SuperStructDecl; RecordDecl *ConstantStringDecl; FunctionDecl *MsgSendFunctionDecl; FunctionDecl *MsgSendSuperFunctionDecl; FunctionDecl *MsgSendStretFunctionDecl; FunctionDecl *MsgSendSuperStretFunctionDecl; FunctionDecl *MsgSendFpretFunctionDecl; FunctionDecl *GetClassFunctionDecl; FunctionDecl *GetMetaClassFunctionDecl; FunctionDecl *GetSuperClassFunctionDecl; FunctionDecl *SelGetUidFunctionDecl; FunctionDecl *CFStringFunctionDecl; FunctionDecl *SuperConstructorFunctionDecl; FunctionDecl *CurFunctionDef; /* Misc. containers needed for meta-data rewrite. */ SmallVector<ObjCImplementationDecl *, 8> ClassImplementation; SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation; llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs; llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols; llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces; llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags; SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen; /// DefinedNonLazyClasses - List of defined "non-lazy" classes. SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses; /// DefinedNonLazyCategories - List of defined "non-lazy" categories. SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories; SmallVector<Stmt *, 32> Stmts; SmallVector<int, 8> ObjCBcLabelNo; // Remember all the @protocol(<expr>) expressions. llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls; llvm::DenseSet<uint64_t> CopyDestroyCache; // Block expressions. SmallVector<BlockExpr *, 32> Blocks; SmallVector<int, 32> InnerDeclRefsCount; SmallVector<DeclRefExpr *, 32> InnerDeclRefs; SmallVector<DeclRefExpr *, 32> BlockDeclRefs; // Block related declarations. SmallVector<ValueDecl *, 8> BlockByCopyDecls; llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet; SmallVector<ValueDecl *, 8> BlockByRefDecls; llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet; llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo; llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls; llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls; llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs; llvm::DenseMap<ObjCInterfaceDecl *, llvm::SmallSetVector<ObjCIvarDecl *, 8> > ReferencedIvars; // ivar bitfield grouping containers llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups; llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber; // This container maps an <class, group number for ivar> tuple to the type // of the struct where the bitfield belongs. llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType; SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen; // This maps an original source AST to it's rewritten form. This allows // us to avoid rewriting the same node twice (which is very uncommon). // This is needed to support some of the exotic property rewriting. llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes; // Needed for header files being rewritten bool IsHeader; bool SilenceRewriteMacroWarning; bool GenerateLineInfo; bool objc_impl_method; bool DisableReplaceStmt; class DisableReplaceStmtScope { RewriteModernObjC &R; bool SavedValue; public: DisableReplaceStmtScope(RewriteModernObjC &R) : R(R), SavedValue(R.DisableReplaceStmt) { R.DisableReplaceStmt = true; } ~DisableReplaceStmtScope() { R.DisableReplaceStmt = SavedValue; } }; void InitializeCommon(ASTContext &context); public: llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames; // Top Level Driver code. bool HandleTopLevelDecl(DeclGroupRef D) override { for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) { if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) { if (!Class->isThisDeclarationADefinition()) { RewriteForwardClassDecl(D); break; } else { // Keep track of all interface declarations seen. ObjCInterfacesSeen.push_back(Class); break; } } if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) { if (!Proto->isThisDeclarationADefinition()) { RewriteForwardProtocolDecl(D); break; } } if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) { // Under modern abi, we cannot translate body of the function // yet until all class extensions and its implementation is seen. // This is because they may introduce new bitfields which must go // into their grouping struct. if (FDecl->isThisDeclarationADefinition() && // Not c functions defined inside an objc container. !FDecl->isTopLevelDeclInObjCContainer()) { FunctionDefinitionsSeen.push_back(FDecl); break; } } HandleTopLevelSingleDecl(*I); } return true; } void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override { for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) { if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) { if (isTopLevelBlockPointerType(TD->getUnderlyingType())) RewriteBlockPointerDecl(TD); else if (TD->getUnderlyingType()->isFunctionPointerType()) CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); else RewriteObjCQualifiedInterfaceTypes(TD); } } } void HandleTopLevelSingleDecl(Decl *D); void HandleDeclInMainFile(Decl *D); RewriteModernObjC(std::string inFile, std::unique_ptr<raw_ostream> OS, DiagnosticsEngine &D, const LangOptions &LOpts, bool silenceMacroWarn, bool LineInfo); ~RewriteModernObjC() override {} void HandleTranslationUnit(ASTContext &C) override; void ReplaceStmt(Stmt *Old, Stmt *New) { ReplaceStmtWithRange(Old, New, Old->getSourceRange()); } void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) { assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's"); Stmt *ReplacingStmt = ReplacedNodes[Old]; if (ReplacingStmt) return; // We can't rewrite the same node twice. if (DisableReplaceStmt) return; // Measure the old text. int Size = Rewrite.getRangeSize(SrcRange); if (Size == -1) { Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag) << Old->getSourceRange(); return; } // Get the new text. std::string SStr; llvm::raw_string_ostream S(SStr); New->printPretty(S, nullptr, PrintingPolicy(LangOpts)); const std::string &Str = S.str(); // If replacement succeeded or warning disabled return with no warning. if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) { ReplacedNodes[Old] = New; return; } if (SilenceRewriteMacroWarning) return; Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag) << Old->getSourceRange(); } void InsertText(SourceLocation Loc, StringRef Str, bool InsertAfter = true) { // If insertion succeeded or warning disabled return with no warning. if (!Rewrite.InsertText(Loc, Str, InsertAfter) || SilenceRewriteMacroWarning) return; Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag); } void ReplaceText(SourceLocation Start, unsigned OrigLength, StringRef Str) { // If removal succeeded or warning disabled return with no warning. if (!Rewrite.ReplaceText(Start, OrigLength, Str) || SilenceRewriteMacroWarning) return; Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag); } // Syntactic Rewriting. void RewriteRecordBody(RecordDecl *RD); void RewriteInclude(); void RewriteLineDirective(const Decl *D); void ConvertSourceLocationToLineDirective(SourceLocation Loc, std::string &LineString); void RewriteForwardClassDecl(DeclGroupRef D); void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG); void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, const std::string &typedefString); void RewriteImplementations(); void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, ObjCImplementationDecl *IMD, ObjCCategoryImplDecl *CID); void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl); void RewriteImplementationDecl(Decl *Dcl); void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl, ObjCMethodDecl *MDecl, std::string &ResultStr); void RewriteTypeIntoString(QualType T, std::string &ResultStr, const FunctionType *&FPRetType); void RewriteByRefString(std::string &ResultStr, const std::string &Name, ValueDecl *VD, bool def=false); void RewriteCategoryDecl(ObjCCategoryDecl *Dcl); void RewriteProtocolDecl(ObjCProtocolDecl *Dcl); void RewriteForwardProtocolDecl(DeclGroupRef D); void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG); void RewriteMethodDeclaration(ObjCMethodDecl *Method); void RewriteProperty(ObjCPropertyDecl *prop); void RewriteFunctionDecl(FunctionDecl *FD); void RewriteBlockPointerType(std::string& Str, QualType Type); void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD); void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD); void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl); void RewriteTypeOfDecl(VarDecl *VD); void RewriteObjCQualifiedInterfaceTypes(Expr *E); std::string getIvarAccessString(ObjCIvarDecl *D); // Expression Rewriting. Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S); Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp); Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo); Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo); Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp); Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp); Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp); Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp); Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp); Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp); Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp); Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp); Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S); Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S); Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S); Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S); Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, SourceLocation OrigEnd); Stmt *RewriteBreakStmt(BreakStmt *S); Stmt *RewriteContinueStmt(ContinueStmt *S); void RewriteCastExpr(CStyleCastExpr *CE); void RewriteImplicitCastObjCExpr(CastExpr *IE); // Computes ivar bitfield group no. unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV); // Names field decl. for ivar bitfield group. void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result); // Names struct type for ivar bitfield group. void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result); // Names symbol for ivar bitfield group field offset. void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result); // Given an ivar bitfield, it builds (or finds) its group record type. QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV); QualType SynthesizeBitfieldGroupStructType( ObjCIvarDecl *IV, SmallVectorImpl<ObjCIvarDecl *> &IVars); // Block rewriting. void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D); // Block specific rewrite rules. void RewriteBlockPointerDecl(NamedDecl *VD); void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl); Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD); Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE); void RewriteBlockPointerFunctionArgs(FunctionDecl *FD); void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, std::string &Result); void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result); bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag, bool &IsNamedDefinition); void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, std::string &Result); bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result); void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl, std::string &Result); void Initialize(ASTContext &context) override; // Misc. AST transformation routines. Sometimes they end up calling // rewriting routines on the new ASTs. CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD, ArrayRef<Expr *> Args, SourceLocation StartLoc=SourceLocation(), SourceLocation EndLoc=SourceLocation()); Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor, QualType returnType, SmallVectorImpl<QualType> &ArgTypes, SmallVectorImpl<Expr*> &MsgExprs, ObjCMethodDecl *Method); Stmt *SynthMessageExpr(ObjCMessageExpr *Exp, SourceLocation StartLoc=SourceLocation(), SourceLocation EndLoc=SourceLocation()); void SynthCountByEnumWithState(std::string &buf); void SynthMsgSendFunctionDecl(); void SynthMsgSendSuperFunctionDecl(); void SynthMsgSendStretFunctionDecl(); void SynthMsgSendFpretFunctionDecl(); void SynthMsgSendSuperStretFunctionDecl(); void SynthGetClassFunctionDecl(); void SynthGetMetaClassFunctionDecl(); void SynthGetSuperClassFunctionDecl(); void SynthSelGetUidFunctionDecl(); void SynthSuperConstructorFunctionDecl(); // Rewriting metadata template<typename MethodIterator> void RewriteObjCMethodsMetaData(MethodIterator MethodBegin, MethodIterator MethodEnd, bool IsInstanceMethod, StringRef prefix, StringRef ClassName, std::string &Result); void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol, std::string &Result); void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, std::string &Result); void RewriteClassSetupInitHook(std::string &Result); void RewriteMetaDataIntoBuffer(std::string &Result); void WriteImageInfo(std::string &Result); void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl, std::string &Result); void RewriteCategorySetupInitHook(std::string &Result); // Rewriting ivar void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar, std::string &Result); Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV); std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag); std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, StringRef funcName, std::string Tag); std::string SynthesizeBlockFunc(BlockExpr *CE, int i, StringRef funcName, std::string Tag); std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, std::string Desc); std::string SynthesizeBlockDescriptor(std::string DescTag, std::string ImplTag, int i, StringRef funcName, unsigned hasCopy); Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp); void SynthesizeBlockLiterals(SourceLocation FunLocStart, StringRef FunName); FunctionDecl *SynthBlockInitFunctionDecl(StringRef name); Stmt *SynthBlockInitExpr(BlockExpr *Exp, const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs); // Misc. helper routines. QualType getProtocolType(); void WarnAboutReturnGotoStmts(Stmt *S); void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND); void InsertBlockLiteralsWithinFunction(FunctionDecl *FD); void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD); bool IsDeclStmtInForeachHeader(DeclStmt *DS); void CollectBlockDeclRefInfo(BlockExpr *Exp); void GetBlockDeclRefExprs(Stmt *S); void GetInnerBlockDeclRefExprs(Stmt *S, SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs, llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts); // We avoid calling Type::isBlockPointerType(), since it operates on the // canonical type. We only care if the top-level type is a closure pointer. bool isTopLevelBlockPointerType(QualType T) { return isa<BlockPointerType>(T); } /// convertBlockPointerToFunctionPointer - Converts a block-pointer type /// to a function pointer type and upon success, returns true; false /// otherwise. bool convertBlockPointerToFunctionPointer(QualType &T) { if (isTopLevelBlockPointerType(T)) { const auto *BPT = T->castAs<BlockPointerType>(); T = Context->getPointerType(BPT->getPointeeType()); return true; } return false; } bool convertObjCTypeToCStyleType(QualType &T); bool needToScanForQualifiers(QualType T); QualType getSuperStructType(); QualType getConstantStringStructType(); QualType convertFunctionTypeOfBlocks(const FunctionType *FT); void convertToUnqualifiedObjCType(QualType &T) { if (T->isObjCQualifiedIdType()) { bool isConst = T.isConstQualified(); T = isConst ? Context->getObjCIdType().withConst() : Context->getObjCIdType(); } else if (T->isObjCQualifiedClassType()) T = Context->getObjCClassType(); else if (T->isObjCObjectPointerType() && T->getPointeeType()->isObjCQualifiedInterfaceType()) { if (const ObjCObjectPointerType * OBJPT = T->getAsObjCInterfacePointerType()) { const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType(); T = QualType(IFaceT, 0); T = Context->getPointerType(T); } } } // FIXME: This predicate seems like it would be useful to add to ASTContext. bool isObjCType(QualType T) { if (!LangOpts.ObjC) return false; QualType OCT = Context->getCanonicalType(T).getUnqualifiedType(); if (OCT == Context->getCanonicalType(Context->getObjCIdType()) || OCT == Context->getCanonicalType(Context->getObjCClassType())) return true; if (const PointerType *PT = OCT->getAs<PointerType>()) { if (isa<ObjCInterfaceType>(PT->getPointeeType()) || PT->getPointeeType()->isObjCQualifiedIdType()) return true; } return false; } bool PointerTypeTakesAnyBlockArguments(QualType QT); bool PointerTypeTakesAnyObjCQualifiedType(QualType QT); void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen); void QuoteDoublequotes(std::string &From, std::string &To) { for (unsigned i = 0; i < From.length(); i++) { if (From[i] == '"') To += "\\\""; else To += From[i]; } } QualType getSimpleFunctionType(QualType result, ArrayRef<QualType> args, bool variadic = false) { if (result == Context->getObjCInstanceType()) result = Context->getObjCIdType(); FunctionProtoType::ExtProtoInfo fpi; fpi.Variadic = variadic; return Context->getFunctionType(result, args, fpi); } // Helper function: create a CStyleCastExpr with trivial type source info. CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty, CastKind Kind, Expr *E) { TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation()); return CStyleCastExpr::Create(*Ctx, Ty, VK_PRValue, Kind, E, nullptr, FPOptionsOverride(), TInfo, SourceLocation(), SourceLocation()); } bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const { IdentifierInfo* II = &Context->Idents.get("load"); Selector LoadSel = Context->Selectors.getSelector(0, &II); return OD->getClassMethod(LoadSel) != nullptr; } StringLiteral *getStringLiteral(StringRef Str) { QualType StrType = Context->getConstantArrayType( Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr, ArrayType::Normal, 0); return StringLiteral::Create(*Context, Str, StringLiteral::Ascii, /*Pascal=*/false, StrType, SourceLocation()); } }; } // end anonymous namespace void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D) { if (const FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) { for (const auto &I : fproto->param_types()) if (isTopLevelBlockPointerType(I)) { // All the args are checked/rewritten. Don't call twice! RewriteBlockPointerDecl(D); break; } } } void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) { const PointerType *PT = funcType->getAs<PointerType>(); if (PT && PointerTypeTakesAnyBlockArguments(funcType)) RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND); } static bool IsHeaderFile(const std::string &Filename) { std::string::size_type DotPos = Filename.rfind('.'); if (DotPos == std::string::npos) { // no file extension return false; } std::string Ext = Filename.substr(DotPos + 1); // C header: .h // C++ header: .hh or .H; return Ext == "h" || Ext == "hh" || Ext == "H"; } RewriteModernObjC::RewriteModernObjC(std::string inFile, std::unique_ptr<raw_ostream> OS, DiagnosticsEngine &D, const LangOptions &LOpts, bool silenceMacroWarn, bool LineInfo) : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)), SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) { IsHeader = IsHeaderFile(inFile); RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning, "rewriting sub-expression within a macro (may not be correct)"); // FIXME. This should be an error. But if block is not called, it is OK. And it // may break including some headers. GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning, "rewriting block literal declared in global scope is not implemented"); TryFinallyContainsReturnDiag = Diags.getCustomDiagID( DiagnosticsEngine::Warning, "rewriter doesn't support user-specified control flow semantics " "for @try/@finally (code may not execute properly)"); } std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter( const std::string &InFile, std::unique_ptr<raw_ostream> OS, DiagnosticsEngine &Diags, const LangOptions &LOpts, bool SilenceRewriteMacroWarning, bool LineInfo) { return std::make_unique<RewriteModernObjC>(InFile, std::move(OS), Diags, LOpts, SilenceRewriteMacroWarning, LineInfo); } void RewriteModernObjC::InitializeCommon(ASTContext &context) { Context = &context; SM = &Context->getSourceManager(); TUDecl = Context->getTranslationUnitDecl(); MsgSendFunctionDecl = nullptr; MsgSendSuperFunctionDecl = nullptr; MsgSendStretFunctionDecl = nullptr; MsgSendSuperStretFunctionDecl = nullptr; MsgSendFpretFunctionDecl = nullptr; GetClassFunctionDecl = nullptr; GetMetaClassFunctionDecl = nullptr; GetSuperClassFunctionDecl = nullptr; SelGetUidFunctionDecl = nullptr; CFStringFunctionDecl = nullptr; ConstantStringClassReference = nullptr; NSStringRecord = nullptr; CurMethodDef = nullptr; CurFunctionDef = nullptr; GlobalVarDecl = nullptr; GlobalConstructionExp = nullptr; SuperStructDecl = nullptr; ProtocolTypeDecl = nullptr; ConstantStringDecl = nullptr; BcLabelCount = 0; SuperConstructorFunctionDecl = nullptr; NumObjCStringLiterals = 0; PropParentMap = nullptr; CurrentBody = nullptr; DisableReplaceStmt = false; objc_impl_method = false; // Get the ID and start/end of the main file. MainFileID = SM->getMainFileID(); llvm::MemoryBufferRef MainBuf = SM->getBufferOrFake(MainFileID); MainFileStart = MainBuf.getBufferStart(); MainFileEnd = MainBuf.getBufferEnd(); Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts()); } //===----------------------------------------------------------------------===// // Top Level Driver Code //===----------------------------------------------------------------------===// void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) { if (Diags.hasErrorOccurred()) return; // Two cases: either the decl could be in the main file, or it could be in a // #included file. If the former, rewrite it now. If the later, check to see // if we rewrote the #include/#import. SourceLocation Loc = D->getLocation(); Loc = SM->getExpansionLoc(Loc); // If this is for a builtin, ignore it. if (Loc.isInvalid()) return; // Look for built-in declarations that we need to refer during the rewrite. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { RewriteFunctionDecl(FD); } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) { // declared in <Foundation/NSString.h> if (FVD->getName() == "_NSConstantStringClassReference") { ConstantStringClassReference = FVD; return; } } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) { RewriteCategoryDecl(CD); } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) { if (PD->isThisDeclarationADefinition()) RewriteProtocolDecl(PD); } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) { // Recurse into linkage specifications for (DeclContext::decl_iterator DI = LSD->decls_begin(), DIEnd = LSD->decls_end(); DI != DIEnd; ) { if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) { if (!IFace->isThisDeclarationADefinition()) { SmallVector<Decl *, 8> DG; SourceLocation StartLoc = IFace->getBeginLoc(); do { if (isa<ObjCInterfaceDecl>(*DI) && !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() && StartLoc == (*DI)->getBeginLoc()) DG.push_back(*DI); else break; ++DI; } while (DI != DIEnd); RewriteForwardClassDecl(DG); continue; } else { // Keep track of all interface declarations seen. ObjCInterfacesSeen.push_back(IFace); ++DI; continue; } } if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) { if (!Proto->isThisDeclarationADefinition()) { SmallVector<Decl *, 8> DG; SourceLocation StartLoc = Proto->getBeginLoc(); do { if (isa<ObjCProtocolDecl>(*DI) && !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() && StartLoc == (*DI)->getBeginLoc()) DG.push_back(*DI); else break; ++DI; } while (DI != DIEnd); RewriteForwardProtocolDecl(DG); continue; } } HandleTopLevelSingleDecl(*DI); ++DI; } } // If we have a decl in the main file, see if we should rewrite it. if (SM->isWrittenInMainFile(Loc)) return HandleDeclInMainFile(D); } //===----------------------------------------------------------------------===// // Syntactic (non-AST) Rewriting Code //===----------------------------------------------------------------------===// void RewriteModernObjC::RewriteInclude() { SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID); StringRef MainBuf = SM->getBufferData(MainFileID); const char *MainBufStart = MainBuf.begin(); const char *MainBufEnd = MainBuf.end(); size_t ImportLen = strlen("import"); // Loop over the whole file, looking for includes. for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) { if (*BufPtr == '#') { if (++BufPtr == MainBufEnd) return; while (*BufPtr == ' ' || *BufPtr == '\t') if (++BufPtr == MainBufEnd) return; if (!strncmp(BufPtr, "import", ImportLen)) { // replace import with include SourceLocation ImportLoc = LocStart.getLocWithOffset(BufPtr-MainBufStart); ReplaceText(ImportLoc, ImportLen, "include"); BufPtr += ImportLen; } } } } static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl, ObjCIvarDecl *IvarDecl, std::string &Result) { Result += "OBJC_IVAR_$_"; Result += IDecl->getName(); Result += "$"; Result += IvarDecl->getName(); } std::string RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) { const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface(); // Build name of symbol holding ivar offset. std::string IvarOffsetName; if (D->isBitField()) ObjCIvarBitfieldGroupOffset(D, IvarOffsetName); else WriteInternalIvarName(ClassDecl, D, IvarOffsetName); std::string S = "(*("; QualType IvarT = D->getType(); if (D->isBitField()) IvarT = GetGroupRecordTypeForObjCIvarBitfield(D); if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) { RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl(); RD = RD->getDefinition(); if (RD && !RD->getDeclName().getAsIdentifierInfo()) { // decltype(((Foo_IMPL*)0)->bar) * auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext()); // ivar in class extensions requires special treatment. if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) CDecl = CatDecl->getClassInterface(); std::string RecName = std::string(CDecl->getName()); RecName += "_IMPL"; RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(RecName)); QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD)); unsigned UnsignedIntSize = static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); Expr *Zero = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, 0), Context->UnsignedIntTy, SourceLocation()); Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero); ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), Zero); FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get(D->getNameAsString()), IvarT, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); MemberExpr *ME = MemberExpr::CreateImplicit( *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary); IvarT = Context->getDecltypeType(ME, ME->getType()); } } convertObjCTypeToCStyleType(IvarT); QualType castT = Context->getPointerType(IvarT); std::string TypeString(castT.getAsString(Context->getPrintingPolicy())); S += TypeString; S += ")"; // ((char *)self + IVAR_OFFSET_SYMBOL_NAME) S += "((char *)self + "; S += IvarOffsetName; S += "))"; if (D->isBitField()) { S += "."; S += D->getNameAsString(); } ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D); return S; } /// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not /// been found in the class implementation. In this case, it must be synthesized. static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP, ObjCPropertyDecl *PD, bool getter) { auto *OMD = IMP->getInstanceMethod(getter ? PD->getGetterName() : PD->getSetterName()); return !OMD || OMD->isSynthesizedAccessorStub(); } void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, ObjCImplementationDecl *IMD, ObjCCategoryImplDecl *CID) { static bool objcGetPropertyDefined = false; static bool objcSetPropertyDefined = false; SourceLocation startGetterSetterLoc; if (PID->getBeginLoc().isValid()) { SourceLocation startLoc = PID->getBeginLoc(); InsertText(startLoc, "// "); const char *startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @synthesize location"); const char *semiBuf = strchr(startBuf, ';'); assert((*semiBuf == ';') && "@synthesize: can't find ';'"); startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1); } else startGetterSetterLoc = IMD ? IMD->getEndLoc() : CID->getEndLoc(); if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) return; // FIXME: is this correct? // Generate the 'getter' function. ObjCPropertyDecl *PD = PID->getPropertyDecl(); ObjCIvarDecl *OID = PID->getPropertyIvarDecl(); assert(IMD && OID && "Synthesized ivars must be attached to @implementation"); unsigned Attributes = PD->getPropertyAttributes(); if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) { bool GenGetProperty = !(Attributes & ObjCPropertyAttribute::kind_nonatomic) && (Attributes & (ObjCPropertyAttribute::kind_retain | ObjCPropertyAttribute::kind_copy)); std::string Getr; if (GenGetProperty && !objcGetPropertyDefined) { objcGetPropertyDefined = true; // FIXME. Is this attribute correct in all cases? Getr = "\nextern \"C\" __declspec(dllimport) " "id objc_getProperty(id, SEL, long, bool);\n"; } RewriteObjCMethodDecl(OID->getContainingInterface(), PID->getGetterMethodDecl(), Getr); Getr += "{ "; // Synthesize an explicit cast to gain access to the ivar. // See objc-act.c:objc_synthesize_new_getter() for details. if (GenGetProperty) { // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1) Getr += "typedef "; const FunctionType *FPRetType = nullptr; RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr, FPRetType); Getr += " _TYPE"; if (FPRetType) { Getr += ")"; // close the precedence "scope" for "*". // Now, emit the argument types (if any). if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){ Getr += "("; for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { if (i) Getr += ", "; std::string ParamStr = FT->getParamType(i).getAsString(Context->getPrintingPolicy()); Getr += ParamStr; } if (FT->isVariadic()) { if (FT->getNumParams()) Getr += ", "; Getr += "..."; } Getr += ")"; } else Getr += "()"; } Getr += ";\n"; Getr += "return (_TYPE)"; Getr += "objc_getProperty(self, _cmd, "; RewriteIvarOffsetComputation(OID, Getr); Getr += ", 1)"; } else Getr += "return " + getIvarAccessString(OID); Getr += "; }"; InsertText(startGetterSetterLoc, Getr); } if (PD->isReadOnly() || !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/)) return; // Generate the 'setter' function. std::string Setr; bool GenSetProperty = Attributes & (ObjCPropertyAttribute::kind_retain | ObjCPropertyAttribute::kind_copy); if (GenSetProperty && !objcSetPropertyDefined) { objcSetPropertyDefined = true; // FIXME. Is this attribute correct in all cases? Setr = "\nextern \"C\" __declspec(dllimport) " "void objc_setProperty (id, SEL, long, id, bool, bool);\n"; } RewriteObjCMethodDecl(OID->getContainingInterface(), PID->getSetterMethodDecl(), Setr); Setr += "{ "; // Synthesize an explicit cast to initialize the ivar. // See objc-act.c:objc_synthesize_new_setter() for details. if (GenSetProperty) { Setr += "objc_setProperty (self, _cmd, "; RewriteIvarOffsetComputation(OID, Setr); Setr += ", (id)"; Setr += PD->getName(); Setr += ", "; if (Attributes & ObjCPropertyAttribute::kind_nonatomic) Setr += "0, "; else Setr += "1, "; if (Attributes & ObjCPropertyAttribute::kind_copy) Setr += "1)"; else Setr += "0)"; } else { Setr += getIvarAccessString(OID) + " = "; Setr += PD->getName(); } Setr += "; }\n"; InsertText(startGetterSetterLoc, Setr); } static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl, std::string &typedefString) { typedefString += "\n#ifndef _REWRITER_typedef_"; typedefString += ForwardDecl->getNameAsString(); typedefString += "\n"; typedefString += "#define _REWRITER_typedef_"; typedefString += ForwardDecl->getNameAsString(); typedefString += "\n"; typedefString += "typedef struct objc_object "; typedefString += ForwardDecl->getNameAsString(); // typedef struct { } _objc_exc_Classname; typedefString += ";\ntypedef struct {} _objc_exc_"; typedefString += ForwardDecl->getNameAsString(); typedefString += ";\n#endif\n"; } void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, const std::string &typedefString) { SourceLocation startLoc = ClassDecl->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); const char *semiPtr = strchr(startBuf, ';'); // Replace the @class with typedefs corresponding to the classes. ReplaceText(startLoc, semiPtr-startBuf+1, typedefString); } void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) { std::string typedefString; for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) { if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) { if (I == D.begin()) { // Translate to typedef's that forward reference structs with the same name // as the class. As a convenience, we include the original declaration // as a comment. typedefString += "// @class "; typedefString += ForwardDecl->getNameAsString(); typedefString += ";"; } RewriteOneForwardClassDecl(ForwardDecl, typedefString); } else HandleTopLevelSingleDecl(*I); } DeclGroupRef::iterator I = D.begin(); RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString); } void RewriteModernObjC::RewriteForwardClassDecl( const SmallVectorImpl<Decl *> &D) { std::string typedefString; for (unsigned i = 0; i < D.size(); i++) { ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]); if (i == 0) { typedefString += "// @class "; typedefString += ForwardDecl->getNameAsString(); typedefString += ";"; } RewriteOneForwardClassDecl(ForwardDecl, typedefString); } RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString); } void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) { // When method is a synthesized one, such as a getter/setter there is // nothing to rewrite. if (Method->isImplicit()) return; SourceLocation LocStart = Method->getBeginLoc(); SourceLocation LocEnd = Method->getEndLoc(); if (SM->getExpansionLineNumber(LocEnd) > SM->getExpansionLineNumber(LocStart)) { InsertText(LocStart, "#if 0\n"); ReplaceText(LocEnd, 1, ";\n#endif\n"); } else { InsertText(LocStart, "// "); } } void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) { SourceLocation Loc = prop->getAtLoc(); ReplaceText(Loc, 0, "// "); // FIXME: handle properties that are declared across multiple lines. } void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { SourceLocation LocStart = CatDecl->getBeginLoc(); // FIXME: handle category headers that are declared across multiple lines. if (CatDecl->getIvarRBraceLoc().isValid()) { ReplaceText(LocStart, 1, "/** "); ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ "); } else { ReplaceText(LocStart, 0, "// "); } for (auto *I : CatDecl->instance_properties()) RewriteProperty(I); for (auto *I : CatDecl->instance_methods()) RewriteMethodDeclaration(I); for (auto *I : CatDecl->class_methods()) RewriteMethodDeclaration(I); // Lastly, comment out the @end. ReplaceText(CatDecl->getAtEndRange().getBegin(), strlen("@end"), "/* @end */\n"); } void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { SourceLocation LocStart = PDecl->getBeginLoc(); assert(PDecl->isThisDeclarationADefinition()); // FIXME: handle protocol headers that are declared across multiple lines. ReplaceText(LocStart, 0, "// "); for (auto *I : PDecl->instance_methods()) RewriteMethodDeclaration(I); for (auto *I : PDecl->class_methods()) RewriteMethodDeclaration(I); for (auto *I : PDecl->instance_properties()) RewriteProperty(I); // Lastly, comment out the @end. SourceLocation LocEnd = PDecl->getAtEndRange().getBegin(); ReplaceText(LocEnd, strlen("@end"), "/* @end */\n"); // Must comment out @optional/@required const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); for (const char *p = startBuf; p < endBuf; p++) { if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) { SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf); ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */"); } else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) { SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf); ReplaceText(OptionalLoc, strlen("@required"), "/* @required */"); } } } void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) { SourceLocation LocStart = (*D.begin())->getBeginLoc(); if (LocStart.isInvalid()) llvm_unreachable("Invalid SourceLocation"); // FIXME: handle forward protocol that are declared across multiple lines. ReplaceText(LocStart, 0, "// "); } void RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) { SourceLocation LocStart = DG[0]->getBeginLoc(); if (LocStart.isInvalid()) llvm_unreachable("Invalid SourceLocation"); // FIXME: handle forward protocol that are declared across multiple lines. ReplaceText(LocStart, 0, "// "); } void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr, const FunctionType *&FPRetType) { if (T->isObjCQualifiedIdType()) ResultStr += "id"; else if (T->isFunctionPointerType() || T->isBlockPointerType()) { // needs special handling, since pointer-to-functions have special // syntax (where a decaration models use). QualType retType = T; QualType PointeeTy; if (const PointerType* PT = retType->getAs<PointerType>()) PointeeTy = PT->getPointeeType(); else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>()) PointeeTy = BPT->getPointeeType(); if ((FPRetType = PointeeTy->getAs<FunctionType>())) { ResultStr += FPRetType->getReturnType().getAsString(Context->getPrintingPolicy()); ResultStr += "(*"; } } else ResultStr += T.getAsString(Context->getPrintingPolicy()); } void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl, ObjCMethodDecl *OMD, std::string &ResultStr) { //fprintf(stderr,"In RewriteObjCMethodDecl\n"); const FunctionType *FPRetType = nullptr; ResultStr += "\nstatic "; RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType); ResultStr += " "; // Unique method name std::string NameStr; if (OMD->isInstanceMethod()) NameStr += "_I_"; else NameStr += "_C_"; NameStr += IDecl->getNameAsString(); NameStr += "_"; if (ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) { NameStr += CID->getNameAsString(); NameStr += "_"; } // Append selector names, replacing ':' with '_' { std::string selString = OMD->getSelector().getAsString(); int len = selString.size(); for (int i = 0; i < len; i++) if (selString[i] == ':') selString[i] = '_'; NameStr += selString; } // Remember this name for metadata emission MethodInternalNames[OMD] = NameStr; ResultStr += NameStr; // Rewrite arguments ResultStr += "("; // invisible arguments if (OMD->isInstanceMethod()) { QualType selfTy = Context->getObjCInterfaceType(IDecl); selfTy = Context->getPointerType(selfTy); if (!LangOpts.MicrosoftExt) { if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl))) ResultStr += "struct "; } // When rewriting for Microsoft, explicitly omit the structure name. ResultStr += IDecl->getNameAsString(); ResultStr += " *"; } else ResultStr += Context->getObjCClassType().getAsString( Context->getPrintingPolicy()); ResultStr += " self, "; ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy()); ResultStr += " _cmd"; // Method arguments. for (const auto *PDecl : OMD->parameters()) { ResultStr += ", "; if (PDecl->getType()->isObjCQualifiedIdType()) { ResultStr += "id "; ResultStr += PDecl->getNameAsString(); } else { std::string Name = PDecl->getNameAsString(); QualType QT = PDecl->getType(); // Make sure we convert "t (^)(...)" to "t (*)(...)". (void)convertBlockPointerToFunctionPointer(QT); QT.getAsStringInternal(Name, Context->getPrintingPolicy()); ResultStr += Name; } } if (OMD->isVariadic()) ResultStr += ", ..."; ResultStr += ") "; if (FPRetType) { ResultStr += ")"; // close the precedence "scope" for "*". // Now, emit the argument types (if any). if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) { ResultStr += "("; for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { if (i) ResultStr += ", "; std::string ParamStr = FT->getParamType(i).getAsString(Context->getPrintingPolicy()); ResultStr += ParamStr; } if (FT->isVariadic()) { if (FT->getNumParams()) ResultStr += ", "; ResultStr += "..."; } ResultStr += ")"; } else { ResultStr += "()"; } } } void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) { ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID); ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID); assert((IMD || CID) && "Unknown implementation type"); if (IMD) { if (IMD->getIvarRBraceLoc().isValid()) { ReplaceText(IMD->getBeginLoc(), 1, "/** "); ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ "); } else { InsertText(IMD->getBeginLoc(), "// "); } } else InsertText(CID->getBeginLoc(), "// "); for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) { if (!OMD->getBody()) continue; std::string ResultStr; RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); SourceLocation LocStart = OMD->getBeginLoc(); SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc(); const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); ReplaceText(LocStart, endBuf-startBuf, ResultStr); } for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) { if (!OMD->getBody()) continue; std::string ResultStr; RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); SourceLocation LocStart = OMD->getBeginLoc(); SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc(); const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); ReplaceText(LocStart, endBuf-startBuf, ResultStr); } for (auto *I : IMD ? IMD->property_impls() : CID->property_impls()) RewritePropertyImplDecl(I, IMD, CID); InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// "); } void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { // Do not synthesize more than once. if (ObjCSynthesizedStructs.count(ClassDecl)) return; // Make sure super class's are written before current class is written. ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass(); while (SuperClass) { RewriteInterfaceDecl(SuperClass); SuperClass = SuperClass->getSuperClass(); } std::string ResultStr; if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) { // we haven't seen a forward decl - generate a typedef. RewriteOneForwardClassDecl(ClassDecl, ResultStr); RewriteIvarOffsetSymbols(ClassDecl, ResultStr); RewriteObjCInternalStruct(ClassDecl, ResultStr); // Mark this typedef as having been written into its c++ equivalent. ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl()); for (auto *I : ClassDecl->instance_properties()) RewriteProperty(I); for (auto *I : ClassDecl->instance_methods()) RewriteMethodDeclaration(I); for (auto *I : ClassDecl->class_methods()) RewriteMethodDeclaration(I); // Lastly, comment out the @end. ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"), "/* @end */\n"); } } Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) { SourceRange OldRange = PseudoOp->getSourceRange(); // We just magically know some things about the structure of this // expression. ObjCMessageExpr *OldMsg = cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr( PseudoOp->getNumSemanticExprs() - 1)); // Because the rewriter doesn't allow us to rewrite rewritten code, // we need to suppress rewriting the sub-statements. Expr *Base; SmallVector<Expr*, 2> Args; { DisableReplaceStmtScope S(*this); // Rebuild the base expression if we have one. Base = nullptr; if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) { Base = OldMsg->getInstanceReceiver(); Base = cast<OpaqueValueExpr>(Base)->getSourceExpr(); Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base)); } unsigned numArgs = OldMsg->getNumArgs(); for (unsigned i = 0; i < numArgs; i++) { Expr *Arg = OldMsg->getArg(i); if (isa<OpaqueValueExpr>(Arg)) Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr(); Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg)); Args.push_back(Arg); } } // TODO: avoid this copy. SmallVector<SourceLocation, 1> SelLocs; OldMsg->getSelectorLocs(SelLocs); ObjCMessageExpr *NewMsg = nullptr; switch (OldMsg->getReceiverKind()) { case ObjCMessageExpr::Class: NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), OldMsg->getValueKind(), OldMsg->getLeftLoc(), OldMsg->getClassReceiverTypeInfo(), OldMsg->getSelector(), SelLocs, OldMsg->getMethodDecl(), Args, OldMsg->getRightLoc(), OldMsg->isImplicit()); break; case ObjCMessageExpr::Instance: NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), OldMsg->getValueKind(), OldMsg->getLeftLoc(), Base, OldMsg->getSelector(), SelLocs, OldMsg->getMethodDecl(), Args, OldMsg->getRightLoc(), OldMsg->isImplicit()); break; case ObjCMessageExpr::SuperClass: case ObjCMessageExpr::SuperInstance: NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), OldMsg->getValueKind(), OldMsg->getLeftLoc(), OldMsg->getSuperLoc(), OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance, OldMsg->getSuperType(), OldMsg->getSelector(), SelLocs, OldMsg->getMethodDecl(), Args, OldMsg->getRightLoc(), OldMsg->isImplicit()); break; } Stmt *Replacement = SynthMessageExpr(NewMsg); ReplaceStmtWithRange(PseudoOp, Replacement, OldRange); return Replacement; } Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) { SourceRange OldRange = PseudoOp->getSourceRange(); // We just magically know some things about the structure of this // expression. ObjCMessageExpr *OldMsg = cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit()); // Because the rewriter doesn't allow us to rewrite rewritten code, // we need to suppress rewriting the sub-statements. Expr *Base = nullptr; SmallVector<Expr*, 1> Args; { DisableReplaceStmtScope S(*this); // Rebuild the base expression if we have one. if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) { Base = OldMsg->getInstanceReceiver(); Base = cast<OpaqueValueExpr>(Base)->getSourceExpr(); Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base)); } unsigned numArgs = OldMsg->getNumArgs(); for (unsigned i = 0; i < numArgs; i++) { Expr *Arg = OldMsg->getArg(i); if (isa<OpaqueValueExpr>(Arg)) Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr(); Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg)); Args.push_back(Arg); } } // Intentionally empty. SmallVector<SourceLocation, 1> SelLocs; ObjCMessageExpr *NewMsg = nullptr; switch (OldMsg->getReceiverKind()) { case ObjCMessageExpr::Class: NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), OldMsg->getValueKind(), OldMsg->getLeftLoc(), OldMsg->getClassReceiverTypeInfo(), OldMsg->getSelector(), SelLocs, OldMsg->getMethodDecl(), Args, OldMsg->getRightLoc(), OldMsg->isImplicit()); break; case ObjCMessageExpr::Instance: NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), OldMsg->getValueKind(), OldMsg->getLeftLoc(), Base, OldMsg->getSelector(), SelLocs, OldMsg->getMethodDecl(), Args, OldMsg->getRightLoc(), OldMsg->isImplicit()); break; case ObjCMessageExpr::SuperClass: case ObjCMessageExpr::SuperInstance: NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), OldMsg->getValueKind(), OldMsg->getLeftLoc(), OldMsg->getSuperLoc(), OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance, OldMsg->getSuperType(), OldMsg->getSelector(), SelLocs, OldMsg->getMethodDecl(), Args, OldMsg->getRightLoc(), OldMsg->isImplicit()); break; } Stmt *Replacement = SynthMessageExpr(NewMsg); ReplaceStmtWithRange(PseudoOp, Replacement, OldRange); return Replacement; } /// SynthCountByEnumWithState - To print: /// ((NSUInteger (*) /// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger)) /// (void *)objc_msgSend)((id)l_collection, /// sel_registerName( /// "countByEnumeratingWithState:objects:count:"), /// &enumState, /// (id *)__rw_items, (NSUInteger)16) /// void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) { buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, " "id *, _WIN_NSUInteger))(void *)objc_msgSend)"; buf += "\n\t\t"; buf += "((id)l_collection,\n\t\t"; buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),"; buf += "\n\t\t"; buf += "&enumState, " "(id *)__rw_items, (_WIN_NSUInteger)16)"; } /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach /// statement to exit to its outer synthesized loop. /// Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) { if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back())) return S; // replace break with goto __break_label std::string buf; SourceLocation startLoc = S->getBeginLoc(); buf = "goto __break_label_"; buf += utostr(ObjCBcLabelNo.back()); ReplaceText(startLoc, strlen("break"), buf); return nullptr; } void RewriteModernObjC::ConvertSourceLocationToLineDirective( SourceLocation Loc, std::string &LineString) { if (Loc.isFileID() && GenerateLineInfo) { LineString += "\n#line "; PresumedLoc PLoc = SM->getPresumedLoc(Loc); LineString += utostr(PLoc.getLine()); LineString += " \""; LineString += Lexer::Stringify(PLoc.getFilename()); LineString += "\"\n"; } } /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach /// statement to continue with its inner synthesized loop. /// Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) { if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back())) return S; // replace continue with goto __continue_label std::string buf; SourceLocation startLoc = S->getBeginLoc(); buf = "goto __continue_label_"; buf += utostr(ObjCBcLabelNo.back()); ReplaceText(startLoc, strlen("continue"), buf); return nullptr; } /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement. /// It rewrites: /// for ( type elem in collection) { stmts; } /// Into: /// { /// type elem; /// struct __objcFastEnumerationState enumState = { 0 }; /// id __rw_items[16]; /// id l_collection = (id)collection; /// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState /// objects:__rw_items count:16]; /// if (limit) { /// unsigned long startMutations = *enumState.mutationsPtr; /// do { /// unsigned long counter = 0; /// do { /// if (startMutations != *enumState.mutationsPtr) /// objc_enumerationMutation(l_collection); /// elem = (type)enumState.itemsPtr[counter++]; /// stmts; /// __continue_label: ; /// } while (counter < limit); /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState /// objects:__rw_items count:16])); /// elem = nil; /// __break_label: ; /// } /// else /// elem = nil; /// } /// Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, SourceLocation OrigEnd) { assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty"); assert(isa<ObjCForCollectionStmt>(Stmts.back()) && "ObjCForCollectionStmt Statement stack mismatch"); assert(!ObjCBcLabelNo.empty() && "ObjCForCollectionStmt - Label No stack empty"); SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); StringRef elementName; std::string elementTypeAsString; std::string buf; // line directive first. SourceLocation ForEachLoc = S->getForLoc(); ConvertSourceLocationToLineDirective(ForEachLoc, buf); buf += "{\n\t"; if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) { // type elem; NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl()); QualType ElementType = cast<ValueDecl>(D)->getType(); if (ElementType->isObjCQualifiedIdType() || ElementType->isObjCQualifiedInterfaceType()) // Simply use 'id' for all qualified types. elementTypeAsString = "id"; else elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy()); buf += elementTypeAsString; buf += " "; elementName = D->getName(); buf += elementName; buf += ";\n\t"; } else { DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement()); elementName = DR->getDecl()->getName(); ValueDecl *VD = DR->getDecl(); if (VD->getType()->isObjCQualifiedIdType() || VD->getType()->isObjCQualifiedInterfaceType()) // Simply use 'id' for all qualified types. elementTypeAsString = "id"; else elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy()); } // struct __objcFastEnumerationState enumState = { 0 }; buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t"; // id __rw_items[16]; buf += "id __rw_items[16];\n\t"; // id l_collection = (id) buf += "id l_collection = (id)"; // Find start location of 'collection' the hard way! const char *startCollectionBuf = startBuf; startCollectionBuf += 3; // skip 'for' startCollectionBuf = strchr(startCollectionBuf, '('); startCollectionBuf++; // skip '(' // find 'in' and skip it. while (*startCollectionBuf != ' ' || *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' || (*(startCollectionBuf+3) != ' ' && *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '(')) startCollectionBuf++; startCollectionBuf += 3; // Replace: "for (type element in" with string constructed thus far. ReplaceText(startLoc, startCollectionBuf - startBuf, buf); // Replace ')' in for '(' type elem in collection ')' with ';' SourceLocation rightParenLoc = S->getRParenLoc(); const char *rparenBuf = SM->getCharacterData(rightParenLoc); SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf); buf = ";\n\t"; // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState // objects:__rw_items count:16]; // which is synthesized into: // NSUInteger limit = // ((NSUInteger (*) // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger)) // (void *)objc_msgSend)((id)l_collection, // sel_registerName( // "countByEnumeratingWithState:objects:count:"), // (struct __objcFastEnumerationState *)&state, // (id *)__rw_items, (NSUInteger)16); buf += "_WIN_NSUInteger limit =\n\t\t"; SynthCountByEnumWithState(buf); buf += ";\n\t"; /// if (limit) { /// unsigned long startMutations = *enumState.mutationsPtr; /// do { /// unsigned long counter = 0; /// do { /// if (startMutations != *enumState.mutationsPtr) /// objc_enumerationMutation(l_collection); /// elem = (type)enumState.itemsPtr[counter++]; buf += "if (limit) {\n\t"; buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t"; buf += "do {\n\t\t"; buf += "unsigned long counter = 0;\n\t\t"; buf += "do {\n\t\t\t"; buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t"; buf += "objc_enumerationMutation(l_collection);\n\t\t\t"; buf += elementName; buf += " = ("; buf += elementTypeAsString; buf += ")enumState.itemsPtr[counter++];"; // Replace ')' in for '(' type elem in collection ')' with all of these. ReplaceText(lparenLoc, 1, buf); /// __continue_label: ; /// } while (counter < limit); /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState /// objects:__rw_items count:16])); /// elem = nil; /// __break_label: ; /// } /// else /// elem = nil; /// } /// buf = ";\n\t"; buf += "__continue_label_"; buf += utostr(ObjCBcLabelNo.back()); buf += ": ;"; buf += "\n\t\t"; buf += "} while (counter < limit);\n\t"; buf += "} while ((limit = "; SynthCountByEnumWithState(buf); buf += "));\n\t"; buf += elementName; buf += " = (("; buf += elementTypeAsString; buf += ")0);\n\t"; buf += "__break_label_"; buf += utostr(ObjCBcLabelNo.back()); buf += ": ;\n\t"; buf += "}\n\t"; buf += "else\n\t\t"; buf += elementName; buf += " = (("; buf += elementTypeAsString; buf += ")0);\n\t"; buf += "}\n"; // Insert all these *after* the statement body. // FIXME: If this should support Obj-C++, support CXXTryStmt if (isa<CompoundStmt>(S->getBody())) { SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1); InsertText(endBodyLoc, buf); } else { /* Need to treat single statements specially. For example: * * for (A *a in b) if (stuff()) break; * for (A *a in b) xxxyy; * * The following code simply scans ahead to the semi to find the actual end. */ const char *stmtBuf = SM->getCharacterData(OrigEnd); const char *semiBuf = strchr(stmtBuf, ';'); assert(semiBuf && "Can't find ';'"); SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1); InsertText(endBodyLoc, buf); } Stmts.pop_back(); ObjCBcLabelNo.pop_back(); return nullptr; } static void Write_RethrowObject(std::string &buf) { buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n"; buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n"; buf += "\tid rethrow;\n"; buf += "\t} _fin_force_rethow(_rethrow);"; } /// RewriteObjCSynchronizedStmt - /// This routine rewrites @synchronized(expr) stmt; /// into: /// objc_sync_enter(expr); /// @try stmt @finally { objc_sync_exit(expr); } /// Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { // Get the start location and compute the semi location. SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @synchronized location"); std::string buf; SourceLocation SynchLoc = S->getAtSynchronizedLoc(); ConvertSourceLocationToLineDirective(SynchLoc, buf); buf += "{ id _rethrow = 0; id _sync_obj = (id)"; const char *lparenBuf = startBuf; while (*lparenBuf != '(') lparenBuf++; ReplaceText(startLoc, lparenBuf-startBuf+1, buf); buf = "; objc_sync_enter(_sync_obj);\n"; buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}"; buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}"; buf += "\n\tid sync_exit;"; buf += "\n\t} _sync_exit(_sync_obj);\n"; // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since // the sync expression is typically a message expression that's already // been rewritten! (which implies the SourceLocation's are invalid). SourceLocation RParenExprLoc = S->getSynchBody()->getBeginLoc(); const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc); while (*RParenExprLocBuf != ')') RParenExprLocBuf--; RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf); SourceLocation LBranceLoc = S->getSynchBody()->getBeginLoc(); const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc); assert (*LBraceLocBuf == '{'); ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf); SourceLocation startRBraceLoc = S->getSynchBody()->getEndLoc(); assert((*SM->getCharacterData(startRBraceLoc) == '}') && "bogus @synchronized block"); buf = "} catch (id e) {_rethrow = e;}\n"; Write_RethrowObject(buf); buf += "}\n"; buf += "}\n"; ReplaceText(startRBraceLoc, 1, buf); return nullptr; } void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S) { // Perform a bottom up traversal of all children. for (Stmt *SubStmt : S->children()) if (SubStmt) WarnAboutReturnGotoStmts(SubStmt); if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) { Diags.Report(Context->getFullLoc(S->getBeginLoc()), TryFinallyContainsReturnDiag); } } Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) { SourceLocation startLoc = S->getAtLoc(); ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */"); ReplaceText(S->getSubStmt()->getBeginLoc(), 1, "{ __AtAutoreleasePool __autoreleasepool; "); return nullptr; } Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt(); bool noCatch = S->getNumCatchStmts() == 0; std::string buf; SourceLocation TryLocation = S->getAtTryLoc(); ConvertSourceLocationToLineDirective(TryLocation, buf); if (finalStmt) { if (noCatch) buf += "{ id volatile _rethrow = 0;\n"; else { buf += "{ id volatile _rethrow = 0;\ntry {\n"; } } // Get the start location and compute the semi location. SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @try location"); if (finalStmt) ReplaceText(startLoc, 1, buf); else // @try -> try ReplaceText(startLoc, 1, ""); for (ObjCAtCatchStmt *Catch : S->catch_stmts()) { VarDecl *catchDecl = Catch->getCatchParamDecl(); startLoc = Catch->getBeginLoc(); bool AtRemoved = false; if (catchDecl) { QualType t = catchDecl->getType(); if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) { // Should be a pointer to a class. ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface(); if (IDecl) { std::string Result; ConvertSourceLocationToLineDirective(Catch->getBeginLoc(), Result); startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @catch location"); SourceLocation rParenLoc = Catch->getRParenLoc(); const char *rParenBuf = SM->getCharacterData(rParenLoc); // _objc_exc_Foo *_e as argument to catch. Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString(); Result += " *_"; Result += catchDecl->getNameAsString(); Result += ")"; ReplaceText(startLoc, rParenBuf-startBuf+1, Result); // Foo *e = (Foo *)_e; Result.clear(); Result = "{ "; Result += IDecl->getNameAsString(); Result += " *"; Result += catchDecl->getNameAsString(); Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)"; Result += "_"; Result += catchDecl->getNameAsString(); Result += "; "; SourceLocation lBraceLoc = Catch->getCatchBody()->getBeginLoc(); ReplaceText(lBraceLoc, 1, Result); AtRemoved = true; } } } if (!AtRemoved) // @catch -> catch ReplaceText(startLoc, 1, ""); } if (finalStmt) { buf.clear(); SourceLocation FinallyLoc = finalStmt->getBeginLoc(); if (noCatch) { ConvertSourceLocationToLineDirective(FinallyLoc, buf); buf += "catch (id e) {_rethrow = e;}\n"; } else { buf += "}\n"; ConvertSourceLocationToLineDirective(FinallyLoc, buf); buf += "catch (id e) {_rethrow = e;}\n"; } SourceLocation startFinalLoc = finalStmt->getBeginLoc(); ReplaceText(startFinalLoc, 8, buf); Stmt *body = finalStmt->getFinallyBody(); SourceLocation startFinalBodyLoc = body->getBeginLoc(); buf.clear(); Write_RethrowObject(buf); ReplaceText(startFinalBodyLoc, 1, buf); SourceLocation endFinalBodyLoc = body->getEndLoc(); ReplaceText(endFinalBodyLoc, 1, "}\n}"); // Now check for any return/continue/go statements within the @try. WarnAboutReturnGotoStmts(S->getTryBody()); } return nullptr; } // This can't be done with ReplaceStmt(S, ThrowExpr), since // the throw expression is typically a message expression that's already // been rewritten! (which implies the SourceLocation's are invalid). Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) { // Get the start location and compute the semi location. SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @throw location"); std::string buf; /* void objc_exception_throw(id) __attribute__((noreturn)); */ if (S->getThrowExpr()) buf = "objc_exception_throw("; else buf = "throw"; // handle "@ throw" correctly. const char *wBuf = strchr(startBuf, 'w'); assert((*wBuf == 'w') && "@throw: can't find 'w'"); ReplaceText(startLoc, wBuf-startBuf+1, buf); SourceLocation endLoc = S->getEndLoc(); const char *endBuf = SM->getCharacterData(endLoc); const char *semiBuf = strchr(endBuf, ';'); assert((*semiBuf == ';') && "@throw: can't find ';'"); SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf); if (S->getThrowExpr()) ReplaceText(semiLoc, 1, ");"); return nullptr; } Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) { // Create a new string expression. std::string StrEncoding; Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding); Expr *Replacement = getStringLiteral(StrEncoding); ReplaceStmt(Exp, Replacement); // Replace this subexpr in the parent. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. return Replacement; } Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) { if (!SelGetUidFunctionDecl) SynthSelGetUidFunctionDecl(); assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl"); // Create a call to sel_registerName("selName"). SmallVector<Expr*, 8> SelExprs; SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString())); CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, SelExprs); ReplaceStmt(Exp, SelExp); // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. return SelExp; } CallExpr * RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD, ArrayRef<Expr *> Args, SourceLocation StartLoc, SourceLocation EndLoc) { // Get the type, we will need to reference it in a couple spots. QualType msgSendType = FD->getType(); // Create a reference to the objc_msgSend() declaration. DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType, VK_LValue, SourceLocation()); // Now, we cast the reference to a pointer to the objc_msgSend type. QualType pToFunc = Context->getPointerType(msgSendType); ImplicitCastExpr *ICE = ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay, DRE, nullptr, VK_PRValue, FPOptionsOverride()); const auto *FT = msgSendType->castAs<FunctionType>(); CallExpr *Exp = CallExpr::Create(*Context, ICE, Args, FT->getCallResultType(*Context), VK_PRValue, EndLoc, FPOptionsOverride()); return Exp; } static bool scanForProtocolRefs(const char *startBuf, const char *endBuf, const char *&startRef, const char *&endRef) { while (startBuf < endBuf) { if (*startBuf == '<') startRef = startBuf; // mark the start. if (*startBuf == '>') { if (startRef && *startRef == '<') { endRef = startBuf; // mark the end. return true; } return false; } startBuf++; } return false; } static void scanToNextArgument(const char *&argRef) { int angle = 0; while (*argRef != ')' && (*argRef != ',' || angle > 0)) { if (*argRef == '<') angle++; else if (*argRef == '>') angle--; argRef++; } assert(angle == 0 && "scanToNextArgument - bad protocol type syntax"); } bool RewriteModernObjC::needToScanForQualifiers(QualType T) { if (T->isObjCQualifiedIdType()) return true; if (const PointerType *PT = T->getAs<PointerType>()) { if (PT->getPointeeType()->isObjCQualifiedIdType()) return true; } if (T->isObjCObjectPointerType()) { T = T->getPointeeType(); return T->isObjCQualifiedInterfaceType(); } if (T->isArrayType()) { QualType ElemTy = Context->getBaseElementType(T); return needToScanForQualifiers(ElemTy); } return false; } void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) { QualType Type = E->getType(); if (needToScanForQualifiers(Type)) { SourceLocation Loc, EndLoc; if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) { Loc = ECE->getLParenLoc(); EndLoc = ECE->getRParenLoc(); } else { Loc = E->getBeginLoc(); EndLoc = E->getEndLoc(); } // This will defend against trying to rewrite synthesized expressions. if (Loc.isInvalid() || EndLoc.isInvalid()) return; const char *startBuf = SM->getCharacterData(Loc); const char *endBuf = SM->getCharacterData(EndLoc); const char *startRef = nullptr, *endRef = nullptr; if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { // Get the locations of the startRef, endRef. SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf); SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1); // Comment out the protocol references. InsertText(LessLoc, "/*"); InsertText(GreaterLoc, "*/"); } } } void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) { SourceLocation Loc; QualType Type; const FunctionProtoType *proto = nullptr; if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) { Loc = VD->getLocation(); Type = VD->getType(); } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) { Loc = FD->getLocation(); // Check for ObjC 'id' and class types that have been adorned with protocol // information (id<p>, C<p>*). The protocol references need to be rewritten! const FunctionType *funcType = FD->getType()->getAs<FunctionType>(); assert(funcType && "missing function type"); proto = dyn_cast<FunctionProtoType>(funcType); if (!proto) return; Type = proto->getReturnType(); } else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) { Loc = FD->getLocation(); Type = FD->getType(); } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) { Loc = TD->getLocation(); Type = TD->getUnderlyingType(); } else return; if (needToScanForQualifiers(Type)) { // Since types are unique, we need to scan the buffer. const char *endBuf = SM->getCharacterData(Loc); const char *startBuf = endBuf; while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart) startBuf--; // scan backward (from the decl location) for return type. const char *startRef = nullptr, *endRef = nullptr; if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { // Get the locations of the startRef, endRef. SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf); SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1); // Comment out the protocol references. InsertText(LessLoc, "/*"); InsertText(GreaterLoc, "*/"); } } if (!proto) return; // most likely, was a variable // Now check arguments. const char *startBuf = SM->getCharacterData(Loc); const char *startFuncBuf = startBuf; for (unsigned i = 0; i < proto->getNumParams(); i++) { if (needToScanForQualifiers(proto->getParamType(i))) { // Since types are unique, we need to scan the buffer. const char *endBuf = startBuf; // scan forward (from the decl location) for argument types. scanToNextArgument(endBuf); const char *startRef = nullptr, *endRef = nullptr; if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { // Get the locations of the startRef, endRef. SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startFuncBuf); SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startFuncBuf+1); // Comment out the protocol references. InsertText(LessLoc, "/*"); InsertText(GreaterLoc, "*/"); } startBuf = ++endBuf; } else { // If the function name is derived from a macro expansion, then the // argument buffer will not follow the name. Need to speak with Chris. while (*startBuf && *startBuf != ')' && *startBuf != ',') startBuf++; // scan forward (from the decl location) for argument types. startBuf++; } } } void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) { QualType QT = ND->getType(); const Type* TypePtr = QT->getAs<Type>(); if (!isa<TypeOfExprType>(TypePtr)) return; while (isa<TypeOfExprType>(TypePtr)) { const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr); QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType(); TypePtr = QT->getAs<Type>(); } // FIXME. This will not work for multiple declarators; as in: // __typeof__(a) b,c,d; std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy())); SourceLocation DeclLoc = ND->getTypeSpecStartLoc(); const char *startBuf = SM->getCharacterData(DeclLoc); if (ND->getInit()) { std::string Name(ND->getNameAsString()); TypeAsString += " " + Name + " = "; Expr *E = ND->getInit(); SourceLocation startLoc; if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) startLoc = ECE->getLParenLoc(); else startLoc = E->getBeginLoc(); startLoc = SM->getExpansionLoc(startLoc); const char *endBuf = SM->getCharacterData(startLoc); ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString); } else { SourceLocation X = ND->getEndLoc(); X = SM->getExpansionLoc(X); const char *endBuf = SM->getCharacterData(X); ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString); } } // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str); void RewriteModernObjC::SynthSelGetUidFunctionDecl() { IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName"); SmallVector<QualType, 16> ArgTys; ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); QualType getFuncType = getSimpleFunctionType(Context->getObjCSelType(), ArgTys); SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), SelGetUidIdent, getFuncType, nullptr, SC_Extern); } void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) { // declared in <objc/objc.h> if (FD->getIdentifier() && FD->getName() == "sel_registerName") { SelGetUidFunctionDecl = FD; return; } RewriteObjCQualifiedInterfaceTypes(FD); } void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) { std::string TypeString(Type.getAsString(Context->getPrintingPolicy())); const char *argPtr = TypeString.c_str(); if (!strchr(argPtr, '^')) { Str += TypeString; return; } while (*argPtr) { Str += (*argPtr == '^' ? '*' : *argPtr); argPtr++; } } // FIXME. Consolidate this routine with RewriteBlockPointerType. void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD) { QualType Type = VD->getType(); std::string TypeString(Type.getAsString(Context->getPrintingPolicy())); const char *argPtr = TypeString.c_str(); int paren = 0; while (*argPtr) { switch (*argPtr) { case '(': Str += *argPtr; paren++; break; case ')': Str += *argPtr; paren--; break; case '^': Str += '*'; if (paren == 1) Str += VD->getNameAsString(); break; default: Str += *argPtr; break; } argPtr++; } } void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) { SourceLocation FunLocStart = FD->getTypeSpecStartLoc(); const FunctionType *funcType = FD->getType()->getAs<FunctionType>(); const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType); if (!proto) return; QualType Type = proto->getReturnType(); std::string FdStr = Type.getAsString(Context->getPrintingPolicy()); FdStr += " "; FdStr += FD->getName(); FdStr += "("; unsigned numArgs = proto->getNumParams(); for (unsigned i = 0; i < numArgs; i++) { QualType ArgType = proto->getParamType(i); RewriteBlockPointerType(FdStr, ArgType); if (i+1 < numArgs) FdStr += ", "; } if (FD->isVariadic()) { FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n"; } else FdStr += ");\n"; InsertText(FunLocStart, FdStr); } // SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super); void RewriteModernObjC::SynthSuperConstructorFunctionDecl() { if (SuperConstructorFunctionDecl) return; IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super"); SmallVector<QualType, 16> ArgTys; QualType argT = Context->getObjCIdType(); assert(!argT.isNull() && "Can't find 'id' type"); ArgTys.push_back(argT); ArgTys.push_back(argT); QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), ArgTys); SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), msgSendIdent, msgSendType, nullptr, SC_Extern); } // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...); void RewriteModernObjC::SynthMsgSendFunctionDecl() { IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend"); SmallVector<QualType, 16> ArgTys; QualType argT = Context->getObjCIdType(); assert(!argT.isNull() && "Can't find 'id' type"); ArgTys.push_back(argT); argT = Context->getObjCSelType(); assert(!argT.isNull() && "Can't find 'SEL' type"); ArgTys.push_back(argT); QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), ArgTys, /*variadic=*/true); MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), msgSendIdent, msgSendType, nullptr, SC_Extern); } // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void); void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() { IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper"); SmallVector<QualType, 2> ArgTys; ArgTys.push_back(Context->VoidTy); QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), ArgTys, /*variadic=*/true); MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), msgSendIdent, msgSendType, nullptr, SC_Extern); } // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...); void RewriteModernObjC::SynthMsgSendStretFunctionDecl() { IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret"); SmallVector<QualType, 16> ArgTys; QualType argT = Context->getObjCIdType(); assert(!argT.isNull() && "Can't find 'id' type"); ArgTys.push_back(argT); argT = Context->getObjCSelType(); assert(!argT.isNull() && "Can't find 'SEL' type"); ArgTys.push_back(argT); QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), ArgTys, /*variadic=*/true); MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), msgSendIdent, msgSendType, nullptr, SC_Extern); } // SynthMsgSendSuperStretFunctionDecl - // id objc_msgSendSuper_stret(void); void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() { IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper_stret"); SmallVector<QualType, 2> ArgTys; ArgTys.push_back(Context->VoidTy); QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), ArgTys, /*variadic=*/true); MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), msgSendIdent, msgSendType, nullptr, SC_Extern); } // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...); void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() { IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret"); SmallVector<QualType, 16> ArgTys; QualType argT = Context->getObjCIdType(); assert(!argT.isNull() && "Can't find 'id' type"); ArgTys.push_back(argT); argT = Context->getObjCSelType(); assert(!argT.isNull() && "Can't find 'SEL' type"); ArgTys.push_back(argT); QualType msgSendType = getSimpleFunctionType(Context->DoubleTy, ArgTys, /*variadic=*/true); MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), msgSendIdent, msgSendType, nullptr, SC_Extern); } // SynthGetClassFunctionDecl - Class objc_getClass(const char *name); void RewriteModernObjC::SynthGetClassFunctionDecl() { IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass"); SmallVector<QualType, 16> ArgTys; ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(), ArgTys); GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), getClassIdent, getClassType, nullptr, SC_Extern); } // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls); void RewriteModernObjC::SynthGetSuperClassFunctionDecl() { IdentifierInfo *getSuperClassIdent = &Context->Idents.get("class_getSuperclass"); SmallVector<QualType, 16> ArgTys; ArgTys.push_back(Context->getObjCClassType()); QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(), ArgTys); GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), getSuperClassIdent, getClassType, nullptr, SC_Extern); } // SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name); void RewriteModernObjC::SynthGetMetaClassFunctionDecl() { IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass"); SmallVector<QualType, 16> ArgTys; ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(), ArgTys); GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), getClassIdent, getClassType, nullptr, SC_Extern); } Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) { assert (Exp != nullptr && "Expected non-null ObjCStringLiteral"); QualType strType = getConstantStringStructType(); std::string S = "__NSConstantStringImpl_"; std::string tmpName = InFileName; unsigned i; for (i=0; i < tmpName.length(); i++) { char c = tmpName.at(i); // replace any non-alphanumeric characters with '_'. if (!isAlphanumeric(c)) tmpName[i] = '_'; } S += tmpName; S += "_"; S += utostr(NumObjCStringLiterals++); Preamble += "static __NSConstantStringImpl " + S; Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,"; Preamble += "0x000007c8,"; // utf8_str // The pretty printer for StringLiteral handles escape characters properly. std::string prettyBufS; llvm::raw_string_ostream prettyBuf(prettyBufS); Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts)); Preamble += prettyBuf.str(); Preamble += ","; Preamble += utostr(Exp->getString()->getByteLength()) + "};\n"; VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(S), strType, nullptr, SC_Static); DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation()); Expr *Unop = UnaryOperator::Create( const_cast<ASTContext &>(*Context), DRE, UO_AddrOf, Context->getPointerType(DRE->getType()), VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); // cast to NSConstantString * CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(), CK_CPointerToObjCPointerCast, Unop); ReplaceStmt(Exp, cast); // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. return cast; } Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) { unsigned IntSize = static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, Exp->getValue()), Context->IntTy, Exp->getLocation()); CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy, CK_BitCast, FlagExp); ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(), cast); ReplaceStmt(Exp, PE); return PE; } Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) { // synthesize declaration of helper functions needed in this routine. if (!SelGetUidFunctionDecl) SynthSelGetUidFunctionDecl(); // use objc_msgSend() for all. if (!MsgSendFunctionDecl) SynthMsgSendFunctionDecl(); if (!GetClassFunctionDecl) SynthGetClassFunctionDecl(); FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; SourceLocation StartLoc = Exp->getBeginLoc(); SourceLocation EndLoc = Exp->getEndLoc(); // Synthesize a call to objc_msgSend(). SmallVector<Expr*, 4> MsgExprs; SmallVector<Expr*, 4> ClsExprs; // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument. ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod(); ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface(); IdentifierInfo *clsName = BoxingClass->getIdentifier(); ClsExprs.push_back(getStringLiteral(clsName->getName())); CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs, StartLoc, EndLoc); MsgExprs.push_back(Cls); // Create a call to sel_registerName("<BoxingMethod>:"), etc. // it will be the 2nd argument. SmallVector<Expr*, 4> SelExprs; SelExprs.push_back( getStringLiteral(BoxingMethod->getSelector().getAsString())); CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, SelExprs, StartLoc, EndLoc); MsgExprs.push_back(SelExp); // User provided sub-expression is the 3rd, and last, argument. Expr *subExpr = Exp->getSubExpr(); if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) { QualType type = ICE->getType(); const Expr *SubExpr = ICE->IgnoreParenImpCasts(); CastKind CK = CK_BitCast; if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType()) CK = CK_IntegralToBoolean; subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr); } MsgExprs.push_back(subExpr); SmallVector<QualType, 4> ArgTypes; ArgTypes.push_back(Context->getObjCClassType()); ArgTypes.push_back(Context->getObjCSelType()); for (const auto PI : BoxingMethod->parameters()) ArgTypes.push_back(PI->getType()); QualType returnType = Exp->getType(); // Get the type, we will need to reference it in a couple spots. QualType msgSendType = MsgSendFlavor->getType(); // Create a reference to the objc_msgSend() declaration. DeclRefExpr *DRE = new (Context) DeclRefExpr( *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); CastExpr *cast = NoTypeInfoCStyleCastExpr( Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE); // Now do the "normal" pointer to function cast. QualType castType = getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic()); castType = Context->getPointerType(castType); cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, cast); // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); auto *FT = msgSendType->castAs<FunctionType>(); CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), VK_PRValue, EndLoc, FPOptionsOverride()); ReplaceStmt(Exp, CE); return CE; } Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { // synthesize declaration of helper functions needed in this routine. if (!SelGetUidFunctionDecl) SynthSelGetUidFunctionDecl(); // use objc_msgSend() for all. if (!MsgSendFunctionDecl) SynthMsgSendFunctionDecl(); if (!GetClassFunctionDecl) SynthGetClassFunctionDecl(); FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; SourceLocation StartLoc = Exp->getBeginLoc(); SourceLocation EndLoc = Exp->getEndLoc(); // Build the expression: __NSContainer_literal(int, ...).arr QualType IntQT = Context->IntTy; QualType NSArrayFType = getSimpleFunctionType(Context->VoidTy, IntQT, true); std::string NSArrayFName("__NSContainer_literal"); FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName); DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr( *Context, NSArrayFD, false, NSArrayFType, VK_PRValue, SourceLocation()); SmallVector<Expr*, 16> InitExprs; unsigned NumElements = Exp->getNumElements(); unsigned UnsignedIntSize = static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); Expr *count = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, NumElements), Context->UnsignedIntTy, SourceLocation()); InitExprs.push_back(count); for (unsigned i = 0; i < NumElements; i++) InitExprs.push_back(Exp->getElement(i)); Expr *NSArrayCallExpr = CallExpr::Create(*Context, NSArrayDRE, InitExprs, NSArrayFType, VK_LValue, SourceLocation(), FPOptionsOverride()); FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get("arr"), Context->getPointerType(Context->VoidPtrTy), nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); MemberExpr *ArrayLiteralME = MemberExpr::CreateImplicit(*Context, NSArrayCallExpr, false, ARRFD, ARRFD->getType(), VK_LValue, OK_Ordinary); QualType ConstIdT = Context->getObjCIdType().withConst(); CStyleCastExpr * ArrayLiteralObjects = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(ConstIdT), CK_BitCast, ArrayLiteralME); // Synthesize a call to objc_msgSend(). SmallVector<Expr*, 32> MsgExprs; SmallVector<Expr*, 4> ClsExprs; QualType expType = Exp->getType(); // Create a call to objc_getClass("NSArray"). It will be th 1st argument. ObjCInterfaceDecl *Class = expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface(); IdentifierInfo *clsName = Class->getIdentifier(); ClsExprs.push_back(getStringLiteral(clsName->getName())); CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs, StartLoc, EndLoc); MsgExprs.push_back(Cls); // Create a call to sel_registerName("arrayWithObjects:count:"). // it will be the 2nd argument. SmallVector<Expr*, 4> SelExprs; ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod(); SelExprs.push_back( getStringLiteral(ArrayMethod->getSelector().getAsString())); CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, SelExprs, StartLoc, EndLoc); MsgExprs.push_back(SelExp); // (const id [])objects MsgExprs.push_back(ArrayLiteralObjects); // (NSUInteger)cnt Expr *cnt = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, NumElements), Context->UnsignedIntTy, SourceLocation()); MsgExprs.push_back(cnt); SmallVector<QualType, 4> ArgTypes; ArgTypes.push_back(Context->getObjCClassType()); ArgTypes.push_back(Context->getObjCSelType()); for (const auto *PI : ArrayMethod->parameters()) ArgTypes.push_back(PI->getType()); QualType returnType = Exp->getType(); // Get the type, we will need to reference it in a couple spots. QualType msgSendType = MsgSendFlavor->getType(); // Create a reference to the objc_msgSend() declaration. DeclRefExpr *DRE = new (Context) DeclRefExpr( *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); CastExpr *cast = NoTypeInfoCStyleCastExpr( Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE); // Now do the "normal" pointer to function cast. QualType castType = getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic()); castType = Context->getPointerType(castType); cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, cast); // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); const FunctionType *FT = msgSendType->castAs<FunctionType>(); CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), VK_PRValue, EndLoc, FPOptionsOverride()); ReplaceStmt(Exp, CE); return CE; } Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) { // synthesize declaration of helper functions needed in this routine. if (!SelGetUidFunctionDecl) SynthSelGetUidFunctionDecl(); // use objc_msgSend() for all. if (!MsgSendFunctionDecl) SynthMsgSendFunctionDecl(); if (!GetClassFunctionDecl) SynthGetClassFunctionDecl(); FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; SourceLocation StartLoc = Exp->getBeginLoc(); SourceLocation EndLoc = Exp->getEndLoc(); // Build the expression: __NSContainer_literal(int, ...).arr QualType IntQT = Context->IntTy; QualType NSDictFType = getSimpleFunctionType(Context->VoidTy, IntQT, true); std::string NSDictFName("__NSContainer_literal"); FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName); DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr( *Context, NSDictFD, false, NSDictFType, VK_PRValue, SourceLocation()); SmallVector<Expr*, 16> KeyExprs; SmallVector<Expr*, 16> ValueExprs; unsigned NumElements = Exp->getNumElements(); unsigned UnsignedIntSize = static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); Expr *count = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, NumElements), Context->UnsignedIntTy, SourceLocation()); KeyExprs.push_back(count); ValueExprs.push_back(count); for (unsigned i = 0; i < NumElements; i++) { ObjCDictionaryElement Element = Exp->getKeyValueElement(i); KeyExprs.push_back(Element.Key); ValueExprs.push_back(Element.Value); } // (const id [])objects Expr *NSValueCallExpr = CallExpr::Create(*Context, NSDictDRE, ValueExprs, NSDictFType, VK_LValue, SourceLocation(), FPOptionsOverride()); FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get("arr"), Context->getPointerType(Context->VoidPtrTy), nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); MemberExpr *DictLiteralValueME = MemberExpr::CreateImplicit(*Context, NSValueCallExpr, false, ARRFD, ARRFD->getType(), VK_LValue, OK_Ordinary); QualType ConstIdT = Context->getObjCIdType().withConst(); CStyleCastExpr * DictValueObjects = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(ConstIdT), CK_BitCast, DictLiteralValueME); // (const id <NSCopying> [])keys Expr *NSKeyCallExpr = CallExpr::Create(*Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue, SourceLocation(), FPOptionsOverride()); MemberExpr *DictLiteralKeyME = MemberExpr::CreateImplicit(*Context, NSKeyCallExpr, false, ARRFD, ARRFD->getType(), VK_LValue, OK_Ordinary); CStyleCastExpr * DictKeyObjects = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(ConstIdT), CK_BitCast, DictLiteralKeyME); // Synthesize a call to objc_msgSend(). SmallVector<Expr*, 32> MsgExprs; SmallVector<Expr*, 4> ClsExprs; QualType expType = Exp->getType(); // Create a call to objc_getClass("NSArray"). It will be th 1st argument. ObjCInterfaceDecl *Class = expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface(); IdentifierInfo *clsName = Class->getIdentifier(); ClsExprs.push_back(getStringLiteral(clsName->getName())); CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs, StartLoc, EndLoc); MsgExprs.push_back(Cls); // Create a call to sel_registerName("arrayWithObjects:count:"). // it will be the 2nd argument. SmallVector<Expr*, 4> SelExprs; ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod(); SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString())); CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, SelExprs, StartLoc, EndLoc); MsgExprs.push_back(SelExp); // (const id [])objects MsgExprs.push_back(DictValueObjects); // (const id <NSCopying> [])keys MsgExprs.push_back(DictKeyObjects); // (NSUInteger)cnt Expr *cnt = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, NumElements), Context->UnsignedIntTy, SourceLocation()); MsgExprs.push_back(cnt); SmallVector<QualType, 8> ArgTypes; ArgTypes.push_back(Context->getObjCClassType()); ArgTypes.push_back(Context->getObjCSelType()); for (const auto *PI : DictMethod->parameters()) { QualType T = PI->getType(); if (const PointerType* PT = T->getAs<PointerType>()) { QualType PointeeTy = PT->getPointeeType(); convertToUnqualifiedObjCType(PointeeTy); T = Context->getPointerType(PointeeTy); } ArgTypes.push_back(T); } QualType returnType = Exp->getType(); // Get the type, we will need to reference it in a couple spots. QualType msgSendType = MsgSendFlavor->getType(); // Create a reference to the objc_msgSend() declaration. DeclRefExpr *DRE = new (Context) DeclRefExpr( *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); CastExpr *cast = NoTypeInfoCStyleCastExpr( Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE); // Now do the "normal" pointer to function cast. QualType castType = getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic()); castType = Context->getPointerType(castType); cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, cast); // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); const FunctionType *FT = msgSendType->castAs<FunctionType>(); CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), VK_PRValue, EndLoc, FPOptionsOverride()); ReplaceStmt(Exp, CE); return CE; } // struct __rw_objc_super { // struct objc_object *object; struct objc_object *superClass; // }; QualType RewriteModernObjC::getSuperStructType() { if (!SuperStructDecl) { SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get("__rw_objc_super")); QualType FieldTypes[2]; // struct objc_object *object; FieldTypes[0] = Context->getObjCIdType(); // struct objc_object *superClass; FieldTypes[1] = Context->getObjCIdType(); // Create fields for (unsigned i = 0; i < 2; ++i) { SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl, SourceLocation(), SourceLocation(), nullptr, FieldTypes[i], nullptr, /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit)); } SuperStructDecl->completeDefinition(); } return Context->getTagDeclType(SuperStructDecl); } QualType RewriteModernObjC::getConstantStringStructType() { if (!ConstantStringDecl) { ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get("__NSConstantStringImpl")); QualType FieldTypes[4]; // struct objc_object *receiver; FieldTypes[0] = Context->getObjCIdType(); // int flags; FieldTypes[1] = Context->IntTy; // char *str; FieldTypes[2] = Context->getPointerType(Context->CharTy); // long length; FieldTypes[3] = Context->LongTy; // Create fields for (unsigned i = 0; i < 4; ++i) { ConstantStringDecl->addDecl(FieldDecl::Create(*Context, ConstantStringDecl, SourceLocation(), SourceLocation(), nullptr, FieldTypes[i], nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit)); } ConstantStringDecl->completeDefinition(); } return Context->getTagDeclType(ConstantStringDecl); } /// getFunctionSourceLocation - returns start location of a function /// definition. Complication arises when function has declared as /// extern "C" or extern "C" {...} static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R, FunctionDecl *FD) { if (FD->isExternC() && !FD->isMain()) { const DeclContext *DC = FD->getDeclContext(); if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC)) // if it is extern "C" {...}, return function decl's own location. if (!LSD->getRBraceLoc().isValid()) return LSD->getExternLoc(); } if (FD->getStorageClass() != SC_None) R.RewriteBlockLiteralFunctionDecl(FD); return FD->getTypeSpecStartLoc(); } void RewriteModernObjC::RewriteLineDirective(const Decl *D) { SourceLocation Location = D->getLocation(); if (Location.isFileID() && GenerateLineInfo) { std::string LineString("\n#line "); PresumedLoc PLoc = SM->getPresumedLoc(Location); LineString += utostr(PLoc.getLine()); LineString += " \""; LineString += Lexer::Stringify(PLoc.getFilename()); if (isa<ObjCMethodDecl>(D)) LineString += "\""; else LineString += "\"\n"; Location = D->getBeginLoc(); if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { if (FD->isExternC() && !FD->isMain()) { const DeclContext *DC = FD->getDeclContext(); if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC)) // if it is extern "C" {...}, return function decl's own location. if (!LSD->getRBraceLoc().isValid()) Location = LSD->getExternLoc(); } } InsertText(Location, LineString); } } /// SynthMsgSendStretCallExpr - This routine translates message expression /// into a call to objc_msgSend_stret() entry point. Tricky part is that /// nil check on receiver must be performed before calling objc_msgSend_stret. /// MsgSendStretFlavor - function declaration objc_msgSend_stret(...) /// msgSendType - function type of objc_msgSend_stret(...) /// returnType - Result type of the method being synthesized. /// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type. /// MsgExprs - list of argument expressions being passed to objc_msgSend_stret, /// starting with receiver. /// Method - Method being rewritten. Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor, QualType returnType, SmallVectorImpl<QualType> &ArgTypes, SmallVectorImpl<Expr*> &MsgExprs, ObjCMethodDecl *Method) { // Now do the "normal" pointer to function cast. QualType FuncType = getSimpleFunctionType( returnType, ArgTypes, Method ? Method->isVariadic() : false); QualType castType = Context->getPointerType(FuncType); // build type for containing the objc_msgSend_stret object. static unsigned stretCount=0; std::string name = "__Stret"; name += utostr(stretCount); std::string str = "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n"; str += "namespace {\n"; str += "struct "; str += name; str += " {\n\t"; str += name; str += "(id receiver, SEL sel"; for (unsigned i = 2; i < ArgTypes.size(); i++) { std::string ArgName = "arg"; ArgName += utostr(i); ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy()); str += ", "; str += ArgName; } // could be vararg. for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) { std::string ArgName = "arg"; ArgName += utostr(i); MsgExprs[i]->getType().getAsStringInternal(ArgName, Context->getPrintingPolicy()); str += ", "; str += ArgName; } str += ") {\n"; str += "\t unsigned size = sizeof("; str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n"; str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n"; str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy()); str += ")(void *)objc_msgSend)(receiver, sel"; for (unsigned i = 2; i < ArgTypes.size(); i++) { str += ", arg"; str += utostr(i); } // could be vararg. for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) { str += ", arg"; str += utostr(i); } str+= ");\n"; str += "\t else if (receiver == 0)\n"; str += "\t memset((void*)&s, 0, sizeof(s));\n"; str += "\t else\n"; str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy()); str += ")(void *)objc_msgSend_stret)(receiver, sel"; for (unsigned i = 2; i < ArgTypes.size(); i++) { str += ", arg"; str += utostr(i); } // could be vararg. for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) { str += ", arg"; str += utostr(i); } str += ");\n"; str += "\t}\n"; str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy()); str += " s;\n"; str += "};\n};\n\n"; SourceLocation FunLocStart; if (CurFunctionDef) FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef); else { assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null"); FunLocStart = CurMethodDef->getBeginLoc(); } InsertText(FunLocStart, str); ++stretCount; // AST for __Stretn(receiver, args).s; IdentifierInfo *ID = &Context->Idents.get(name); FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), ID, FuncType, nullptr, SC_Extern, false, false); DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, castType, VK_PRValue, SourceLocation()); CallExpr *STCE = CallExpr::Create(*Context, DRE, MsgExprs, castType, VK_LValue, SourceLocation(), FPOptionsOverride()); FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get("s"), returnType, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); MemberExpr *ME = MemberExpr::CreateImplicit( *Context, STCE, false, FieldD, FieldD->getType(), VK_LValue, OK_Ordinary); return ME; } Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, SourceLocation StartLoc, SourceLocation EndLoc) { if (!SelGetUidFunctionDecl) SynthSelGetUidFunctionDecl(); if (!MsgSendFunctionDecl) SynthMsgSendFunctionDecl(); if (!MsgSendSuperFunctionDecl) SynthMsgSendSuperFunctionDecl(); if (!MsgSendStretFunctionDecl) SynthMsgSendStretFunctionDecl(); if (!MsgSendSuperStretFunctionDecl) SynthMsgSendSuperStretFunctionDecl(); if (!MsgSendFpretFunctionDecl) SynthMsgSendFpretFunctionDecl(); if (!GetClassFunctionDecl) SynthGetClassFunctionDecl(); if (!GetSuperClassFunctionDecl) SynthGetSuperClassFunctionDecl(); if (!GetMetaClassFunctionDecl) SynthGetMetaClassFunctionDecl(); // default to objc_msgSend(). FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; // May need to use objc_msgSend_stret() as well. FunctionDecl *MsgSendStretFlavor = nullptr; if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) { QualType resultType = mDecl->getReturnType(); if (resultType->isRecordType()) MsgSendStretFlavor = MsgSendStretFunctionDecl; else if (resultType->isRealFloatingType()) MsgSendFlavor = MsgSendFpretFunctionDecl; } // Synthesize a call to objc_msgSend(). SmallVector<Expr*, 8> MsgExprs; switch (Exp->getReceiverKind()) { case ObjCMessageExpr::SuperClass: { MsgSendFlavor = MsgSendSuperFunctionDecl; if (MsgSendStretFlavor) MsgSendStretFlavor = MsgSendSuperStretFunctionDecl; assert(MsgSendFlavor && "MsgSendFlavor is NULL!"); ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface(); SmallVector<Expr*, 4> InitExprs; // set the receiver to self, the first argument to all methods. InitExprs.push_back(NoTypeInfoCStyleCastExpr( Context, Context->getObjCIdType(), CK_BitCast, new (Context) DeclRefExpr(*Context, CurMethodDef->getSelfDecl(), false, Context->getObjCIdType(), VK_PRValue, SourceLocation()))); // set the 'receiver'. // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) SmallVector<Expr*, 8> ClsExprs; ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName())); // (Class)objc_getClass("CurrentClass") CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl, ClsExprs, StartLoc, EndLoc); ClsExprs.clear(); ClsExprs.push_back(Cls); Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs, StartLoc, EndLoc); // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) // To turn off a warning, type-cast to 'id' InitExprs.push_back( // set 'super class', using class_getSuperclass(). NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), CK_BitCast, Cls)); // struct __rw_objc_super QualType superType = getSuperStructType(); Expr *SuperRep; if (LangOpts.MicrosoftExt) { SynthSuperConstructorFunctionDecl(); // Simulate a constructor call... DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType, VK_LValue, SourceLocation()); SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue, SourceLocation(), FPOptionsOverride()); // The code for super is a little tricky to prevent collision with // the structure definition in the header. The rewriter has it's own // internal definition (__rw_objc_super) that is uses. This is why // we need the cast below. For example: // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER")) // SuperRep = UnaryOperator::Create( const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf, Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); SuperRep = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(superType), CK_BitCast, SuperRep); } else { // (struct __rw_objc_super) { <exprs from above> } InitListExpr *ILE = new (Context) InitListExpr(*Context, SourceLocation(), InitExprs, SourceLocation()); TypeSourceInfo *superTInfo = Context->getTrivialTypeSourceInfo(superType); SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo, superType, VK_LValue, ILE, false); // struct __rw_objc_super * SuperRep = UnaryOperator::Create( const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf, Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); } MsgExprs.push_back(SuperRep); break; } case ObjCMessageExpr::Class: { SmallVector<Expr*, 8> ClsExprs; ObjCInterfaceDecl *Class = Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface(); IdentifierInfo *clsName = Class->getIdentifier(); ClsExprs.push_back(getStringLiteral(clsName->getName())); CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs, StartLoc, EndLoc); CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), CK_BitCast, Cls); MsgExprs.push_back(ArgExpr); break; } case ObjCMessageExpr::SuperInstance:{ MsgSendFlavor = MsgSendSuperFunctionDecl; if (MsgSendStretFlavor) MsgSendStretFlavor = MsgSendSuperStretFunctionDecl; assert(MsgSendFlavor && "MsgSendFlavor is NULL!"); ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface(); SmallVector<Expr*, 4> InitExprs; InitExprs.push_back(NoTypeInfoCStyleCastExpr( Context, Context->getObjCIdType(), CK_BitCast, new (Context) DeclRefExpr(*Context, CurMethodDef->getSelfDecl(), false, Context->getObjCIdType(), VK_PRValue, SourceLocation()))); // set the 'receiver'. // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) SmallVector<Expr*, 8> ClsExprs; ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName())); // (Class)objc_getClass("CurrentClass") CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs, StartLoc, EndLoc); ClsExprs.clear(); ClsExprs.push_back(Cls); Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs, StartLoc, EndLoc); // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) // To turn off a warning, type-cast to 'id' InitExprs.push_back( // set 'super class', using class_getSuperclass(). NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), CK_BitCast, Cls)); // struct __rw_objc_super QualType superType = getSuperStructType(); Expr *SuperRep; if (LangOpts.MicrosoftExt) { SynthSuperConstructorFunctionDecl(); // Simulate a constructor call... DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType, VK_LValue, SourceLocation()); SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue, SourceLocation(), FPOptionsOverride()); // The code for super is a little tricky to prevent collision with // the structure definition in the header. The rewriter has it's own // internal definition (__rw_objc_super) that is uses. This is why // we need the cast below. For example: // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER")) // SuperRep = UnaryOperator::Create( const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf, Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); SuperRep = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(superType), CK_BitCast, SuperRep); } else { // (struct __rw_objc_super) { <exprs from above> } InitListExpr *ILE = new (Context) InitListExpr(*Context, SourceLocation(), InitExprs, SourceLocation()); TypeSourceInfo *superTInfo = Context->getTrivialTypeSourceInfo(superType); SuperRep = new (Context) CompoundLiteralExpr( SourceLocation(), superTInfo, superType, VK_PRValue, ILE, false); } MsgExprs.push_back(SuperRep); break; } case ObjCMessageExpr::Instance: { // Remove all type-casts because it may contain objc-style types; e.g. // Foo<Proto> *. Expr *recExpr = Exp->getInstanceReceiver(); while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr)) recExpr = CE->getSubExpr(); CastKind CK = recExpr->getType()->isObjCObjectPointerType() ? CK_BitCast : recExpr->getType()->isBlockPointerType() ? CK_BlockPointerToObjCPointerCast : CK_CPointerToObjCPointerCast; recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), CK, recExpr); MsgExprs.push_back(recExpr); break; } } // Create a call to sel_registerName("selName"), it will be the 2nd argument. SmallVector<Expr*, 8> SelExprs; SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString())); CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, SelExprs, StartLoc, EndLoc); MsgExprs.push_back(SelExp); // Now push any user supplied arguments. for (unsigned i = 0; i < Exp->getNumArgs(); i++) { Expr *userExpr = Exp->getArg(i); // Make all implicit casts explicit...ICE comes in handy:-) if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) { // Reuse the ICE type, it is exactly what the doctor ordered. QualType type = ICE->getType(); if (needToScanForQualifiers(type)) type = Context->getObjCIdType(); // Make sure we convert "type (^)(...)" to "type (*)(...)". (void)convertBlockPointerToFunctionPointer(type); const Expr *SubExpr = ICE->IgnoreParenImpCasts(); CastKind CK; if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType()) { CK = CK_IntegralToBoolean; } else if (type->isObjCObjectPointerType()) { if (SubExpr->getType()->isBlockPointerType()) { CK = CK_BlockPointerToObjCPointerCast; } else if (SubExpr->getType()->isPointerType()) { CK = CK_CPointerToObjCPointerCast; } else { CK = CK_BitCast; } } else { CK = CK_BitCast; } userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr); } // Make id<P...> cast into an 'id' cast. else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) { if (CE->getType()->isObjCQualifiedIdType()) { while ((CE = dyn_cast<CStyleCastExpr>(userExpr))) userExpr = CE->getSubExpr(); CastKind CK; if (userExpr->getType()->isIntegralType(*Context)) { CK = CK_IntegralToPointer; } else if (userExpr->getType()->isBlockPointerType()) { CK = CK_BlockPointerToObjCPointerCast; } else if (userExpr->getType()->isPointerType()) { CK = CK_CPointerToObjCPointerCast; } else { CK = CK_BitCast; } userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), CK, userExpr); } } MsgExprs.push_back(userExpr); // We've transferred the ownership to MsgExprs. For now, we *don't* null // out the argument in the original expression (since we aren't deleting // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info. //Exp->setArg(i, 0); } // Generate the funky cast. CastExpr *cast; SmallVector<QualType, 8> ArgTypes; QualType returnType; // Push 'id' and 'SEL', the 2 implicit arguments. if (MsgSendFlavor == MsgSendSuperFunctionDecl) ArgTypes.push_back(Context->getPointerType(getSuperStructType())); else ArgTypes.push_back(Context->getObjCIdType()); ArgTypes.push_back(Context->getObjCSelType()); if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) { // Push any user argument types. for (const auto *PI : OMD->parameters()) { QualType t = PI->getType()->isObjCQualifiedIdType() ? Context->getObjCIdType() : PI->getType(); // Make sure we convert "t (^)(...)" to "t (*)(...)". (void)convertBlockPointerToFunctionPointer(t); ArgTypes.push_back(t); } returnType = Exp->getType(); convertToUnqualifiedObjCType(returnType); (void)convertBlockPointerToFunctionPointer(returnType); } else { returnType = Context->getObjCIdType(); } // Get the type, we will need to reference it in a couple spots. QualType msgSendType = MsgSendFlavor->getType(); // Create a reference to the objc_msgSend() declaration. DeclRefExpr *DRE = new (Context) DeclRefExpr( *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid). // If we don't do this cast, we get the following bizarre warning/note: // xx.m:13: warning: function called through a non-compatible type // xx.m:13: note: if this code is reached, the program will abort cast = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE); // Now do the "normal" pointer to function cast. // If we don't have a method decl, force a variadic cast. const ObjCMethodDecl *MD = Exp->getMethodDecl(); QualType castType = getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true); castType = Context->getPointerType(castType); cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, cast); // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); const FunctionType *FT = msgSendType->castAs<FunctionType>(); CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), VK_PRValue, EndLoc, FPOptionsOverride()); Stmt *ReplacingStmt = CE; if (MsgSendStretFlavor) { // We have the method which returns a struct/union. Must also generate // call to objc_msgSend_stret and hang both varieties on a conditional // expression which dictate which one to envoke depending on size of // method's return type. Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor, returnType, ArgTypes, MsgExprs, Exp->getMethodDecl()); ReplacingStmt = STCE; } // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. return ReplacingStmt; } Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) { Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc()); // Now do the actual rewrite. ReplaceStmt(Exp, ReplacingStmt); // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. return ReplacingStmt; } // typedef struct objc_object Protocol; QualType RewriteModernObjC::getProtocolType() { if (!ProtocolTypeDecl) { TypeSourceInfo *TInfo = Context->getTrivialTypeSourceInfo(Context->getObjCIdType()); ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get("Protocol"), TInfo); } return Context->getTypeDeclType(ProtocolTypeDecl); } /// RewriteObjCProtocolExpr - Rewrite a protocol expression into /// a synthesized/forward data reference (to the protocol's metadata). /// The forward references (and metadata) are generated in /// RewriteModernObjC::HandleTranslationUnit(). Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) { std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" + Exp->getProtocol()->getNameAsString(); IdentifierInfo *ID = &Context->Idents.get(Name); VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), ID, getProtocolType(), nullptr, SC_Extern); DeclRefExpr *DRE = new (Context) DeclRefExpr( *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation()); CastExpr *castExpr = NoTypeInfoCStyleCastExpr( Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE); ReplaceStmt(Exp, castExpr); ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl()); // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. return castExpr; } /// IsTagDefinedInsideClass - This routine checks that a named tagged type /// is defined inside an objective-c class. If so, it returns true. bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag, bool &IsNamedDefinition) { if (!IDecl) return false; SourceLocation TagLocation; if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) { RD = RD->getDefinition(); if (!RD || !RD->getDeclName().getAsIdentifierInfo()) return false; IsNamedDefinition = true; TagLocation = RD->getLocation(); return Context->getSourceManager().isBeforeInTranslationUnit( IDecl->getLocation(), TagLocation); } if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) { if (!ED || !ED->getDeclName().getAsIdentifierInfo()) return false; IsNamedDefinition = true; TagLocation = ED->getLocation(); return Context->getSourceManager().isBeforeInTranslationUnit( IDecl->getLocation(), TagLocation); } return false; } /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer. /// It handles elaborated types, as well as enum types in the process. bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, std::string &Result) { if (isa<TypedefType>(Type)) { Result += "\t"; return false; } if (Type->isArrayType()) { QualType ElemTy = Context->getBaseElementType(Type); return RewriteObjCFieldDeclType(ElemTy, Result); } else if (Type->isRecordType()) { RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); if (RD->isCompleteDefinition()) { if (RD->isStruct()) Result += "\n\tstruct "; else if (RD->isUnion()) Result += "\n\tunion "; else assert(false && "class not allowed as an ivar type"); Result += RD->getName(); if (GlobalDefinedTags.count(RD)) { // struct/union is defined globally, use it. Result += " "; return true; } Result += " {\n"; for (auto *FD : RD->fields()) RewriteObjCFieldDecl(FD, Result); Result += "\t} "; return true; } } else if (Type->isEnumeralType()) { EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); if (ED->isCompleteDefinition()) { Result += "\n\tenum "; Result += ED->getName(); if (GlobalDefinedTags.count(ED)) { // Enum is globall defined, use it. Result += " "; return true; } Result += " {\n"; for (const auto *EC : ED->enumerators()) { Result += "\t"; Result += EC->getName(); Result += " = "; Result += toString(EC->getInitVal(), 10); Result += ",\n"; } Result += "\t} "; return true; } } Result += "\t"; convertObjCTypeToCStyleType(Type); return false; } /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer. /// It handles elaborated types, as well as enum types in the process. void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result) { QualType Type = fieldDecl->getType(); std::string Name = fieldDecl->getNameAsString(); bool EleboratedType = RewriteObjCFieldDeclType(Type, Result); if (!EleboratedType) Type.getAsStringInternal(Name, Context->getPrintingPolicy()); Result += Name; if (fieldDecl->isBitField()) { Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context)); } else if (EleboratedType && Type->isArrayType()) { const ArrayType *AT = Context->getAsArrayType(Type); do { if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { Result += "["; llvm::APInt Dim = CAT->getSize(); Result += utostr(Dim.getZExtValue()); Result += "]"; } AT = Context->getAsArrayType(AT->getElementType()); } while (AT); } Result += ";\n"; } /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined /// named aggregate types into the input buffer. void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, std::string &Result) { QualType Type = fieldDecl->getType(); if (isa<TypedefType>(Type)) return; if (Type->isArrayType()) Type = Context->getBaseElementType(Type); auto *IDecl = dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext()); TagDecl *TD = nullptr; if (Type->isRecordType()) { TD = Type->castAs<RecordType>()->getDecl(); } else if (Type->isEnumeralType()) { TD = Type->castAs<EnumType>()->getDecl(); } if (TD) { if (GlobalDefinedTags.count(TD)) return; bool IsNamedDefinition = false; if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) { RewriteObjCFieldDeclType(Type, Result); Result += ";"; } if (IsNamedDefinition) GlobalDefinedTags.insert(TD); } } unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) { const ObjCInterfaceDecl *CDecl = IV->getContainingInterface(); if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) { return IvarGroupNumber[IV]; } unsigned GroupNo = 0; SmallVector<const ObjCIvarDecl *, 8> IVars; for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) IVars.push_back(IVD); for (unsigned i = 0, e = IVars.size(); i < e; i++) if (IVars[i]->isBitField()) { IvarGroupNumber[IVars[i++]] = ++GroupNo; while (i < e && IVars[i]->isBitField()) IvarGroupNumber[IVars[i++]] = GroupNo; if (i < e) --i; } ObjCInterefaceHasBitfieldGroups.insert(CDecl); return IvarGroupNumber[IV]; } QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType( ObjCIvarDecl *IV, SmallVectorImpl<ObjCIvarDecl *> &IVars) { std::string StructTagName; ObjCIvarBitfieldGroupType(IV, StructTagName); RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, Context->getTranslationUnitDecl(), SourceLocation(), SourceLocation(), &Context->Idents.get(StructTagName)); for (unsigned i=0, e = IVars.size(); i < e; i++) { ObjCIvarDecl *Ivar = IVars[i]; RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(), &Context->Idents.get(Ivar->getName()), Ivar->getType(), nullptr, /*Expr *BW */Ivar->getBitWidth(), false, ICIS_NoInit)); } RD->completeDefinition(); return Context->getTagDeclType(RD); } QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) { const ObjCInterfaceDecl *CDecl = IV->getContainingInterface(); unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV); std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo); if (GroupRecordType.count(tuple)) return GroupRecordType[tuple]; SmallVector<ObjCIvarDecl *, 8> IVars; for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) { if (IVD->isBitField()) IVars.push_back(const_cast<ObjCIvarDecl *>(IVD)); else { if (!IVars.empty()) { unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]); // Generate the struct type for this group of bitfield ivars. GroupRecordType[std::make_pair(CDecl, GroupNo)] = SynthesizeBitfieldGroupStructType(IVars[0], IVars); IVars.clear(); } } } if (!IVars.empty()) { // Do the last one. unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]); GroupRecordType[std::make_pair(CDecl, GroupNo)] = SynthesizeBitfieldGroupStructType(IVars[0], IVars); } QualType RetQT = GroupRecordType[tuple]; assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL"); return RetQT; } /// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group. /// Name would be: classname__GRBF_n where n is the group number for this ivar. void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result) { const ObjCInterfaceDecl *CDecl = IV->getContainingInterface(); Result += CDecl->getName(); Result += "__GRBF_"; unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV); Result += utostr(GroupNo); } /// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group. /// Name of the struct would be: classname__T_n where n is the group number for /// this ivar. void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result) { const ObjCInterfaceDecl *CDecl = IV->getContainingInterface(); Result += CDecl->getName(); Result += "__T_"; unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV); Result += utostr(GroupNo); } /// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset. /// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for /// this ivar. void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result) { Result += "OBJC_IVAR_$_"; ObjCIvarBitfieldGroupDecl(IV, Result); } #define SKIP_BITFIELDS(IX, ENDIX, VEC) { \ while ((IX < ENDIX) && VEC[IX]->isBitField()) \ ++IX; \ if (IX < ENDIX) \ --IX; \ } /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to /// an objective-c class with ivars. void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, std::string &Result) { assert(CDecl && "Class missing in SynthesizeObjCInternalStruct"); assert(CDecl->getName() != "" && "Name missing in SynthesizeObjCInternalStruct"); ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass(); SmallVector<ObjCIvarDecl *, 8> IVars; for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) IVars.push_back(IVD); SourceLocation LocStart = CDecl->getBeginLoc(); SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc(); const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); // If no ivars and no root or if its root, directly or indirectly, // have no ivars (thus not synthesized) then no need to synthesize this class. if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) { endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts); ReplaceText(LocStart, endBuf-startBuf, Result); return; } // Insert named struct/union definitions inside class to // outer scope. This follows semantics of locally defined // struct/unions in objective-c classes. for (unsigned i = 0, e = IVars.size(); i < e; i++) RewriteLocallyDefinedNamedAggregates(IVars[i], Result); // Insert named structs which are syntheized to group ivar bitfields // to outer scope as well. for (unsigned i = 0, e = IVars.size(); i < e; i++) if (IVars[i]->isBitField()) { ObjCIvarDecl *IV = IVars[i]; QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV); RewriteObjCFieldDeclType(QT, Result); Result += ";"; // skip over ivar bitfields in this group. SKIP_BITFIELDS(i , e, IVars); } Result += "\nstruct "; Result += CDecl->getNameAsString(); Result += "_IMPL {\n"; if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) { Result += "\tstruct "; Result += RCDecl->getNameAsString(); Result += "_IMPL "; Result += RCDecl->getNameAsString(); Result += "_IVARS;\n"; } for (unsigned i = 0, e = IVars.size(); i < e; i++) { if (IVars[i]->isBitField()) { ObjCIvarDecl *IV = IVars[i]; Result += "\tstruct "; ObjCIvarBitfieldGroupType(IV, Result); Result += " "; ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n"; // skip over ivar bitfields in this group. SKIP_BITFIELDS(i , e, IVars); } else RewriteObjCFieldDecl(IVars[i], Result); } Result += "};\n"; endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts); ReplaceText(LocStart, endBuf-startBuf, Result); // Mark this struct as having been generated. if (!ObjCSynthesizedStructs.insert(CDecl).second) llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct"); } /// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which /// have been referenced in an ivar access expression. void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl, std::string &Result) { // write out ivar offset symbols which have been referenced in an ivar // access expression. llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl]; if (Ivars.empty()) return; llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput; for (ObjCIvarDecl *IvarDecl : Ivars) { const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface(); unsigned GroupNo = 0; if (IvarDecl->isBitField()) { GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl); if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo))) continue; } Result += "\n"; if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_ivar$B\")) "; Result += "extern \"C\" "; if (LangOpts.MicrosoftExt && IvarDecl->getAccessControl() != ObjCIvarDecl::Private && IvarDecl->getAccessControl() != ObjCIvarDecl::Package) Result += "__declspec(dllimport) "; Result += "unsigned long "; if (IvarDecl->isBitField()) { ObjCIvarBitfieldGroupOffset(IvarDecl, Result); GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo)); } else WriteInternalIvarName(CDecl, IvarDecl, Result); Result += ";"; } } //===----------------------------------------------------------------------===// // Meta Data Emission //===----------------------------------------------------------------------===// /// RewriteImplementations - This routine rewrites all method implementations /// and emits meta-data. void RewriteModernObjC::RewriteImplementations() { int ClsDefCount = ClassImplementation.size(); int CatDefCount = CategoryImplementation.size(); // Rewrite implemented methods for (int i = 0; i < ClsDefCount; i++) { ObjCImplementationDecl *OIMP = ClassImplementation[i]; ObjCInterfaceDecl *CDecl = OIMP->getClassInterface(); if (CDecl->isImplicitInterfaceDecl()) assert(false && "Legacy implicit interface rewriting not supported in moder abi"); RewriteImplementationDecl(OIMP); } for (int i = 0; i < CatDefCount; i++) { ObjCCategoryImplDecl *CIMP = CategoryImplementation[i]; ObjCInterfaceDecl *CDecl = CIMP->getClassInterface(); if (CDecl->isImplicitInterfaceDecl()) assert(false && "Legacy implicit interface rewriting not supported in moder abi"); RewriteImplementationDecl(CIMP); } } void RewriteModernObjC::RewriteByRefString(std::string &ResultStr, const std::string &Name, ValueDecl *VD, bool def) { assert(BlockByRefDeclNo.count(VD) && "RewriteByRefString: ByRef decl missing"); if (def) ResultStr += "struct "; ResultStr += "__Block_byref_" + Name + "_" + utostr(BlockByRefDeclNo[VD]) ; } static bool HasLocalVariableExternalStorage(ValueDecl *VD) { if (VarDecl *Var = dyn_cast<VarDecl>(VD)) return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage()); return false; } std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i, StringRef funcName, std::string Tag) { const FunctionType *AFT = CE->getFunctionType(); QualType RT = AFT->getReturnType(); std::string StructRef = "struct " + Tag; SourceLocation BlockLoc = CE->getExprLoc(); std::string S; ConvertSourceLocationToLineDirective(BlockLoc, S); S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" + funcName.str() + "_block_func_" + utostr(i); BlockDecl *BD = CE->getBlockDecl(); if (isa<FunctionNoProtoType>(AFT)) { // No user-supplied arguments. Still need to pass in a pointer to the // block (to reference imported block decl refs). S += "(" + StructRef + " *__cself)"; } else if (BD->param_empty()) { S += "(" + StructRef + " *__cself)"; } else { const FunctionProtoType *FT = cast<FunctionProtoType>(AFT); assert(FT && "SynthesizeBlockFunc: No function proto"); S += '('; // first add the implicit argument. S += StructRef + " *__cself, "; std::string ParamStr; for (BlockDecl::param_iterator AI = BD->param_begin(), E = BD->param_end(); AI != E; ++AI) { if (AI != BD->param_begin()) S += ", "; ParamStr = (*AI)->getNameAsString(); QualType QT = (*AI)->getType(); (void)convertBlockPointerToFunctionPointer(QT); QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy()); S += ParamStr; } if (FT->isVariadic()) { if (!BD->param_empty()) S += ", "; S += "..."; } S += ')'; } S += " {\n"; // Create local declarations to avoid rewriting all closure decl ref exprs. // First, emit a declaration for all "by ref" decls. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { S += " "; std::string Name = (*I)->getNameAsString(); std::string TypeString; RewriteByRefString(TypeString, Name, (*I)); TypeString += " *"; Name = TypeString + Name; S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n"; } // Next, emit a declaration for all "by copy" declarations. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { S += " "; // Handle nested closure invocation. For example: // // void (^myImportedClosure)(void); // myImportedClosure = ^(void) { setGlobalInt(x + y); }; // // void (^anotherClosure)(void); // anotherClosure = ^(void) { // myImportedClosure(); // import and invoke the closure // }; // if (isTopLevelBlockPointerType((*I)->getType())) { RewriteBlockPointerTypeVariable(S, (*I)); S += " = ("; RewriteBlockPointerType(S, (*I)->getType()); S += ")"; S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n"; } else { std::string Name = (*I)->getNameAsString(); QualType QT = (*I)->getType(); if (HasLocalVariableExternalStorage(*I)) QT = Context->getPointerType(QT); QT.getAsStringInternal(Name, Context->getPrintingPolicy()); S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n"; } } std::string RewrittenStr = RewrittenBlockExprs[CE]; const char *cstr = RewrittenStr.c_str(); while (*cstr++ != '{') ; S += cstr; S += "\n"; return S; } std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, StringRef funcName, std::string Tag) { std::string StructRef = "struct " + Tag; std::string S = "static void __"; S += funcName; S += "_block_copy_" + utostr(i); S += "(" + StructRef; S += "*dst, " + StructRef; S += "*src) {"; for (ValueDecl *VD : ImportedBlockDecls) { S += "_Block_object_assign((void*)&dst->"; S += VD->getNameAsString(); S += ", (void*)src->"; S += VD->getNameAsString(); if (BlockByRefDeclsPtrSet.count(VD)) S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);"; else if (VD->getType()->isBlockPointerType()) S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);"; else S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);"; } S += "}\n"; S += "\nstatic void __"; S += funcName; S += "_block_dispose_" + utostr(i); S += "(" + StructRef; S += "*src) {"; for (ValueDecl *VD : ImportedBlockDecls) { S += "_Block_object_dispose((void*)src->"; S += VD->getNameAsString(); if (BlockByRefDeclsPtrSet.count(VD)) S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);"; else if (VD->getType()->isBlockPointerType()) S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);"; else S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);"; } S += "}\n"; return S; } std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, std::string Desc) { std::string S = "\nstruct " + Tag; std::string Constructor = " " + Tag; S += " {\n struct __block_impl impl;\n"; S += " struct " + Desc; S += "* Desc;\n"; Constructor += "(void *fp, "; // Invoke function pointer. Constructor += "struct " + Desc; // Descriptor pointer. Constructor += " *desc"; if (BlockDeclRefs.size()) { // Output all "by copy" declarations. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { S += " "; std::string FieldName = (*I)->getNameAsString(); std::string ArgName = "_" + FieldName; // Handle nested closure invocation. For example: // // void (^myImportedBlock)(void); // myImportedBlock = ^(void) { setGlobalInt(x + y); }; // // void (^anotherBlock)(void); // anotherBlock = ^(void) { // myImportedBlock(); // import and invoke the closure // }; // if (isTopLevelBlockPointerType((*I)->getType())) { S += "struct __block_impl *"; Constructor += ", void *" + ArgName; } else { QualType QT = (*I)->getType(); if (HasLocalVariableExternalStorage(*I)) QT = Context->getPointerType(QT); QT.getAsStringInternal(FieldName, Context->getPrintingPolicy()); QT.getAsStringInternal(ArgName, Context->getPrintingPolicy()); Constructor += ", " + ArgName; } S += FieldName + ";\n"; } // Output all "by ref" declarations. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { S += " "; std::string FieldName = (*I)->getNameAsString(); std::string ArgName = "_" + FieldName; { std::string TypeString; RewriteByRefString(TypeString, FieldName, (*I)); TypeString += " *"; FieldName = TypeString + FieldName; ArgName = TypeString + ArgName; Constructor += ", " + ArgName; } S += FieldName + "; // by ref\n"; } // Finish writing the constructor. Constructor += ", int flags=0)"; // Initialize all "by copy" arguments. bool firsTime = true; for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { std::string Name = (*I)->getNameAsString(); if (firsTime) { Constructor += " : "; firsTime = false; } else Constructor += ", "; if (isTopLevelBlockPointerType((*I)->getType())) Constructor += Name + "((struct __block_impl *)_" + Name + ")"; else Constructor += Name + "(_" + Name + ")"; } // Initialize all "by ref" arguments. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { std::string Name = (*I)->getNameAsString(); if (firsTime) { Constructor += " : "; firsTime = false; } else Constructor += ", "; Constructor += Name + "(_" + Name + "->__forwarding)"; } Constructor += " {\n"; if (GlobalVarDecl) Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n"; else Constructor += " impl.isa = &_NSConcreteStackBlock;\n"; Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n"; Constructor += " Desc = desc;\n"; } else { // Finish writing the constructor. Constructor += ", int flags=0) {\n"; if (GlobalVarDecl) Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n"; else Constructor += " impl.isa = &_NSConcreteStackBlock;\n"; Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n"; Constructor += " Desc = desc;\n"; } Constructor += " "; Constructor += "}\n"; S += Constructor; S += "};\n"; return S; } std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag, std::string ImplTag, int i, StringRef FunName, unsigned hasCopy) { std::string S = "\nstatic struct " + DescTag; S += " {\n size_t reserved;\n"; S += " size_t Block_size;\n"; if (hasCopy) { S += " void (*copy)(struct "; S += ImplTag; S += "*, struct "; S += ImplTag; S += "*);\n"; S += " void (*dispose)(struct "; S += ImplTag; S += "*);\n"; } S += "} "; S += DescTag + "_DATA = { 0, sizeof(struct "; S += ImplTag + ")"; if (hasCopy) { S += ", __" + FunName.str() + "_block_copy_" + utostr(i); S += ", __" + FunName.str() + "_block_dispose_" + utostr(i); } S += "};\n"; return S; } void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, StringRef FunName) { bool RewriteSC = (GlobalVarDecl && !Blocks.empty() && GlobalVarDecl->getStorageClass() == SC_Static && GlobalVarDecl->getType().getCVRQualifiers()); if (RewriteSC) { std::string SC(" void __"); SC += GlobalVarDecl->getNameAsString(); SC += "() {}"; InsertText(FunLocStart, SC); } // Insert closures that were part of the function. for (unsigned i = 0, count=0; i < Blocks.size(); i++) { CollectBlockDeclRefInfo(Blocks[i]); // Need to copy-in the inner copied-in variables not actually used in this // block. for (int j = 0; j < InnerDeclRefsCount[i]; j++) { DeclRefExpr *Exp = InnerDeclRefs[count++]; ValueDecl *VD = Exp->getDecl(); BlockDeclRefs.push_back(Exp); if (!VD->hasAttr<BlocksAttr>()) { if (!BlockByCopyDeclsPtrSet.count(VD)) { BlockByCopyDeclsPtrSet.insert(VD); BlockByCopyDecls.push_back(VD); } continue; } if (!BlockByRefDeclsPtrSet.count(VD)) { BlockByRefDeclsPtrSet.insert(VD); BlockByRefDecls.push_back(VD); } // imported objects in the inner blocks not used in the outer // blocks must be copied/disposed in the outer block as well. if (VD->getType()->isObjCObjectPointerType() || VD->getType()->isBlockPointerType()) ImportedBlockDecls.insert(VD); } std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i); std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i); std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag); InsertText(FunLocStart, CI); std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag); InsertText(FunLocStart, CF); if (ImportedBlockDecls.size()) { std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag); InsertText(FunLocStart, HF); } std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName, ImportedBlockDecls.size() > 0); InsertText(FunLocStart, BD); BlockDeclRefs.clear(); BlockByRefDecls.clear(); BlockByRefDeclsPtrSet.clear(); BlockByCopyDecls.clear(); BlockByCopyDeclsPtrSet.clear(); ImportedBlockDecls.clear(); } if (RewriteSC) { // Must insert any 'const/volatile/static here. Since it has been // removed as result of rewriting of block literals. std::string SC; if (GlobalVarDecl->getStorageClass() == SC_Static) SC = "static "; if (GlobalVarDecl->getType().isConstQualified()) SC += "const "; if (GlobalVarDecl->getType().isVolatileQualified()) SC += "volatile "; if (GlobalVarDecl->getType().isRestrictQualified()) SC += "restrict "; InsertText(FunLocStart, SC); } if (GlobalConstructionExp) { // extra fancy dance for global literal expression. // Always the latest block expression on the block stack. std::string Tag = "__"; Tag += FunName; Tag += "_block_impl_"; Tag += utostr(Blocks.size()-1); std::string globalBuf = "static "; globalBuf += Tag; globalBuf += " "; std::string SStr; llvm::raw_string_ostream constructorExprBuf(SStr); GlobalConstructionExp->printPretty(constructorExprBuf, nullptr, PrintingPolicy(LangOpts)); globalBuf += constructorExprBuf.str(); globalBuf += ";\n"; InsertText(FunLocStart, globalBuf); GlobalConstructionExp = nullptr; } Blocks.clear(); InnerDeclRefsCount.clear(); InnerDeclRefs.clear(); RewrittenBlockExprs.clear(); } void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) { SourceLocation FunLocStart = (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD) : FD->getTypeSpecStartLoc(); StringRef FuncName = FD->getName(); SynthesizeBlockLiterals(FunLocStart, FuncName); } static void BuildUniqueMethodName(std::string &Name, ObjCMethodDecl *MD) { ObjCInterfaceDecl *IFace = MD->getClassInterface(); Name = std::string(IFace->getName()); Name += "__" + MD->getSelector().getAsString(); // Convert colons to underscores. std::string::size_type loc = 0; while ((loc = Name.find(':', loc)) != std::string::npos) Name.replace(loc, 1, "_"); } void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) { // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n"); // SourceLocation FunLocStart = MD->getBeginLoc(); SourceLocation FunLocStart = MD->getBeginLoc(); std::string FuncName; BuildUniqueMethodName(FuncName, MD); SynthesizeBlockLiterals(FunLocStart, FuncName); } void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) { for (Stmt *SubStmt : S->children()) if (SubStmt) { if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) GetBlockDeclRefExprs(CBE->getBody()); else GetBlockDeclRefExprs(SubStmt); } // Handle specific things. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) if (DRE->refersToEnclosingVariableOrCapture() || HasLocalVariableExternalStorage(DRE->getDecl())) // FIXME: Handle enums. BlockDeclRefs.push_back(DRE); } void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S, SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs, llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) { for (Stmt *SubStmt : S->children()) if (SubStmt) { if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) { InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl())); GetInnerBlockDeclRefExprs(CBE->getBody(), InnerBlockDeclRefs, InnerContexts); } else GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts); } // Handle specific things. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) { if (DRE->refersToEnclosingVariableOrCapture() || HasLocalVariableExternalStorage(DRE->getDecl())) { if (!InnerContexts.count(DRE->getDecl()->getDeclContext())) InnerBlockDeclRefs.push_back(DRE); if (VarDecl *Var = cast<VarDecl>(DRE->getDecl())) if (Var->isFunctionOrMethodVarDecl()) ImportedLocalExternalDecls.insert(Var); } } } /// convertObjCTypeToCStyleType - This routine converts such objc types /// as qualified objects, and blocks to their closest c/c++ types that /// it can. It returns true if input type was modified. bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) { QualType oldT = T; convertBlockPointerToFunctionPointer(T); if (T->isFunctionPointerType()) { QualType PointeeTy; if (const PointerType* PT = T->getAs<PointerType>()) { PointeeTy = PT->getPointeeType(); if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) { T = convertFunctionTypeOfBlocks(FT); T = Context->getPointerType(T); } } } convertToUnqualifiedObjCType(T); return T != oldT; } /// convertFunctionTypeOfBlocks - This routine converts a function type /// whose result type may be a block pointer or whose argument type(s) /// might be block pointers to an equivalent function type replacing /// all block pointers to function pointers. QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) { const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT); // FTP will be null for closures that don't take arguments. // Generate a funky cast. SmallVector<QualType, 8> ArgTypes; QualType Res = FT->getReturnType(); bool modified = convertObjCTypeToCStyleType(Res); if (FTP) { for (auto &I : FTP->param_types()) { QualType t = I; // Make sure we convert "t (^)(...)" to "t (*)(...)". if (convertObjCTypeToCStyleType(t)) modified = true; ArgTypes.push_back(t); } } QualType FuncType; if (modified) FuncType = getSimpleFunctionType(Res, ArgTypes); else FuncType = QualType(FT, 0); return FuncType; } Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) { // Navigate to relevant type information. const BlockPointerType *CPT = nullptr; if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) { CPT = DRE->getType()->getAs<BlockPointerType>(); } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) { CPT = MExpr->getType()->getAs<BlockPointerType>(); } else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) { return SynthesizeBlockCall(Exp, PRE->getSubExpr()); } else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp)) CPT = IEXPR->getType()->getAs<BlockPointerType>(); else if (const ConditionalOperator *CEXPR = dyn_cast<ConditionalOperator>(BlockExp)) { Expr *LHSExp = CEXPR->getLHS(); Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp); Expr *RHSExp = CEXPR->getRHS(); Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp); Expr *CONDExp = CEXPR->getCond(); ConditionalOperator *CondExpr = new (Context) ConditionalOperator( CONDExp, SourceLocation(), cast<Expr>(LHSStmt), SourceLocation(), cast<Expr>(RHSStmt), Exp->getType(), VK_PRValue, OK_Ordinary); return CondExpr; } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) { CPT = IRE->getType()->getAs<BlockPointerType>(); } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BlockExp)) { CPT = POE->getType()->castAs<BlockPointerType>(); } else { assert(false && "RewriteBlockClass: Bad type"); } assert(CPT && "RewriteBlockClass: Bad type"); const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>(); assert(FT && "RewriteBlockClass: Bad type"); const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT); // FTP will be null for closures that don't take arguments. RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get("__block_impl")); QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD)); // Generate a funky cast. SmallVector<QualType, 8> ArgTypes; // Push the block argument type. ArgTypes.push_back(PtrBlock); if (FTP) { for (auto &I : FTP->param_types()) { QualType t = I; // Make sure we convert "t (^)(...)" to "t (*)(...)". if (!convertBlockPointerToFunctionPointer(t)) convertToUnqualifiedObjCType(t); ArgTypes.push_back(t); } } // Now do the pointer to function cast. QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes); PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType); CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock, CK_BitCast, const_cast<Expr*>(BlockExp)); // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), BlkCast); //PE->dump(); FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); MemberExpr *ME = MemberExpr::CreateImplicit( *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary); CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType, CK_BitCast, ME); PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast); SmallVector<Expr*, 8> BlkExprs; // Add the implicit argument. BlkExprs.push_back(BlkCast); // Add the user arguments. for (CallExpr::arg_iterator I = Exp->arg_begin(), E = Exp->arg_end(); I != E; ++I) { BlkExprs.push_back(*I); } CallExpr *CE = CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(), VK_PRValue, SourceLocation(), FPOptionsOverride()); return CE; } // We need to return the rewritten expression to handle cases where the // DeclRefExpr is embedded in another expression being rewritten. // For example: // // int main() { // __block Foo *f; // __block int i; // // void (^myblock)() = ^() { // [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten). // i = 77; // }; //} Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR // for each DeclRefExp where BYREFVAR is name of the variable. ValueDecl *VD = DeclRefExp->getDecl(); bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() || HasLocalVariableExternalStorage(DeclRefExp->getDecl()); FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get("__forwarding"), Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); MemberExpr *ME = MemberExpr::CreateImplicit( *Context, DeclRefExp, isArrow, FD, FD->getType(), VK_LValue, OK_Ordinary); StringRef Name = VD->getName(); FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get(Name), Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(), VK_LValue, OK_Ordinary); // Need parens to enforce precedence. ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), DeclRefExp->getExprLoc(), ME); ReplaceStmt(DeclRefExp, PE); return PE; } // Rewrites the imported local variable V with external storage // (static, extern, etc.) as *V // Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) { ValueDecl *VD = DRE->getDecl(); if (VarDecl *Var = dyn_cast<VarDecl>(VD)) if (!ImportedLocalExternalDecls.count(Var)) return DRE; Expr *Exp = UnaryOperator::Create( const_cast<ASTContext &>(*Context), DRE, UO_Deref, DRE->getType(), VK_LValue, OK_Ordinary, DRE->getLocation(), false, FPOptionsOverride()); // Need parens to enforce precedence. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), Exp); ReplaceStmt(DRE, PE); return PE; } void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) { SourceLocation LocStart = CE->getLParenLoc(); SourceLocation LocEnd = CE->getRParenLoc(); // Need to avoid trying to rewrite synthesized casts. if (LocStart.isInvalid()) return; // Need to avoid trying to rewrite casts contained in macros. if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd)) return; const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); QualType QT = CE->getType(); const Type* TypePtr = QT->getAs<Type>(); if (isa<TypeOfExprType>(TypePtr)) { const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr); QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType(); std::string TypeAsString = "("; RewriteBlockPointerType(TypeAsString, QT); TypeAsString += ")"; ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString); return; } // advance the location to startArgList. const char *argPtr = startBuf; while (*argPtr++ && (argPtr < endBuf)) { switch (*argPtr) { case '^': // Replace the '^' with '*'. LocStart = LocStart.getLocWithOffset(argPtr-startBuf); ReplaceText(LocStart, 1, "*"); break; } } } void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) { CastKind CastKind = IC->getCastKind(); if (CastKind != CK_BlockPointerToObjCPointerCast && CastKind != CK_AnyPointerToBlockPointerCast) return; QualType QT = IC->getType(); (void)convertBlockPointerToFunctionPointer(QT); std::string TypeString(QT.getAsString(Context->getPrintingPolicy())); std::string Str = "("; Str += TypeString; Str += ")"; InsertText(IC->getSubExpr()->getBeginLoc(), Str); } void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) { SourceLocation DeclLoc = FD->getLocation(); unsigned parenCount = 0; // We have 1 or more arguments that have closure pointers. const char *startBuf = SM->getCharacterData(DeclLoc); const char *startArgList = strchr(startBuf, '('); assert((*startArgList == '(') && "Rewriter fuzzy parser confused"); parenCount++; // advance the location to startArgList. DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf); assert((DeclLoc.isValid()) && "Invalid DeclLoc"); const char *argPtr = startArgList; while (*argPtr++ && parenCount) { switch (*argPtr) { case '^': // Replace the '^' with '*'. DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList); ReplaceText(DeclLoc, 1, "*"); break; case '(': parenCount++; break; case ')': parenCount--; break; } } } bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) { const FunctionProtoType *FTP; const PointerType *PT = QT->getAs<PointerType>(); if (PT) { FTP = PT->getPointeeType()->getAs<FunctionProtoType>(); } else { const BlockPointerType *BPT = QT->getAs<BlockPointerType>(); assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type"); FTP = BPT->getPointeeType()->getAs<FunctionProtoType>(); } if (FTP) { for (const auto &I : FTP->param_types()) if (isTopLevelBlockPointerType(I)) return true; } return false; } bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) { const FunctionProtoType *FTP; const PointerType *PT = QT->getAs<PointerType>(); if (PT) { FTP = PT->getPointeeType()->getAs<FunctionProtoType>(); } else { const BlockPointerType *BPT = QT->getAs<BlockPointerType>(); assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type"); FTP = BPT->getPointeeType()->getAs<FunctionProtoType>(); } if (FTP) { for (const auto &I : FTP->param_types()) { if (I->isObjCQualifiedIdType()) return true; if (I->isObjCObjectPointerType() && I->getPointeeType()->isObjCQualifiedInterfaceType()) return true; } } return false; } void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen) { const char *argPtr = strchr(Name, '('); assert((*argPtr == '(') && "Rewriter fuzzy parser confused"); LParen = argPtr; // output the start. argPtr++; // skip past the left paren. unsigned parenCount = 1; while (*argPtr && parenCount) { switch (*argPtr) { case '(': parenCount++; break; case ')': parenCount--; break; default: break; } if (parenCount) argPtr++; } assert((*argPtr == ')') && "Rewriter fuzzy parser confused"); RParen = argPtr; // output the end } void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) { if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { RewriteBlockPointerFunctionArgs(FD); return; } // Handle Variables and Typedefs. SourceLocation DeclLoc = ND->getLocation(); QualType DeclT; if (VarDecl *VD = dyn_cast<VarDecl>(ND)) DeclT = VD->getType(); else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND)) DeclT = TDD->getUnderlyingType(); else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND)) DeclT = FD->getType(); else llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled"); const char *startBuf = SM->getCharacterData(DeclLoc); const char *endBuf = startBuf; // scan backward (from the decl location) for the end of the previous decl. while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart) startBuf--; SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf); std::string buf; unsigned OrigLength=0; // *startBuf != '^' if we are dealing with a pointer to function that // may take block argument types (which will be handled below). if (*startBuf == '^') { // Replace the '^' with '*', computing a negative offset. buf = '*'; startBuf++; OrigLength++; } while (*startBuf != ')') { buf += *startBuf; startBuf++; OrigLength++; } buf += ')'; OrigLength++; if (PointerTypeTakesAnyBlockArguments(DeclT) || PointerTypeTakesAnyObjCQualifiedType(DeclT)) { // Replace the '^' with '*' for arguments. // Replace id<P> with id/*<>*/ DeclLoc = ND->getLocation(); startBuf = SM->getCharacterData(DeclLoc); const char *argListBegin, *argListEnd; GetExtentOfArgList(startBuf, argListBegin, argListEnd); while (argListBegin < argListEnd) { if (*argListBegin == '^') buf += '*'; else if (*argListBegin == '<') { buf += "/*"; buf += *argListBegin++; OrigLength++; while (*argListBegin != '>') { buf += *argListBegin++; OrigLength++; } buf += *argListBegin; buf += "*/"; } else buf += *argListBegin; argListBegin++; OrigLength++; } buf += ')'; OrigLength++; } ReplaceText(Start, OrigLength, buf); } /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes: /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst, /// struct Block_byref_id_object *src) { /// _Block_object_assign (&_dest->object, _src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT /// [|BLOCK_FIELD_IS_WEAK]) // object /// _Block_object_assign(&_dest->object, _src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK /// [|BLOCK_FIELD_IS_WEAK]) // block /// } /// And: /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) { /// _Block_object_dispose(_src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT /// [|BLOCK_FIELD_IS_WEAK]) // object /// _Block_object_dispose(_src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK /// [|BLOCK_FIELD_IS_WEAK]) // block /// } std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag) { std::string S; if (CopyDestroyCache.count(flag)) return S; CopyDestroyCache.insert(flag); S = "static void __Block_byref_id_object_copy_"; S += utostr(flag); S += "(void *dst, void *src) {\n"; // offset into the object pointer is computed as: // void * + void* + int + int + void* + void * unsigned IntSize = static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); unsigned VoidPtrSize = static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy)); unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth(); S += " _Block_object_assign((char*)dst + "; S += utostr(offset); S += ", *(void * *) ((char*)src + "; S += utostr(offset); S += "), "; S += utostr(flag); S += ");\n}\n"; S += "static void __Block_byref_id_object_dispose_"; S += utostr(flag); S += "(void *src) {\n"; S += " _Block_object_dispose(*(void * *) ((char*)src + "; S += utostr(offset); S += "), "; S += utostr(flag); S += ");\n}\n"; return S; } /// RewriteByRefVar - For each __block typex ND variable this routine transforms /// the declaration into: /// struct __Block_byref_ND { /// void *__isa; // NULL for everything except __weak pointers /// struct __Block_byref_ND *__forwarding; /// int32_t __flags; /// int32_t __size; /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object /// typex ND; /// }; /// /// It then replaces declaration of ND variable with: /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag, /// __size=sizeof(struct __Block_byref_ND), /// ND=initializer-if-any}; /// /// void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, bool lastDecl) { int flag = 0; int isa = 0; SourceLocation DeclLoc = ND->getTypeSpecStartLoc(); if (DeclLoc.isInvalid()) // If type location is missing, it is because of missing type (a warning). // Use variable's location which is good for this case. DeclLoc = ND->getLocation(); const char *startBuf = SM->getCharacterData(DeclLoc); SourceLocation X = ND->getEndLoc(); X = SM->getExpansionLoc(X); const char *endBuf = SM->getCharacterData(X); std::string Name(ND->getNameAsString()); std::string ByrefType; RewriteByRefString(ByrefType, Name, ND, true); ByrefType += " {\n"; ByrefType += " void *__isa;\n"; RewriteByRefString(ByrefType, Name, ND); ByrefType += " *__forwarding;\n"; ByrefType += " int __flags;\n"; ByrefType += " int __size;\n"; // Add void *__Block_byref_id_object_copy; // void *__Block_byref_id_object_dispose; if needed. QualType Ty = ND->getType(); bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND); if (HasCopyAndDispose) { ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n"; ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n"; } QualType T = Ty; (void)convertBlockPointerToFunctionPointer(T); T.getAsStringInternal(Name, Context->getPrintingPolicy()); ByrefType += " " + Name + ";\n"; ByrefType += "};\n"; // Insert this type in global scope. It is needed by helper function. SourceLocation FunLocStart; if (CurFunctionDef) FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef); else { assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null"); FunLocStart = CurMethodDef->getBeginLoc(); } InsertText(FunLocStart, ByrefType); if (Ty.isObjCGCWeak()) { flag |= BLOCK_FIELD_IS_WEAK; isa = 1; } if (HasCopyAndDispose) { flag = BLOCK_BYREF_CALLER; QualType Ty = ND->getType(); // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well. if (Ty->isBlockPointerType()) flag |= BLOCK_FIELD_IS_BLOCK; else flag |= BLOCK_FIELD_IS_OBJECT; std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag); if (!HF.empty()) Preamble += HF; } // struct __Block_byref_ND ND = // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND), // initializer-if-any}; bool hasInit = (ND->getInit() != nullptr); // FIXME. rewriter does not support __block c++ objects which // require construction. if (hasInit) if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) { CXXConstructorDecl *CXXDecl = CExp->getConstructor(); if (CXXDecl && CXXDecl->isDefaultConstructor()) hasInit = false; } unsigned flags = 0; if (HasCopyAndDispose) flags |= BLOCK_HAS_COPY_DISPOSE; Name = ND->getNameAsString(); ByrefType.clear(); RewriteByRefString(ByrefType, Name, ND); std::string ForwardingCastType("("); ForwardingCastType += ByrefType + " *)"; ByrefType += " " + Name + " = {(void*)"; ByrefType += utostr(isa); ByrefType += "," + ForwardingCastType + "&" + Name + ", "; ByrefType += utostr(flags); ByrefType += ", "; ByrefType += "sizeof("; RewriteByRefString(ByrefType, Name, ND); ByrefType += ")"; if (HasCopyAndDispose) { ByrefType += ", __Block_byref_id_object_copy_"; ByrefType += utostr(flag); ByrefType += ", __Block_byref_id_object_dispose_"; ByrefType += utostr(flag); } if (!firstDecl) { // In multiple __block declarations, and for all but 1st declaration, // find location of the separating comma. This would be start location // where new text is to be inserted. DeclLoc = ND->getLocation(); const char *startDeclBuf = SM->getCharacterData(DeclLoc); const char *commaBuf = startDeclBuf; while (*commaBuf != ',') commaBuf--; assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','"); DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf); startBuf = commaBuf; } if (!hasInit) { ByrefType += "};\n"; unsigned nameSize = Name.size(); // for block or function pointer declaration. Name is already // part of the declaration. if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) nameSize = 1; ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType); } else { ByrefType += ", "; SourceLocation startLoc; Expr *E = ND->getInit(); if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) startLoc = ECE->getLParenLoc(); else startLoc = E->getBeginLoc(); startLoc = SM->getExpansionLoc(startLoc); endBuf = SM->getCharacterData(startLoc); ReplaceText(DeclLoc, endBuf-startBuf, ByrefType); const char separator = lastDecl ? ';' : ','; const char *startInitializerBuf = SM->getCharacterData(startLoc); const char *separatorBuf = strchr(startInitializerBuf, separator); assert((*separatorBuf == separator) && "RewriteByRefVar: can't find ';' or ','"); SourceLocation separatorLoc = startLoc.getLocWithOffset(separatorBuf-startInitializerBuf); InsertText(separatorLoc, lastDecl ? "}" : "};\n"); } } void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) { // Add initializers for any closure decl refs. GetBlockDeclRefExprs(Exp->getBody()); if (BlockDeclRefs.size()) { // Unique all "by copy" declarations. for (unsigned i = 0; i < BlockDeclRefs.size(); i++) if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) { if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) { BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl()); BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl()); } } // Unique all "by ref" declarations. for (unsigned i = 0; i < BlockDeclRefs.size(); i++) if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) { if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) { BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl()); BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl()); } } // Find any imported blocks...they will need special attention. for (unsigned i = 0; i < BlockDeclRefs.size(); i++) if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() || BlockDeclRefs[i]->getType()->isObjCObjectPointerType() || BlockDeclRefs[i]->getType()->isBlockPointerType()) ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl()); } } FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) { IdentifierInfo *ID = &Context->Idents.get(name); QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy); return FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), ID, FType, nullptr, SC_Extern, false, false); } Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) { const BlockDecl *block = Exp->getBlockDecl(); Blocks.push_back(Exp); CollectBlockDeclRefInfo(Exp); // Add inner imported variables now used in current block. int countOfInnerDecls = 0; if (!InnerBlockDeclRefs.empty()) { for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) { DeclRefExpr *Exp = InnerBlockDeclRefs[i]; ValueDecl *VD = Exp->getDecl(); if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) { // We need to save the copied-in variables in nested // blocks because it is needed at the end for some of the API generations. // See SynthesizeBlockLiterals routine. InnerDeclRefs.push_back(Exp); countOfInnerDecls++; BlockDeclRefs.push_back(Exp); BlockByCopyDeclsPtrSet.insert(VD); BlockByCopyDecls.push_back(VD); } if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) { InnerDeclRefs.push_back(Exp); countOfInnerDecls++; BlockDeclRefs.push_back(Exp); BlockByRefDeclsPtrSet.insert(VD); BlockByRefDecls.push_back(VD); } } // Find any imported blocks...they will need special attention. for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() || InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() || InnerBlockDeclRefs[i]->getType()->isBlockPointerType()) ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl()); } InnerDeclRefsCount.push_back(countOfInnerDecls); std::string FuncName; if (CurFunctionDef) FuncName = CurFunctionDef->getNameAsString(); else if (CurMethodDef) BuildUniqueMethodName(FuncName, CurMethodDef); else if (GlobalVarDecl) FuncName = std::string(GlobalVarDecl->getNameAsString()); bool GlobalBlockExpr = block->getDeclContext()->getRedeclContext()->isFileContext(); if (GlobalBlockExpr && !GlobalVarDecl) { Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag); GlobalBlockExpr = false; } std::string BlockNumber = utostr(Blocks.size()-1); std::string Func = "__" + FuncName + "_block_func_" + BlockNumber; // Get a pointer to the function type so we can cast appropriately. QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType()); QualType FType = Context->getPointerType(BFT); FunctionDecl *FD; Expr *NewRep; // Simulate a constructor call... std::string Tag; if (GlobalBlockExpr) Tag = "__global_"; else Tag = "__"; Tag += FuncName + "_block_impl_" + BlockNumber; FD = SynthBlockInitFunctionDecl(Tag); DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, FType, VK_PRValue, SourceLocation()); SmallVector<Expr*, 4> InitExprs; // Initialize the block function. FD = SynthBlockInitFunctionDecl(Func); DeclRefExpr *Arg = new (Context) DeclRefExpr( *Context, FD, false, FD->getType(), VK_LValue, SourceLocation()); CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast, Arg); InitExprs.push_back(castExpr); // Initialize the block descriptor. std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA"; VarDecl *NewVD = VarDecl::Create( *Context, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static); UnaryOperator *DescRefExpr = UnaryOperator::Create( const_cast<ASTContext &>(*Context), new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy, VK_LValue, SourceLocation()), UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); InitExprs.push_back(DescRefExpr); // Add initializers for any closure decl refs. if (BlockDeclRefs.size()) { Expr *Exp; // Output all "by copy" declarations. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { if (isObjCType((*I)->getType())) { // FIXME: Conform to ABI ([[obj retain] autorelease]). FD = SynthBlockInitFunctionDecl((*I)->getName()); Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(), VK_LValue, SourceLocation()); if (HasLocalVariableExternalStorage(*I)) { QualType QT = (*I)->getType(); QT = Context->getPointerType(QT); Exp = UnaryOperator::Create(const_cast<ASTContext &>(*Context), Exp, UO_AddrOf, QT, VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); } } else if (isTopLevelBlockPointerType((*I)->getType())) { FD = SynthBlockInitFunctionDecl((*I)->getName()); Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(), VK_LValue, SourceLocation()); Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast, Arg); } else { FD = SynthBlockInitFunctionDecl((*I)->getName()); Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(), VK_LValue, SourceLocation()); if (HasLocalVariableExternalStorage(*I)) { QualType QT = (*I)->getType(); QT = Context->getPointerType(QT); Exp = UnaryOperator::Create(const_cast<ASTContext &>(*Context), Exp, UO_AddrOf, QT, VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); } } InitExprs.push_back(Exp); } // Output all "by ref" declarations. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { ValueDecl *ND = (*I); std::string Name(ND->getNameAsString()); std::string RecName; RewriteByRefString(RecName, Name, ND, true); IdentifierInfo *II = &Context->Idents.get(RecName.c_str() + sizeof("struct")); RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), II); assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl"); QualType castT = Context->getPointerType(Context->getTagDeclType(RD)); FD = SynthBlockInitFunctionDecl((*I)->getName()); Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(), VK_LValue, SourceLocation()); bool isNestedCapturedVar = false; if (block) for (const auto &CI : block->captures()) { const VarDecl *variable = CI.getVariable(); if (variable == ND && CI.isNested()) { assert (CI.isByRef() && "SynthBlockInitExpr - captured block variable is not byref"); isNestedCapturedVar = true; break; } } // captured nested byref variable has its address passed. Do not take // its address again. if (!isNestedCapturedVar) Exp = UnaryOperator::Create( const_cast<ASTContext &>(*Context), Exp, UO_AddrOf, Context->getPointerType(Exp->getType()), VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp); InitExprs.push_back(Exp); } } if (ImportedBlockDecls.size()) { // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR); unsigned IntSize = static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag), Context->IntTy, SourceLocation()); InitExprs.push_back(FlagExp); } NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue, SourceLocation(), FPOptionsOverride()); if (GlobalBlockExpr) { assert (!GlobalConstructionExp && "SynthBlockInitExpr - GlobalConstructionExp must be null"); GlobalConstructionExp = NewRep; NewRep = DRE; } NewRep = UnaryOperator::Create( const_cast<ASTContext &>(*Context), NewRep, UO_AddrOf, Context->getPointerType(NewRep->getType()), VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast, NewRep); // Put Paren around the call. NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(), NewRep); BlockDeclRefs.clear(); BlockByRefDecls.clear(); BlockByRefDeclsPtrSet.clear(); BlockByCopyDecls.clear(); BlockByCopyDeclsPtrSet.clear(); ImportedBlockDecls.clear(); return NewRep; } bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) { if (const ObjCForCollectionStmt * CS = dyn_cast<ObjCForCollectionStmt>(Stmts.back())) return CS->getElement() == DS; return false; } //===----------------------------------------------------------------------===// // Function Body / Expression rewriting //===----------------------------------------------------------------------===// Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) || isa<ForStmt>(S)) Stmts.push_back(S); else if (isa<ObjCForCollectionStmt>(S)) { Stmts.push_back(S); ObjCBcLabelNo.push_back(++BcLabelCount); } // Pseudo-object operations and ivar references need special // treatment because we're going to recursively rewrite them. if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) { if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) { return RewritePropertyOrImplicitSetter(PseudoOp); } else { return RewritePropertyOrImplicitGetter(PseudoOp); } } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) { return RewriteObjCIvarRefExpr(IvarRefExpr); } else if (isa<OpaqueValueExpr>(S)) S = cast<OpaqueValueExpr>(S)->getSourceExpr(); SourceRange OrigStmtRange = S->getSourceRange(); // Perform a bottom up rewrite of all children. for (Stmt *&childStmt : S->children()) if (childStmt) { Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt); if (newStmt) { childStmt = newStmt; } } if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) { SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs; llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts; InnerContexts.insert(BE->getBlockDecl()); ImportedLocalExternalDecls.clear(); GetInnerBlockDeclRefExprs(BE->getBody(), InnerBlockDeclRefs, InnerContexts); // Rewrite the block body in place. Stmt *SaveCurrentBody = CurrentBody; CurrentBody = BE->getBody(); PropParentMap = nullptr; // block literal on rhs of a property-dot-sytax assignment // must be replaced by its synthesize ast so getRewrittenText // works as expected. In this case, what actually ends up on RHS // is the blockTranscribed which is the helper function for the // block literal; as in: self.c = ^() {[ace ARR];}; bool saveDisableReplaceStmt = DisableReplaceStmt; DisableReplaceStmt = false; RewriteFunctionBodyOrGlobalInitializer(BE->getBody()); DisableReplaceStmt = saveDisableReplaceStmt; CurrentBody = SaveCurrentBody; PropParentMap = nullptr; ImportedLocalExternalDecls.clear(); // Now we snarf the rewritten text and stash it away for later use. std::string Str = Rewrite.getRewrittenText(BE->getSourceRange()); RewrittenBlockExprs[BE] = Str; Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs); //blockTranscribed->dump(); ReplaceStmt(S, blockTranscribed); return blockTranscribed; } // Handle specific things. if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S)) return RewriteAtEncode(AtEncode); if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S)) return RewriteAtSelector(AtSelector); if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S)) return RewriteObjCStringLiteral(AtString); if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S)) return RewriteObjCBoolLiteralExpr(BoolLitExpr); if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S)) return RewriteObjCBoxedExpr(BoxedExpr); if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S)) return RewriteObjCArrayLiteralExpr(ArrayLitExpr); if (ObjCDictionaryLiteral *DictionaryLitExpr = dyn_cast<ObjCDictionaryLiteral>(S)) return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr); if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) { #if 0 // Before we rewrite it, put the original message expression in a comment. SourceLocation startLoc = MessExpr->getBeginLoc(); SourceLocation endLoc = MessExpr->getEndLoc(); const char *startBuf = SM->getCharacterData(startLoc); const char *endBuf = SM->getCharacterData(endLoc); std::string messString; messString += "// "; messString.append(startBuf, endBuf-startBuf+1); messString += "\n"; // FIXME: Missing definition of // InsertText(clang::SourceLocation, char const*, unsigned int). // InsertText(startLoc, messString); // Tried this, but it didn't work either... // ReplaceText(startLoc, 0, messString.c_str(), messString.size()); #endif return RewriteMessageExpr(MessExpr); } if (ObjCAutoreleasePoolStmt *StmtAutoRelease = dyn_cast<ObjCAutoreleasePoolStmt>(S)) { return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease); } if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S)) return RewriteObjCTryStmt(StmtTry); if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S)) return RewriteObjCSynchronizedStmt(StmtTry); if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S)) return RewriteObjCThrowStmt(StmtThrow); if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S)) return RewriteObjCProtocolExpr(ProtocolExp); if (ObjCForCollectionStmt *StmtForCollection = dyn_cast<ObjCForCollectionStmt>(S)) return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtRange.getEnd()); if (BreakStmt *StmtBreakStmt = dyn_cast<BreakStmt>(S)) return RewriteBreakStmt(StmtBreakStmt); if (ContinueStmt *StmtContinueStmt = dyn_cast<ContinueStmt>(S)) return RewriteContinueStmt(StmtContinueStmt); // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls // and cast exprs. if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) { // FIXME: What we're doing here is modifying the type-specifier that // precedes the first Decl. In the future the DeclGroup should have // a separate type-specifier that we can rewrite. // NOTE: We need to avoid rewriting the DeclStmt if it is within // the context of an ObjCForCollectionStmt. For example: // NSArray *someArray; // for (id <FooProtocol> index in someArray) ; // This is because RewriteObjCForCollectionStmt() does textual rewriting // and it depends on the original text locations/positions. if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS)) RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin()); // Blocks rewrite rules. for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end(); DI != DE; ++DI) { Decl *SD = *DI; if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) { if (isTopLevelBlockPointerType(ND->getType())) RewriteBlockPointerDecl(ND); else if (ND->getType()->isFunctionPointerType()) CheckFunctionPointerDecl(ND->getType(), ND); if (VarDecl *VD = dyn_cast<VarDecl>(SD)) { if (VD->hasAttr<BlocksAttr>()) { static unsigned uniqueByrefDeclCount = 0; assert(!BlockByRefDeclNo.count(ND) && "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl"); BlockByRefDeclNo[ND] = uniqueByrefDeclCount++; RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE)); } else RewriteTypeOfDecl(VD); } } if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) { if (isTopLevelBlockPointerType(TD->getUnderlyingType())) RewriteBlockPointerDecl(TD); else if (TD->getUnderlyingType()->isFunctionPointerType()) CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); } } } if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) RewriteObjCQualifiedInterfaceTypes(CE); if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) || isa<ForStmt>(S)) { assert(!Stmts.empty() && "Statement stack is empty"); assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) || isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back())) && "Statement stack mismatch"); Stmts.pop_back(); } // Handle blocks rewriting. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) { ValueDecl *VD = DRE->getDecl(); if (VD->hasAttr<BlocksAttr>()) return RewriteBlockDeclRefExpr(DRE); if (HasLocalVariableExternalStorage(VD)) return RewriteLocalVariableExternalStorage(DRE); } if (CallExpr *CE = dyn_cast<CallExpr>(S)) { if (CE->getCallee()->getType()->isBlockPointerType()) { Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee()); ReplaceStmt(S, BlockCall); return BlockCall; } } if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) { RewriteCastExpr(CE); } if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) { RewriteImplicitCastObjCExpr(ICE); } #if 0 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) { CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation()); // Get the new text. std::string SStr; llvm::raw_string_ostream Buf(SStr); Replacement->printPretty(Buf); const std::string &Str = Buf.str(); printf("CAST = %s\n", &Str[0]); InsertText(ICE->getSubExpr()->getBeginLoc(), Str); delete S; return Replacement; } #endif // Return this stmt unmodified. return S; } void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) { for (auto *FD : RD->fields()) { if (isTopLevelBlockPointerType(FD->getType())) RewriteBlockPointerDecl(FD); if (FD->getType()->isObjCQualifiedIdType() || FD->getType()->isObjCQualifiedInterfaceType()) RewriteObjCQualifiedInterfaceTypes(FD); } } /// HandleDeclInMainFile - This is called for each top-level decl defined in the /// main file of the input. void RewriteModernObjC::HandleDeclInMainFile(Decl *D) { switch (D->getKind()) { case Decl::Function: { FunctionDecl *FD = cast<FunctionDecl>(D); if (FD->isOverloadedOperator()) return; // Since function prototypes don't have ParmDecl's, we check the function // prototype. This enables us to rewrite function declarations and // definitions using the same code. RewriteBlocksInFunctionProtoType(FD->getType(), FD); if (!FD->isThisDeclarationADefinition()) break; // FIXME: If this should support Obj-C++, support CXXTryStmt if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) { CurFunctionDef = FD; CurrentBody = Body; Body = cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body)); FD->setBody(Body); CurrentBody = nullptr; if (PropParentMap) { delete PropParentMap; PropParentMap = nullptr; } // This synthesizes and inserts the block "impl" struct, invoke function, // and any copy/dispose helper functions. InsertBlockLiteralsWithinFunction(FD); RewriteLineDirective(D); CurFunctionDef = nullptr; } break; } case Decl::ObjCMethod: { ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D); if (CompoundStmt *Body = MD->getCompoundBody()) { CurMethodDef = MD; CurrentBody = Body; Body = cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body)); MD->setBody(Body); CurrentBody = nullptr; if (PropParentMap) { delete PropParentMap; PropParentMap = nullptr; } InsertBlockLiteralsWithinMethod(MD); RewriteLineDirective(D); CurMethodDef = nullptr; } break; } case Decl::ObjCImplementation: { ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D); ClassImplementation.push_back(CI); break; } case Decl::ObjCCategoryImpl: { ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D); CategoryImplementation.push_back(CI); break; } case Decl::Var: { VarDecl *VD = cast<VarDecl>(D); RewriteObjCQualifiedInterfaceTypes(VD); if (isTopLevelBlockPointerType(VD->getType())) RewriteBlockPointerDecl(VD); else if (VD->getType()->isFunctionPointerType()) { CheckFunctionPointerDecl(VD->getType(), VD); if (VD->getInit()) { if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) { RewriteCastExpr(CE); } } } else if (VD->getType()->isRecordType()) { RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl(); if (RD->isCompleteDefinition()) RewriteRecordBody(RD); } if (VD->getInit()) { GlobalVarDecl = VD; CurrentBody = VD->getInit(); RewriteFunctionBodyOrGlobalInitializer(VD->getInit()); CurrentBody = nullptr; if (PropParentMap) { delete PropParentMap; PropParentMap = nullptr; } SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName()); GlobalVarDecl = nullptr; // This is needed for blocks. if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) { RewriteCastExpr(CE); } } break; } case Decl::TypeAlias: case Decl::Typedef: { if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { if (isTopLevelBlockPointerType(TD->getUnderlyingType())) RewriteBlockPointerDecl(TD); else if (TD->getUnderlyingType()->isFunctionPointerType()) CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); else RewriteObjCQualifiedInterfaceTypes(TD); } break; } case Decl::CXXRecord: case Decl::Record: { RecordDecl *RD = cast<RecordDecl>(D); if (RD->isCompleteDefinition()) RewriteRecordBody(RD); break; } default: break; } // Nothing yet. } /// Write_ProtocolExprReferencedMetadata - This routine writer out the /// protocol reference symbols in the for of: /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA. static void Write_ProtocolExprReferencedMetadata(ASTContext *Context, ObjCProtocolDecl *PDecl, std::string &Result) { // Also output .objc_protorefs$B section and its meta-data. if (Context->getLangOpts().MicrosoftExt) Result += "static "; Result += "struct _protocol_t *"; Result += "_OBJC_PROTOCOL_REFERENCE_$_"; Result += PDecl->getNameAsString(); Result += " = &"; Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString(); Result += ";\n"; } void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) { if (Diags.hasErrorOccurred()) return; RewriteInclude(); for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) { // translation of function bodies were postponed until all class and // their extensions and implementations are seen. This is because, we // cannot build grouping structs for bitfields until they are all seen. FunctionDecl *FDecl = FunctionDefinitionsSeen[i]; HandleTopLevelSingleDecl(FDecl); } // Here's a great place to add any extra declarations that may be needed. // Write out meta data for each @protocol(<expr>). for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) { RewriteObjCProtocolMetaData(ProtDecl, Preamble); Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble); } InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false); if (ClassImplementation.size() || CategoryImplementation.size()) RewriteImplementations(); for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) { ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i]; // Write struct declaration for the class matching its ivar declarations. // Note that for modern abi, this is postponed until the end of TU // because class extensions and the implementation might declare their own // private ivars. RewriteInterfaceDecl(CDecl); } // Get the buffer corresponding to MainFileID. If we haven't changed it, then // we are done. if (const RewriteBuffer *RewriteBuf = Rewrite.getRewriteBufferFor(MainFileID)) { //printf("Changed:\n"); *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end()); } else { llvm::errs() << "No changes\n"; } if (ClassImplementation.size() || CategoryImplementation.size() || ProtocolExprDecls.size()) { // Rewrite Objective-c meta data* std::string ResultStr; RewriteMetaDataIntoBuffer(ResultStr); // Emit metadata. *OutFile << ResultStr; } // Emit ImageInfo; { std::string ResultStr; WriteImageInfo(ResultStr); *OutFile << ResultStr; } OutFile->flush(); } void RewriteModernObjC::Initialize(ASTContext &context) { InitializeCommon(context); Preamble += "#ifndef __OBJC2__\n"; Preamble += "#define __OBJC2__\n"; Preamble += "#endif\n"; // declaring objc_selector outside the parameter list removes a silly // scope related warning... if (IsHeader) Preamble = "#pragma once\n"; Preamble += "struct objc_selector; struct objc_class;\n"; Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; "; Preamble += "\n\tstruct objc_object *superClass; "; // Add a constructor for creating temporary objects. Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) "; Preamble += ": object(o), superClass(s) {} "; Preamble += "\n};\n"; if (LangOpts.MicrosoftExt) { // Define all sections using syntax that makes sense. // These are currently generated. Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n"; // These are generated but not necessary for functionality. Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n"; Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n"; Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n"; // These need be generated for performance. Currently they are not, // using API calls instead. Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n"; } Preamble += "#ifndef _REWRITER_typedef_Protocol\n"; Preamble += "typedef struct objc_object Protocol;\n"; Preamble += "#define _REWRITER_typedef_Protocol\n"; Preamble += "#endif\n"; if (LangOpts.MicrosoftExt) { Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n"; Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n"; } else Preamble += "#define __OBJC_RW_DLLIMPORT extern\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n"; Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass"; Preamble += "(const char *);\n"; Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass"; Preamble += "(struct objc_class *);\n"; Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass"; Preamble += "(const char *);\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n"; // @synchronized hooks. Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n"; Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n"; Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n"; Preamble += "#ifdef _WIN64\n"; Preamble += "typedef unsigned long long _WIN_NSUInteger;\n"; Preamble += "#else\n"; Preamble += "typedef unsigned int _WIN_NSUInteger;\n"; Preamble += "#endif\n"; Preamble += "#ifndef __FASTENUMERATIONSTATE\n"; Preamble += "struct __objcFastEnumerationState {\n\t"; Preamble += "unsigned long state;\n\t"; Preamble += "void **itemsPtr;\n\t"; Preamble += "unsigned long *mutationsPtr;\n\t"; Preamble += "unsigned long extra[5];\n};\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n"; Preamble += "#define __FASTENUMERATIONSTATE\n"; Preamble += "#endif\n"; Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n"; Preamble += "struct __NSConstantStringImpl {\n"; Preamble += " int *isa;\n"; Preamble += " int flags;\n"; Preamble += " char *str;\n"; Preamble += "#if _WIN64\n"; Preamble += " long long length;\n"; Preamble += "#else\n"; Preamble += " long length;\n"; Preamble += "#endif\n"; Preamble += "};\n"; Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n"; Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n"; Preamble += "#else\n"; Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n"; Preamble += "#endif\n"; Preamble += "#define __NSCONSTANTSTRINGIMPL\n"; Preamble += "#endif\n"; // Blocks preamble. Preamble += "#ifndef BLOCK_IMPL\n"; Preamble += "#define BLOCK_IMPL\n"; Preamble += "struct __block_impl {\n"; Preamble += " void *isa;\n"; Preamble += " int Flags;\n"; Preamble += " int Reserved;\n"; Preamble += " void *FuncPtr;\n"; Preamble += "};\n"; Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n"; Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n"; Preamble += "extern \"C\" __declspec(dllexport) " "void _Block_object_assign(void *, const void *, const int);\n"; Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n"; Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n"; Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n"; Preamble += "#else\n"; Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n"; Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n"; Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n"; Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n"; Preamble += "#endif\n"; Preamble += "#endif\n"; if (LangOpts.MicrosoftExt) { Preamble += "#undef __OBJC_RW_DLLIMPORT\n"; Preamble += "#undef __OBJC_RW_STATICIMPORT\n"; Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests. Preamble += "#define __attribute__(X)\n"; Preamble += "#endif\n"; Preamble += "#ifndef __weak\n"; Preamble += "#define __weak\n"; Preamble += "#endif\n"; Preamble += "#ifndef __block\n"; Preamble += "#define __block\n"; Preamble += "#endif\n"; } else { Preamble += "#define __block\n"; Preamble += "#define __weak\n"; } // Declarations required for modern objective-c array and dictionary literals. Preamble += "\n#include <stdarg.h>\n"; Preamble += "struct __NSContainer_literal {\n"; Preamble += " void * *arr;\n"; Preamble += " __NSContainer_literal (unsigned int count, ...) {\n"; Preamble += "\tva_list marker;\n"; Preamble += "\tva_start(marker, count);\n"; Preamble += "\tarr = new void *[count];\n"; Preamble += "\tfor (unsigned i = 0; i < count; i++)\n"; Preamble += "\t arr[i] = va_arg(marker, void *);\n"; Preamble += "\tva_end( marker );\n"; Preamble += " };\n"; Preamble += " ~__NSContainer_literal() {\n"; Preamble += "\tdelete[] arr;\n"; Preamble += " }\n"; Preamble += "};\n"; // Declaration required for implementation of @autoreleasepool statement. Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n"; Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n"; Preamble += "struct __AtAutoreleasePool {\n"; Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n"; Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n"; Preamble += " void * atautoreleasepoolobj;\n"; Preamble += "};\n"; // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long // as this avoids warning in any 64bit/32bit compilation model. Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n"; } /// RewriteIvarOffsetComputation - This routine synthesizes computation of /// ivar offset. void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar, std::string &Result) { Result += "__OFFSETOFIVAR__(struct "; Result += ivar->getContainingInterface()->getNameAsString(); if (LangOpts.MicrosoftExt) Result += "_IMPL"; Result += ", "; if (ivar->isBitField()) ObjCIvarBitfieldGroupDecl(ivar, Result); else Result += ivar->getNameAsString(); Result += ")"; } /// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI. /// struct _prop_t { /// const char *name; /// char *attributes; /// } /// struct _prop_list_t { /// uint32_t entsize; // sizeof(struct _prop_t) /// uint32_t count_of_properties; /// struct _prop_t prop_list[count_of_properties]; /// } /// struct _protocol_t; /// struct _protocol_list_t { /// long protocol_count; // Note, this is 32/64 bit /// struct _protocol_t * protocol_list[protocol_count]; /// } /// struct _objc_method { /// SEL _cmd; /// const char *method_type; /// char *_imp; /// } /// struct _method_list_t { /// uint32_t entsize; // sizeof(struct _objc_method) /// uint32_t method_count; /// struct _objc_method method_list[method_count]; /// } /// struct _protocol_t { /// id isa; // NULL /// const char *protocol_name; /// const struct _protocol_list_t * protocol_list; // super protocols /// const struct method_list_t *instance_methods; /// const struct method_list_t *class_methods; /// const struct method_list_t *optionalInstanceMethods; /// const struct method_list_t *optionalClassMethods; /// const struct _prop_list_t * properties; /// const uint32_t size; // sizeof(struct _protocol_t) /// const uint32_t flags; // = 0 /// const char ** extendedMethodTypes; /// } /// struct _ivar_t { /// unsigned long int *offset; // pointer to ivar offset location /// const char *name; /// const char *type; /// uint32_t alignment; /// uint32_t size; /// } /// struct _ivar_list_t { /// uint32 entsize; // sizeof(struct _ivar_t) /// uint32 count; /// struct _ivar_t list[count]; /// } /// struct _class_ro_t { /// uint32_t flags; /// uint32_t instanceStart; /// uint32_t instanceSize; /// uint32_t reserved; // only when building for 64bit targets /// const uint8_t *ivarLayout; /// const char *name; /// const struct _method_list_t *baseMethods; /// const struct _protocol_list_t *baseProtocols; /// const struct _ivar_list_t *ivars; /// const uint8_t *weakIvarLayout; /// const struct _prop_list_t *properties; /// } /// struct _class_t { /// struct _class_t *isa; /// struct _class_t *superclass; /// void *cache; /// IMP *vtable; /// struct _class_ro_t *ro; /// } /// struct _category_t { /// const char *name; /// struct _class_t *cls; /// const struct _method_list_t *instance_methods; /// const struct _method_list_t *class_methods; /// const struct _protocol_list_t *protocols; /// const struct _prop_list_t *properties; /// } /// MessageRefTy - LLVM for: /// struct _message_ref_t { /// IMP messenger; /// SEL name; /// }; /// SuperMessageRefTy - LLVM for: /// struct _super_message_ref_t { /// SUPER_IMP messenger; /// SEL name; /// }; static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) { static bool meta_data_declared = false; if (meta_data_declared) return; Result += "\nstruct _prop_t {\n"; Result += "\tconst char *name;\n"; Result += "\tconst char *attributes;\n"; Result += "};\n"; Result += "\nstruct _protocol_t;\n"; Result += "\nstruct _objc_method {\n"; Result += "\tstruct objc_selector * _cmd;\n"; Result += "\tconst char *method_type;\n"; Result += "\tvoid *_imp;\n"; Result += "};\n"; Result += "\nstruct _protocol_t {\n"; Result += "\tvoid * isa; // NULL\n"; Result += "\tconst char *protocol_name;\n"; Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n"; Result += "\tconst struct method_list_t *instance_methods;\n"; Result += "\tconst struct method_list_t *class_methods;\n"; Result += "\tconst struct method_list_t *optionalInstanceMethods;\n"; Result += "\tconst struct method_list_t *optionalClassMethods;\n"; Result += "\tconst struct _prop_list_t * properties;\n"; Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n"; Result += "\tconst unsigned int flags; // = 0\n"; Result += "\tconst char ** extendedMethodTypes;\n"; Result += "};\n"; Result += "\nstruct _ivar_t {\n"; Result += "\tunsigned long int *offset; // pointer to ivar offset location\n"; Result += "\tconst char *name;\n"; Result += "\tconst char *type;\n"; Result += "\tunsigned int alignment;\n"; Result += "\tunsigned int size;\n"; Result += "};\n"; Result += "\nstruct _class_ro_t {\n"; Result += "\tunsigned int flags;\n"; Result += "\tunsigned int instanceStart;\n"; Result += "\tunsigned int instanceSize;\n"; const llvm::Triple &Triple(Context->getTargetInfo().getTriple()); if (Triple.getArch() == llvm::Triple::x86_64) Result += "\tunsigned int reserved;\n"; Result += "\tconst unsigned char *ivarLayout;\n"; Result += "\tconst char *name;\n"; Result += "\tconst struct _method_list_t *baseMethods;\n"; Result += "\tconst struct _objc_protocol_list *baseProtocols;\n"; Result += "\tconst struct _ivar_list_t *ivars;\n"; Result += "\tconst unsigned char *weakIvarLayout;\n"; Result += "\tconst struct _prop_list_t *properties;\n"; Result += "};\n"; Result += "\nstruct _class_t {\n"; Result += "\tstruct _class_t *isa;\n"; Result += "\tstruct _class_t *superclass;\n"; Result += "\tvoid *cache;\n"; Result += "\tvoid *vtable;\n"; Result += "\tstruct _class_ro_t *ro;\n"; Result += "};\n"; Result += "\nstruct _category_t {\n"; Result += "\tconst char *name;\n"; Result += "\tstruct _class_t *cls;\n"; Result += "\tconst struct _method_list_t *instance_methods;\n"; Result += "\tconst struct _method_list_t *class_methods;\n"; Result += "\tconst struct _protocol_list_t *protocols;\n"; Result += "\tconst struct _prop_list_t *properties;\n"; Result += "};\n"; Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n"; Result += "#pragma warning(disable:4273)\n"; meta_data_declared = true; } static void Write_protocol_list_t_TypeDecl(std::string &Result, long super_protocol_count) { Result += "struct /*_protocol_list_t*/"; Result += " {\n"; Result += "\tlong protocol_count; // Note, this is 32/64 bit\n"; Result += "\tstruct _protocol_t *super_protocols["; Result += utostr(super_protocol_count); Result += "];\n"; Result += "}"; } static void Write_method_list_t_TypeDecl(std::string &Result, unsigned int method_count) { Result += "struct /*_method_list_t*/"; Result += " {\n"; Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n"; Result += "\tunsigned int method_count;\n"; Result += "\tstruct _objc_method method_list["; Result += utostr(method_count); Result += "];\n"; Result += "}"; } static void Write__prop_list_t_TypeDecl(std::string &Result, unsigned int property_count) { Result += "struct /*_prop_list_t*/"; Result += " {\n"; Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n"; Result += "\tunsigned int count_of_properties;\n"; Result += "\tstruct _prop_t prop_list["; Result += utostr(property_count); Result += "];\n"; Result += "}"; } static void Write__ivar_list_t_TypeDecl(std::string &Result, unsigned int ivar_count) { Result += "struct /*_ivar_list_t*/"; Result += " {\n"; Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n"; Result += "\tunsigned int count;\n"; Result += "\tstruct _ivar_t ivar_list["; Result += utostr(ivar_count); Result += "];\n"; Result += "}"; } static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result, ArrayRef<ObjCProtocolDecl *> SuperProtocols, StringRef VarName, StringRef ProtocolName) { if (SuperProtocols.size() > 0) { Result += "\nstatic "; Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size()); Result += " "; Result += VarName; Result += ProtocolName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n"; for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) { ObjCProtocolDecl *SuperPD = SuperProtocols[i]; Result += "\t&"; Result += "_OBJC_PROTOCOL_"; Result += SuperPD->getNameAsString(); if (i == e-1) Result += "\n};\n"; else Result += ",\n"; } } } static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ArrayRef<ObjCMethodDecl *> Methods, StringRef VarName, StringRef TopLevelDeclName, bool MethodImpl) { if (Methods.size() > 0) { Result += "\nstatic "; Write_method_list_t_TypeDecl(Result, Methods.size()); Result += " "; Result += VarName; Result += TopLevelDeclName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n"; Result += "\t"; Result += utostr(Methods.size()); Result += ",\n"; for (unsigned i = 0, e = Methods.size(); i < e; i++) { ObjCMethodDecl *MD = Methods[i]; if (i == 0) Result += "\t{{(struct objc_selector *)\""; else Result += "\t{(struct objc_selector *)\""; Result += (MD)->getSelector().getAsString(); Result += "\""; Result += ", "; std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD); Result += "\""; Result += MethodTypeString; Result += "\""; Result += ", "; if (!MethodImpl) Result += "0"; else { Result += "(void *)"; Result += RewriteObj.MethodInternalNames[MD]; } if (i == e-1) Result += "}}\n"; else Result += "},\n"; } Result += "};\n"; } } static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ArrayRef<ObjCPropertyDecl *> Properties, const Decl *Container, StringRef VarName, StringRef ProtocolName) { if (Properties.size() > 0) { Result += "\nstatic "; Write__prop_list_t_TypeDecl(Result, Properties.size()); Result += " "; Result += VarName; Result += ProtocolName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n"; Result += "\t"; Result += utostr(Properties.size()); Result += ",\n"; for (unsigned i = 0, e = Properties.size(); i < e; i++) { ObjCPropertyDecl *PropDecl = Properties[i]; if (i == 0) Result += "\t{{\""; else Result += "\t{\""; Result += PropDecl->getName(); Result += "\","; std::string PropertyTypeString = Context->getObjCEncodingForPropertyDecl(PropDecl, Container); std::string QuotePropertyTypeString; RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString); Result += "\""; Result += QuotePropertyTypeString; Result += "\""; if (i == e-1) Result += "}}\n"; else Result += "},\n"; } Result += "};\n"; } } // Metadata flags enum MetaDataDlags { CLS = 0x0, CLS_META = 0x1, CLS_ROOT = 0x2, OBJC2_CLS_HIDDEN = 0x10, CLS_EXCEPTION = 0x20, /// (Obsolete) ARC-specific: this class has a .release_ivars method CLS_HAS_IVAR_RELEASER = 0x40, /// class was compiled with -fobjc-arr CLS_COMPILED_BY_ARC = 0x80 // (1<<7) }; static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result, unsigned int flags, const std::string &InstanceStart, const std::string &InstanceSize, ArrayRef<ObjCMethodDecl *>baseMethods, ArrayRef<ObjCProtocolDecl *>baseProtocols, ArrayRef<ObjCIvarDecl *>ivars, ArrayRef<ObjCPropertyDecl *>Properties, StringRef VarName, StringRef ClassName) { Result += "\nstatic struct _class_ro_t "; Result += VarName; Result += ClassName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; Result += "\t"; Result += llvm::utostr(flags); Result += ", "; Result += InstanceStart; Result += ", "; Result += InstanceSize; Result += ", \n"; Result += "\t"; const llvm::Triple &Triple(Context->getTargetInfo().getTriple()); if (Triple.getArch() == llvm::Triple::x86_64) // uint32_t const reserved; // only when building for 64bit targets Result += "(unsigned int)0, \n\t"; // const uint8_t * const ivarLayout; Result += "0, \n\t"; Result += "\""; Result += ClassName; Result += "\",\n\t"; bool metaclass = ((flags & CLS_META) != 0); if (baseMethods.size() > 0) { Result += "(const struct _method_list_t *)&"; if (metaclass) Result += "_OBJC_$_CLASS_METHODS_"; else Result += "_OBJC_$_INSTANCE_METHODS_"; Result += ClassName; Result += ",\n\t"; } else Result += "0, \n\t"; if (!metaclass && baseProtocols.size() > 0) { Result += "(const struct _objc_protocol_list *)&"; Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName; Result += ",\n\t"; } else Result += "0, \n\t"; if (!metaclass && ivars.size() > 0) { Result += "(const struct _ivar_list_t *)&"; Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName; Result += ",\n\t"; } else Result += "0, \n\t"; // weakIvarLayout Result += "0, \n\t"; if (!metaclass && Properties.size() > 0) { Result += "(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_"; Result += ClassName; Result += ",\n"; } else Result += "0, \n"; Result += "};\n"; } static void Write_class_t(ASTContext *Context, std::string &Result, StringRef VarName, const ObjCInterfaceDecl *CDecl, bool metaclass) { bool rootClass = (!CDecl->getSuperClass()); const ObjCInterfaceDecl *RootClass = CDecl; if (!rootClass) { // Find the Root class RootClass = CDecl->getSuperClass(); while (RootClass->getSuperClass()) { RootClass = RootClass->getSuperClass(); } } if (metaclass && rootClass) { // Need to handle a case of use of forward declaration. Result += "\n"; Result += "extern \"C\" "; if (CDecl->getImplementation()) Result += "__declspec(dllexport) "; else Result += "__declspec(dllimport) "; Result += "struct _class_t OBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ";\n"; } // Also, for possibility of 'super' metadata class not having been defined yet. if (!rootClass) { ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass(); Result += "\n"; Result += "extern \"C\" "; if (SuperClass->getImplementation()) Result += "__declspec(dllexport) "; else Result += "__declspec(dllimport) "; Result += "struct _class_t "; Result += VarName; Result += SuperClass->getNameAsString(); Result += ";\n"; if (metaclass && RootClass != SuperClass) { Result += "extern \"C\" "; if (RootClass->getImplementation()) Result += "__declspec(dllexport) "; else Result += "__declspec(dllimport) "; Result += "struct _class_t "; Result += VarName; Result += RootClass->getNameAsString(); Result += ";\n"; } } Result += "\nextern \"C\" __declspec(dllexport) struct _class_t "; Result += VarName; Result += CDecl->getNameAsString(); Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n"; Result += "\t"; if (metaclass) { if (!rootClass) { Result += "0, // &"; Result += VarName; Result += RootClass->getNameAsString(); Result += ",\n\t"; Result += "0, // &"; Result += VarName; Result += CDecl->getSuperClass()->getNameAsString(); Result += ",\n\t"; } else { Result += "0, // &"; Result += VarName; Result += CDecl->getNameAsString(); Result += ",\n\t"; Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ",\n\t"; } } else { Result += "0, // &OBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ",\n\t"; if (!rootClass) { Result += "0, // &"; Result += VarName; Result += CDecl->getSuperClass()->getNameAsString(); Result += ",\n\t"; } else Result += "0,\n\t"; } Result += "0, // (void *)&_objc_empty_cache,\n\t"; Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t"; if (metaclass) Result += "&_OBJC_METACLASS_RO_$_"; else Result += "&_OBJC_CLASS_RO_$_"; Result += CDecl->getNameAsString(); Result += ",\n};\n"; // Add static function to initialize some of the meta-data fields. // avoid doing it twice. if (metaclass) return; const ObjCInterfaceDecl *SuperClass = rootClass ? CDecl : CDecl->getSuperClass(); Result += "static void OBJC_CLASS_SETUP_$_"; Result += CDecl->getNameAsString(); Result += "(void ) {\n"; Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ".isa = "; Result += "&OBJC_METACLASS_$_"; Result += RootClass->getNameAsString(); Result += ";\n"; Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ".superclass = "; if (rootClass) Result += "&OBJC_CLASS_$_"; else Result += "&OBJC_METACLASS_$_"; Result += SuperClass->getNameAsString(); Result += ";\n"; Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n"; Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ".isa = "; Result += "&OBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ";\n"; if (!rootClass) { Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ".superclass = "; Result += "&OBJC_CLASS_$_"; Result += SuperClass->getNameAsString(); Result += ";\n"; } Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n"; Result += "}\n"; } static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ObjCCategoryDecl *CatDecl, ObjCInterfaceDecl *ClassDecl, ArrayRef<ObjCMethodDecl *> InstanceMethods, ArrayRef<ObjCMethodDecl *> ClassMethods, ArrayRef<ObjCProtocolDecl *> RefedProtocols, ArrayRef<ObjCPropertyDecl *> ClassProperties) { StringRef CatName = CatDecl->getName(); StringRef ClassName = ClassDecl->getName(); // must declare an extern class object in case this class is not implemented // in this TU. Result += "\n"; Result += "extern \"C\" "; if (ClassDecl->getImplementation()) Result += "__declspec(dllexport) "; else Result += "__declspec(dllimport) "; Result += "struct _class_t "; Result += "OBJC_CLASS_$_"; Result += ClassName; Result += ";\n"; Result += "\nstatic struct _category_t "; Result += "_OBJC_$_CATEGORY_"; Result += ClassName; Result += "_$_"; Result += CatName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n"; Result += "{\n"; Result += "\t\""; Result += ClassName; Result += "\",\n"; Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName; Result += ",\n"; if (InstanceMethods.size() > 0) { Result += "\t(const struct _method_list_t *)&"; Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_"; Result += ClassName; Result += "_$_"; Result += CatName; Result += ",\n"; } else Result += "\t0,\n"; if (ClassMethods.size() > 0) { Result += "\t(const struct _method_list_t *)&"; Result += "_OBJC_$_CATEGORY_CLASS_METHODS_"; Result += ClassName; Result += "_$_"; Result += CatName; Result += ",\n"; } else Result += "\t0,\n"; if (RefedProtocols.size() > 0) { Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_CATEGORY_PROTOCOLS_$_"; Result += ClassName; Result += "_$_"; Result += CatName; Result += ",\n"; } else Result += "\t0,\n"; if (ClassProperties.size() > 0) { Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_"; Result += ClassName; Result += "_$_"; Result += CatName; Result += ",\n"; } else Result += "\t0,\n"; Result += "};\n"; // Add static function to initialize the class pointer in the category structure. Result += "static void OBJC_CATEGORY_SETUP_$_"; Result += ClassDecl->getNameAsString(); Result += "_$_"; Result += CatName; Result += "(void ) {\n"; Result += "\t_OBJC_$_CATEGORY_"; Result += ClassDecl->getNameAsString(); Result += "_$_"; Result += CatName; Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName; Result += ";\n}\n"; } static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ArrayRef<ObjCMethodDecl *> Methods, StringRef VarName, StringRef ProtocolName) { if (Methods.size() == 0) return; Result += "\nstatic const char *"; Result += VarName; Result += ProtocolName; Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n"; Result += "{\n"; for (unsigned i = 0, e = Methods.size(); i < e; i++) { ObjCMethodDecl *MD = Methods[i]; std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD, true); std::string QuoteMethodTypeString; RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString); Result += "\t\""; Result += QuoteMethodTypeString; Result += "\""; if (i == e-1) Result += "\n};\n"; else { Result += ",\n"; } } } static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ArrayRef<ObjCIvarDecl *> Ivars, ObjCInterfaceDecl *CDecl) { // FIXME. visibilty of offset symbols may have to be set; for Darwin // this is what happens: /** if (Ivar->getAccessControl() == ObjCIvarDecl::Private || Ivar->getAccessControl() == ObjCIvarDecl::Package || Class->getVisibility() == HiddenVisibility) Visibility should be: HiddenVisibility; else Visibility should be: DefaultVisibility; */ Result += "\n"; for (unsigned i =0, e = Ivars.size(); i < e; i++) { ObjCIvarDecl *IvarDecl = Ivars[i]; if (Context->getLangOpts().MicrosoftExt) Result += "__declspec(allocate(\".objc_ivar$B\")) "; if (!Context->getLangOpts().MicrosoftExt || IvarDecl->getAccessControl() == ObjCIvarDecl::Private || IvarDecl->getAccessControl() == ObjCIvarDecl::Package) Result += "extern \"C\" unsigned long int "; else Result += "extern \"C\" __declspec(dllexport) unsigned long int "; if (Ivars[i]->isBitField()) RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result); else WriteInternalIvarName(CDecl, IvarDecl, Result); Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))"; Result += " = "; RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result); Result += ";\n"; if (Ivars[i]->isBitField()) { // skip over rest of the ivar bitfields. SKIP_BITFIELDS(i , e, Ivars); } } } static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ArrayRef<ObjCIvarDecl *> OriginalIvars, StringRef VarName, ObjCInterfaceDecl *CDecl) { if (OriginalIvars.size() > 0) { Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl); SmallVector<ObjCIvarDecl *, 8> Ivars; // strip off all but the first ivar bitfield from each group of ivars. // Such ivars in the ivar list table will be replaced by their grouping struct // 'ivar'. for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) { if (OriginalIvars[i]->isBitField()) { Ivars.push_back(OriginalIvars[i]); // skip over rest of the ivar bitfields. SKIP_BITFIELDS(i , e, OriginalIvars); } else Ivars.push_back(OriginalIvars[i]); } Result += "\nstatic "; Write__ivar_list_t_TypeDecl(Result, Ivars.size()); Result += " "; Result += VarName; Result += CDecl->getNameAsString(); Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n"; Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n"; for (unsigned i =0, e = Ivars.size(); i < e; i++) { ObjCIvarDecl *IvarDecl = Ivars[i]; if (i == 0) Result += "\t{{"; else Result += "\t {"; Result += "(unsigned long int *)&"; if (Ivars[i]->isBitField()) RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result); else WriteInternalIvarName(CDecl, IvarDecl, Result); Result += ", "; Result += "\""; if (Ivars[i]->isBitField()) RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result); else Result += IvarDecl->getName(); Result += "\", "; QualType IVQT = IvarDecl->getType(); if (IvarDecl->isBitField()) IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl); std::string IvarTypeString, QuoteIvarTypeString; Context->getObjCEncodingForType(IVQT, IvarTypeString, IvarDecl); RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString); Result += "\""; Result += QuoteIvarTypeString; Result += "\", "; // FIXME. this alignment represents the host alignment and need be changed to // represent the target alignment. unsigned Align = Context->getTypeAlign(IVQT)/8; Align = llvm::Log2_32(Align); Result += llvm::utostr(Align); Result += ", "; CharUnits Size = Context->getTypeSizeInChars(IVQT); Result += llvm::utostr(Size.getQuantity()); if (i == e-1) Result += "}}\n"; else Result += "},\n"; } Result += "};\n"; } } /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data. void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, std::string &Result) { // Do not synthesize the protocol more than once. if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl())) return; WriteModernMetadataDeclarations(Context, Result); if (ObjCProtocolDecl *Def = PDecl->getDefinition()) PDecl = Def; // Must write out all protocol definitions in current qualifier list, // and in their nested qualifiers before writing out current definition. for (auto *I : PDecl->protocols()) RewriteObjCProtocolMetaData(I, Result); // Construct method lists. std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods; std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods; for (auto *MD : PDecl->instance_methods()) { if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { OptInstanceMethods.push_back(MD); } else { InstanceMethods.push_back(MD); } } for (auto *MD : PDecl->class_methods()) { if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { OptClassMethods.push_back(MD); } else { ClassMethods.push_back(MD); } } std::vector<ObjCMethodDecl *> AllMethods; for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++) AllMethods.push_back(InstanceMethods[i]); for (unsigned i = 0, e = ClassMethods.size(); i < e; i++) AllMethods.push_back(ClassMethods[i]); for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++) AllMethods.push_back(OptInstanceMethods[i]); for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++) AllMethods.push_back(OptClassMethods[i]); Write__extendedMethodTypes_initializer(*this, Context, Result, AllMethods, "_OBJC_PROTOCOL_METHOD_TYPES_", PDecl->getNameAsString()); // Protocol's super protocol list SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols()); Write_protocol_list_initializer(Context, Result, SuperProtocols, "_OBJC_PROTOCOL_REFS_", PDecl->getNameAsString()); Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, "_OBJC_PROTOCOL_INSTANCE_METHODS_", PDecl->getNameAsString(), false); Write_method_list_t_initializer(*this, Context, Result, ClassMethods, "_OBJC_PROTOCOL_CLASS_METHODS_", PDecl->getNameAsString(), false); Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods, "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_", PDecl->getNameAsString(), false); Write_method_list_t_initializer(*this, Context, Result, OptClassMethods, "_OBJC_PROTOCOL_OPT_CLASS_METHODS_", PDecl->getNameAsString(), false); // Protocol's property metadata. SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties( PDecl->instance_properties()); Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties, /* Container */nullptr, "_OBJC_PROTOCOL_PROPERTIES_", PDecl->getNameAsString()); // Writer out root metadata for current protocol: struct _protocol_t Result += "\n"; if (LangOpts.MicrosoftExt) Result += "static "; Result += "struct _protocol_t _OBJC_PROTOCOL_"; Result += PDecl->getNameAsString(); Result += " __attribute__ ((used)) = {\n"; Result += "\t0,\n"; // id is; is null Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n"; if (SuperProtocols.size() > 0) { Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; if (InstanceMethods.size() > 0) { Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; if (ClassMethods.size() > 0) { Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; if (OptInstanceMethods.size() > 0) { Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; if (OptClassMethods.size() > 0) { Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; if (ProtocolProperties.size() > 0) { Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n"; Result += "\t0,\n"; if (AllMethods.size() > 0) { Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_"; Result += PDecl->getNameAsString(); Result += "\n};\n"; } else Result += "\t0\n};\n"; if (LangOpts.MicrosoftExt) Result += "static "; Result += "struct _protocol_t *"; Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString(); Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString(); Result += ";\n"; // Mark this protocol as having been generated. if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second) llvm_unreachable("protocol already synthesized"); } /// hasObjCExceptionAttribute - Return true if this class or any super /// class has the __objc_exception__ attribute. /// FIXME. Move this to ASTContext.cpp as it is also used for IRGen. static bool hasObjCExceptionAttribute(ASTContext &Context, const ObjCInterfaceDecl *OID) { if (OID->hasAttr<ObjCExceptionAttr>()) return true; if (const ObjCInterfaceDecl *Super = OID->getSuperClass()) return hasObjCExceptionAttribute(Context, Super); return false; } void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, std::string &Result) { ObjCInterfaceDecl *CDecl = IDecl->getClassInterface(); // Explicitly declared @interface's are already synthesized. if (CDecl->isImplicitInterfaceDecl()) assert(false && "Legacy implicit interface rewriting not supported in moder abi"); WriteModernMetadataDeclarations(Context, Result); SmallVector<ObjCIvarDecl *, 8> IVars; for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) { // Ignore unnamed bit-fields. if (!IVD->getDeclName()) continue; IVars.push_back(IVD); } Write__ivar_list_t_initializer(*this, Context, Result, IVars, "_OBJC_$_INSTANCE_VARIABLES_", CDecl); // Build _objc_method_list for class's instance methods if needed SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods()); // If any of our property implementations have associated getters or // setters, produce metadata for them as well. for (const auto *Prop : IDecl->property_impls()) { if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) continue; if (!Prop->getPropertyIvarDecl()) continue; ObjCPropertyDecl *PD = Prop->getPropertyDecl(); if (!PD) continue; if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl()) if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/)) InstanceMethods.push_back(Getter); if (PD->isReadOnly()) continue; if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl()) if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/)) InstanceMethods.push_back(Setter); } Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, "_OBJC_$_INSTANCE_METHODS_", IDecl->getNameAsString(), true); SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods()); Write_method_list_t_initializer(*this, Context, Result, ClassMethods, "_OBJC_$_CLASS_METHODS_", IDecl->getNameAsString(), true); // Protocols referenced in class declaration? // Protocol's super protocol list std::vector<ObjCProtocolDecl *> RefedProtocols; const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols(); for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), E = Protocols.end(); I != E; ++I) { RefedProtocols.push_back(*I); // Must write out all protocol definitions in current qualifier list, // and in their nested qualifiers before writing out current definition. RewriteObjCProtocolMetaData(*I, Result); } Write_protocol_list_initializer(Context, Result, RefedProtocols, "_OBJC_CLASS_PROTOCOLS_$_", IDecl->getNameAsString()); // Protocol's property metadata. SmallVector<ObjCPropertyDecl *, 8> ClassProperties( CDecl->instance_properties()); Write_prop_list_t_initializer(*this, Context, Result, ClassProperties, /* Container */IDecl, "_OBJC_$_PROP_LIST_", CDecl->getNameAsString()); // Data for initializing _class_ro_t metaclass meta-data uint32_t flags = CLS_META; std::string InstanceSize; std::string InstanceStart; bool classIsHidden = CDecl->getVisibility() == HiddenVisibility; if (classIsHidden) flags |= OBJC2_CLS_HIDDEN; if (!CDecl->getSuperClass()) // class is root flags |= CLS_ROOT; InstanceSize = "sizeof(struct _class_t)"; InstanceStart = InstanceSize; Write__class_ro_t_initializer(Context, Result, flags, InstanceStart, InstanceSize, ClassMethods, nullptr, nullptr, nullptr, "_OBJC_METACLASS_RO_$_", CDecl->getNameAsString()); // Data for initializing _class_ro_t meta-data flags = CLS; if (classIsHidden) flags |= OBJC2_CLS_HIDDEN; if (hasObjCExceptionAttribute(*Context, CDecl)) flags |= CLS_EXCEPTION; if (!CDecl->getSuperClass()) // class is root flags |= CLS_ROOT; InstanceSize.clear(); InstanceStart.clear(); if (!ObjCSynthesizedStructs.count(CDecl)) { InstanceSize = "0"; InstanceStart = "0"; } else { InstanceSize = "sizeof(struct "; InstanceSize += CDecl->getNameAsString(); InstanceSize += "_IMPL)"; ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); if (IVD) { RewriteIvarOffsetComputation(IVD, InstanceStart); } else InstanceStart = InstanceSize; } Write__class_ro_t_initializer(Context, Result, flags, InstanceStart, InstanceSize, InstanceMethods, RefedProtocols, IVars, ClassProperties, "_OBJC_CLASS_RO_$_", CDecl->getNameAsString()); Write_class_t(Context, Result, "OBJC_METACLASS_$_", CDecl, /*metaclass*/true); Write_class_t(Context, Result, "OBJC_CLASS_$_", CDecl, /*metaclass*/false); if (ImplementationIsNonLazy(IDecl)) DefinedNonLazyClasses.push_back(CDecl); } void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) { int ClsDefCount = ClassImplementation.size(); if (!ClsDefCount) return; Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n"; Result += "__declspec(allocate(\".objc_inithooks$B\")) "; Result += "static void *OBJC_CLASS_SETUP[] = {\n"; for (int i = 0; i < ClsDefCount; i++) { ObjCImplementationDecl *IDecl = ClassImplementation[i]; ObjCInterfaceDecl *CDecl = IDecl->getClassInterface(); Result += "\t(void *)&OBJC_CLASS_SETUP_$_"; Result += CDecl->getName(); Result += ",\n"; } Result += "};\n"; } void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) { int ClsDefCount = ClassImplementation.size(); int CatDefCount = CategoryImplementation.size(); // For each implemented class, write out all its meta data. for (int i = 0; i < ClsDefCount; i++) RewriteObjCClassMetaData(ClassImplementation[i], Result); RewriteClassSetupInitHook(Result); // For each implemented category, write out all its meta data. for (int i = 0; i < CatDefCount; i++) RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result); RewriteCategorySetupInitHook(Result); if (ClsDefCount > 0) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_classlist$B\")) "; Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ ["; Result += llvm::utostr(ClsDefCount); Result += "]"; Result += " __attribute__((used, section (\"__DATA, __objc_classlist," "regular,no_dead_strip\")))= {\n"; for (int i = 0; i < ClsDefCount; i++) { Result += "\t&OBJC_CLASS_$_"; Result += ClassImplementation[i]->getNameAsString(); Result += ",\n"; } Result += "};\n"; if (!DefinedNonLazyClasses.empty()) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n"; Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t"; for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) { Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString(); Result += ",\n"; } Result += "};\n"; } } if (CatDefCount > 0) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_catlist$B\")) "; Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ ["; Result += llvm::utostr(CatDefCount); Result += "]"; Result += " __attribute__((used, section (\"__DATA, __objc_catlist," "regular,no_dead_strip\")))= {\n"; for (int i = 0; i < CatDefCount; i++) { Result += "\t&_OBJC_$_CATEGORY_"; Result += CategoryImplementation[i]->getClassInterface()->getNameAsString(); Result += "_$_"; Result += CategoryImplementation[i]->getNameAsString(); Result += ",\n"; } Result += "};\n"; } if (!DefinedNonLazyCategories.empty()) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n"; Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t"; for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) { Result += "\t&_OBJC_$_CATEGORY_"; Result += DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString(); Result += "_$_"; Result += DefinedNonLazyCategories[i]->getNameAsString(); Result += ",\n"; } Result += "};\n"; } } void RewriteModernObjC::WriteImageInfo(std::string &Result) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n"; Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } "; // version 0, ObjCABI is 2 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n"; } /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category /// implementation. void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, std::string &Result) { WriteModernMetadataDeclarations(Context, Result); ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface(); // Find category declaration for this implementation. ObjCCategoryDecl *CDecl = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier()); std::string FullCategoryName = ClassDecl->getNameAsString(); FullCategoryName += "_$_"; FullCategoryName += CDecl->getNameAsString(); // Build _objc_method_list for class's instance methods if needed SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods()); // If any of our property implementations have associated getters or // setters, produce metadata for them as well. for (const auto *Prop : IDecl->property_impls()) { if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) continue; if (!Prop->getPropertyIvarDecl()) continue; ObjCPropertyDecl *PD = Prop->getPropertyDecl(); if (!PD) continue; if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl()) InstanceMethods.push_back(Getter); if (PD->isReadOnly()) continue; if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl()) InstanceMethods.push_back(Setter); } Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, "_OBJC_$_CATEGORY_INSTANCE_METHODS_", FullCategoryName, true); SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods()); Write_method_list_t_initializer(*this, Context, Result, ClassMethods, "_OBJC_$_CATEGORY_CLASS_METHODS_", FullCategoryName, true); // Protocols referenced in class declaration? // Protocol's super protocol list SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols()); for (auto *I : CDecl->protocols()) // Must write out all protocol definitions in current qualifier list, // and in their nested qualifiers before writing out current definition. RewriteObjCProtocolMetaData(I, Result); Write_protocol_list_initializer(Context, Result, RefedProtocols, "_OBJC_CATEGORY_PROTOCOLS_$_", FullCategoryName); // Protocol's property metadata. SmallVector<ObjCPropertyDecl *, 8> ClassProperties( CDecl->instance_properties()); Write_prop_list_t_initializer(*this, Context, Result, ClassProperties, /* Container */IDecl, "_OBJC_$_PROP_LIST_", FullCategoryName); Write_category_t(*this, Context, Result, CDecl, ClassDecl, InstanceMethods, ClassMethods, RefedProtocols, ClassProperties); // Determine if this category is also "non-lazy". if (ImplementationIsNonLazy(IDecl)) DefinedNonLazyCategories.push_back(CDecl); } void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) { int CatDefCount = CategoryImplementation.size(); if (!CatDefCount) return; Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n"; Result += "__declspec(allocate(\".objc_inithooks$B\")) "; Result += "static void *OBJC_CATEGORY_SETUP[] = {\n"; for (int i = 0; i < CatDefCount; i++) { ObjCCategoryImplDecl *IDecl = CategoryImplementation[i]; ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl(); ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface(); Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_"; Result += ClassDecl->getName(); Result += "_$_"; Result += CatDecl->getName(); Result += ",\n"; } Result += "};\n"; } // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or /// class methods. template<typename MethodIterator> void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin, MethodIterator MethodEnd, bool IsInstanceMethod, StringRef prefix, StringRef ClassName, std::string &Result) { if (MethodBegin == MethodEnd) return; if (!objc_impl_method) { /* struct _objc_method { SEL _cmd; char *method_types; void *_imp; } */ Result += "\nstruct _objc_method {\n"; Result += "\tSEL _cmd;\n"; Result += "\tchar *method_types;\n"; Result += "\tvoid *_imp;\n"; Result += "};\n"; objc_impl_method = true; } // Build _objc_method_list for class's methods if needed /* struct { struct _objc_method_list *next_method; int method_count; struct _objc_method method_list[]; } */ unsigned NumMethods = std::distance(MethodBegin, MethodEnd); Result += "\n"; if (LangOpts.MicrosoftExt) { if (IsInstanceMethod) Result += "__declspec(allocate(\".inst_meth$B\")) "; else Result += "__declspec(allocate(\".cls_meth$B\")) "; } Result += "static struct {\n"; Result += "\tstruct _objc_method_list *next_method;\n"; Result += "\tint method_count;\n"; Result += "\tstruct _objc_method method_list["; Result += utostr(NumMethods); Result += "];\n} _OBJC_"; Result += prefix; Result += IsInstanceMethod ? "INSTANCE" : "CLASS"; Result += "_METHODS_"; Result += ClassName; Result += " __attribute__ ((used, section (\"__OBJC, __"; Result += IsInstanceMethod ? "inst" : "cls"; Result += "_meth\")))= "; Result += "{\n\t0, " + utostr(NumMethods) + "\n"; Result += "\t,{{(SEL)\""; Result += (*MethodBegin)->getSelector().getAsString().c_str(); std::string MethodTypeString; Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString); Result += "\", \""; Result += MethodTypeString; Result += "\", (void *)"; Result += MethodInternalNames[*MethodBegin]; Result += "}\n"; for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) { Result += "\t ,{(SEL)\""; Result += (*MethodBegin)->getSelector().getAsString().c_str(); std::string MethodTypeString; Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString); Result += "\", \""; Result += MethodTypeString; Result += "\", (void *)"; Result += MethodInternalNames[*MethodBegin]; Result += "}\n"; } Result += "\t }\n};\n"; } Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { SourceRange OldRange = IV->getSourceRange(); Expr *BaseExpr = IV->getBase(); // Rewrite the base, but without actually doing replaces. { DisableReplaceStmtScope S(*this); BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr)); IV->setBase(BaseExpr); } ObjCIvarDecl *D = IV->getDecl(); Expr *Replacement = IV; if (BaseExpr->getType()->isObjCObjectPointerType()) { const ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType()); assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null"); // lookup which class implements the instance variable. ObjCInterfaceDecl *clsDeclared = nullptr; iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared); assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class"); // Build name of symbol holding ivar offset. std::string IvarOffsetName; if (D->isBitField()) ObjCIvarBitfieldGroupOffset(D, IvarOffsetName); else WriteInternalIvarName(clsDeclared, D, IvarOffsetName); ReferencedIvars[clsDeclared].insert(D); // cast offset to "char *". CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(Context->CharTy), CK_BitCast, BaseExpr); VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(IvarOffsetName), Context->UnsignedLongTy, nullptr, SC_Extern); DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, NewVD, false, Context->UnsignedLongTy, VK_LValue, SourceLocation()); BinaryOperator *addExpr = BinaryOperator::Create( *Context, castExpr, DRE, BO_Add, Context->getPointerType(Context->CharTy), VK_PRValue, OK_Ordinary, SourceLocation(), FPOptionsOverride()); // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), addExpr); QualType IvarT = D->getType(); if (D->isBitField()) IvarT = GetGroupRecordTypeForObjCIvarBitfield(D); if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) { RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl(); RD = RD->getDefinition(); if (RD && !RD->getDeclName().getAsIdentifierInfo()) { // decltype(((Foo_IMPL*)0)->bar) * auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext()); // ivar in class extensions requires special treatment. if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) CDecl = CatDecl->getClassInterface(); std::string RecName = std::string(CDecl->getName()); RecName += "_IMPL"; RecordDecl *RD = RecordDecl::Create( *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(RecName)); QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD)); unsigned UnsignedIntSize = static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); Expr *Zero = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, 0), Context->UnsignedIntTy, SourceLocation()); Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero); ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), Zero); FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get(D->getNameAsString()), IvarT, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); MemberExpr *ME = MemberExpr::CreateImplicit( *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary); IvarT = Context->getDecltypeType(ME, ME->getType()); } } convertObjCTypeToCStyleType(IvarT); QualType castT = Context->getPointerType(IvarT); castExpr = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, PE); Expr *Exp = UnaryOperator::Create( const_cast<ASTContext &>(*Context), castExpr, UO_Deref, IvarT, VK_LValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); PE = new (Context) ParenExpr(OldRange.getBegin(), OldRange.getEnd(), Exp); if (D->isBitField()) { FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get(D->getNameAsString()), D->getType(), nullptr, /*BitWidth=*/D->getBitWidth(), /*Mutable=*/true, ICIS_NoInit); MemberExpr *ME = MemberExpr::CreateImplicit(*Context, PE, /*isArrow*/ false, FD, FD->getType(), VK_LValue, OK_Ordinary); Replacement = ME; } else Replacement = PE; } ReplaceStmtWithRange(IV, Replacement, OldRange); return Replacement; } #endif // CLANG_ENABLE_OBJC_REWRITER
39.018758
106
0.620133
opencor
b4494d3c379922e1b05f749db7019ecd052782ba
12,199
cpp
C++
ext/libr2tao/required.cpp
jwillemsen/r2corba
c9d32d15b00e3421c00c5a65c9a12bcf2d7beff5
[ "BSD-3-Clause" ]
1
2022-03-07T19:43:43.000Z
2022-03-07T19:43:43.000Z
ext/libr2tao/required.cpp
RemedyIT/r2corba
c65215dd70fb9597d694236b8f3c72890bd827d8
[ "BSD-3-Clause" ]
16
2019-12-02T15:14:52.000Z
2022-03-02T13:22:19.000Z
ext/libr2tao/required.cpp
jwillemsen/r2corba
c9d32d15b00e3421c00c5a65c9a12bcf2d7beff5
[ "BSD-3-Clause" ]
4
2019-11-12T15:14:38.000Z
2021-04-27T11:51:57.000Z
/*-------------------------------------------------------------------- # required.h - R2TAO CORBA basic support # # Author: Martin Corino # # This program is free software; you can redistribute it and/or # modify it under the terms of the R2CORBA LICENSE which is # included with this program. # # Copyright (c) Remedy IT Expertise BV #------------------------------------------------------------------*/ #include "required.h" #include "exception.h" #include "typecode.h" #include "ace/Env_Value_T.h" #include "ace/Null_Mutex.h" #include "ace/Singleton.h" #include "ace/TSS_T.h" #include "tao/AnyTypeCode/Any.h" #include "tao/DynamicInterface/Unknown_User_Exception.h" #include "tao/debug.h" #include <memory> #define RUBY_INVOKE_FUNC RUBY_ALLOC_FUNC R2TAO_EXPORT VALUE r2tao_nsCORBA = 0; R2TAO_EXPORT VALUE r2tao_nsCORBA_Native = 0; extern void r2tao_Init_Exception(); extern void r2tao_Init_Object(); extern void r2tao_Init_ORB(); extern void r2tao_Init_Typecode(); extern void r2tao_init_Values(); class R2TAO_ObjectRegistry { friend class ACE_Singleton<R2TAO_ObjectRegistry, ACE_Null_Mutex>; private: R2TAO_ObjectRegistry() : registry_ (Qnil) { // create an anchoring object R2TAO_ObjectRegistry::registry_anchor_ = Data_Wrap_Struct (rb_cObject, 0, R2TAO_ObjectRegistry::registry_free, this); // prevent GC while Ruby lives rb_gc_register_address (&R2TAO_ObjectRegistry::registry_anchor_); // create registry Hash this->registry_ = rb_hash_new (); // create an instance variable to hold registry (prevents GC since anchor is registered) rb_ivar_set (R2TAO_ObjectRegistry::registry_anchor_, rb_intern ("@registry_"), this->registry_); R2TAO_ObjectRegistry::has_singleton_ = true; } static VALUE registry_anchor_; static bool has_singleton_; public: ~R2TAO_ObjectRegistry() { // no need to unregister; as we live as long as Ruby does // we had better let Ruby take care of cleaning up otherwise // we may end up in a race condition // Just mark the registry as destroyed R2TAO_ObjectRegistry::has_singleton_ = false; this->registry_ = Qnil; } void register_object (VALUE rbobj) { if (TAO_debug_level > 9) ACE_DEBUG ((LM_INFO, "R2TAO (%P|%t) - R2TAO_ObjectRegistry::register_object(%@) - reg=%@\n", rbobj, this->registry_)); if (!NIL_P(this->registry_)) { rb_hash_aset (this->registry_, rbobj, rbobj); } else { if (TAO_debug_level > 1) ACE_DEBUG ((LM_INFO, "R2TAO (%P|%t) - R2TAO_ObjectRegistry::register_object(%@) - " "not registring since registry is nil\n", rbobj)); } } void unregister_object (VALUE rbobj) { if (TAO_debug_level > 9) ACE_DEBUG ((LM_INFO, "R2TAO (%P|%t) - R2TAO_ObjectRegistry::unregister_object(%@) - reg=%@\n", rbobj, this->registry_)); if (!NIL_P(this->registry_)) { rb_hash_delete (this->registry_, rbobj); } } static bool has_singleton (); private: VALUE registry_; void clear_registry () { this->registry_ = Qnil; } static void registry_free(void *ptr) { // what came first? is registry singleton still there? if (R2TAO_ObjectRegistry::has_singleton ()) { // registry anchor is being GC-ed so clean up to prevent illegal access R2TAO_ObjectRegistry* objreg = reinterpret_cast<R2TAO_ObjectRegistry*> (ptr); objreg->clear_registry (); } } }; VALUE R2TAO_ObjectRegistry::registry_anchor_ = Qnil; bool R2TAO_ObjectRegistry::has_singleton_ = false; bool R2TAO_ObjectRegistry::has_singleton () { return R2TAO_ObjectRegistry::has_singleton_; } typedef ACE_Singleton<R2TAO_ObjectRegistry, ACE_Null_Mutex> R2TAO_OBJECTREGISTRY; #if defined(WIN32) && defined(_DEBUG) extern "C" R2TAO_EXPORT void Init_libr2taod() #else extern "C" R2TAO_EXPORT void Init_libr2tao() #endif { rb_eval_string("puts 'Init_libr2tao start' if $VERBOSE"); if (r2tao_nsCORBA) return; // TAO itself only does this when an ORB is initialized; we want it sooner if (TAO_debug_level <= 0) TAO_debug_level = ACE_Env_Value<u_int> ("TAO_ORB_DEBUG", 0); rb_eval_string("puts 'Init_libr2tao 2' if $VERBOSE"); VALUE klass = rb_define_module_under (rb_eval_string ("::R2CORBA"), "TAO"); rb_define_const (klass, "MAJOR_VERSION", INT2NUM (TAO_MAJOR_VERSION)); rb_define_const (klass, "MINOR_VERSION", INT2NUM (TAO_MINOR_VERSION)); rb_define_const (klass, "MICRO_VERSION", INT2NUM (TAO_MICRO_VERSION)); rb_define_const (klass, "VERSION", rb_str_new2 (TAO_VERSION)); rb_define_const (klass, "RUBY_THREAD_SUPPORT", #ifdef R2TAO_THREAD_SAFE Qtrue #else Qfalse #endif ); r2tao_nsCORBA = rb_eval_string("::R2CORBA::CORBA"); r2tao_nsCORBA_Native = rb_define_module_under (r2tao_nsCORBA, "Native"); rb_eval_string("puts 'Init_libr2tao r2tao_Init_Exception' if $VERBOSE"); r2tao_Init_Exception(); rb_eval_string("puts 'Init_libr2tao r2tao_Init_Object' if $VERBOSE"); r2tao_Init_Object(); rb_eval_string("puts 'Init_libr2tao r2tao_Init_ORB' if $VERBOSE"); r2tao_Init_ORB(); rb_eval_string("puts 'Init_libr2tao r2tao_Init_Typecode' if $VERBOSE"); r2tao_Init_Typecode(); rb_eval_string("puts 'Init_libr2tao r2tao_Init_Values' if $VERBOSE"); r2tao_init_Values(); } R2TAO_EXPORT void r2tao_check_type(VALUE x, VALUE t) { if (rb_obj_is_kind_of(x, t) != Qtrue) { VALUE rb_dump = rb_funcall (x, rb_intern ("inspect"), 0); rb_raise(r2tao_cBAD_PARAM, "wrong argument type %s (expected %s)\n", RSTRING_PTR(rb_dump), rb_class2name(t)); } } R2TAO_EXPORT void r2tao_register_object(VALUE rbobj) { R2TAO_OBJECTREGISTRY::instance ()->register_object (rbobj); } R2TAO_EXPORT void r2tao_unregister_object(VALUE rbobj) { if (R2TAO_ObjectRegistry::has_singleton ()) { R2TAO_OBJECTREGISTRY::instance ()->unregister_object (rbobj); } } #if defined (R2TAO_THREAD_SAFE) class R2TAO_GVLGuard { public: R2TAO_GVLGuard (bool lock=true) : lock_(lock) { TSSManager::set_indicator (this->lock_); } ~R2TAO_GVLGuard () { TSSManager::set_indicator (!this->lock_); } static bool gvl_locked (bool start_locked=false) { if (start_locked && !TSSManager::has_indicator ()) { TSSManager::set_indicator (start_locked); } return TSSManager::indicator (); } private: bool lock_; class TSSManager { public: TSSManager () { gvl_indicator_ = new ACE_TSS< ACE_TSS_Type_Adapter<u_int> > (); } ~TSSManager () { delete gvl_indicator_; gvl_indicator_ = nullptr; } static void set_indicator (bool val) { if (gvl_indicator_) (*gvl_indicator_)->operator u_int & () = (val ? 1 : 0); } static bool has_indicator () { return (gvl_indicator_ && (*gvl_indicator_).ts_object ()); } static bool indicator () { // if the TSS storage has alredy been destroyed we're in the exit procedure and the // GVL is always locked return (gvl_indicator_ == 0 || (*gvl_indicator_)->operator u_int () == 1); } private: static ACE_TSS< ACE_TSS_Type_Adapter<u_int> >* gvl_indicator_; }; static TSSManager tss_gvl_flag_; }; ACE_TSS< ACE_TSS_Type_Adapter<u_int> >* R2TAO_GVLGuard::TSSManager::gvl_indicator_; R2TAO_GVLGuard::TSSManager R2TAO_GVLGuard::tss_gvl_flag_; template <typename FTYPE> struct r2tao_gvl_call_arg { r2tao_gvl_call_arg (FTYPE func, void* data) : func_ (func), data_ (data) {} FTYPE func_; void* data_; }; void* r2tao_call_with_gvl (void *data) { R2TAO_GVLGuard gvl_guard_; r2tao_gvl_call_arg<void*(*)(void*)>& arg = *reinterpret_cast<r2tao_gvl_call_arg<void*(*)(void*)>*> (data); return (*arg.func_) (arg.data_); } void* r2tao_call_without_gvl (void *data) { R2TAO_GVLGuard gvl_guard_ (false); r2tao_gvl_call_arg<void*(*)(void*)>& arg = *reinterpret_cast<r2tao_gvl_call_arg<void*(*)(void*)>*> (data); return (*arg.func_) (arg.data_); } #endif R2TAO_EXPORT void* r2tao_call_thread_safe (void *(*func)(void *), void *data) { #if defined (R2TAO_THREAD_SAFE) if (!R2TAO_GVLGuard::gvl_locked ()) { r2tao_gvl_call_arg<void*(*)(void*)> arg(func, data); return rb_thread_call_with_gvl(r2tao_call_with_gvl, &arg); } #endif return (*func) (data); } R2TAO_EXPORT VALUE r2tao_blocking_call (VALUE (*func)(void*), void*data) { #if defined (R2TAO_THREAD_SAFE) if (R2TAO_GVLGuard::gvl_locked (true)) { r2tao_gvl_call_arg<VALUE(*)(void*)> arg(func, data); void *rc = rb_thread_call_without_gvl(r2tao_call_without_gvl, &arg, RUBY_UBF_IO, 0); return reinterpret_cast<VALUE> (rc); } #endif return (*func) (data); } R2TAO_EXPORT VALUE r2tao_blocking_call_ex (VALUE (*func)(void*), void*data, void (*unblock_func)(void*), void*unblock_data) { #if defined (R2TAO_THREAD_SAFE) if (R2TAO_GVLGuard::gvl_locked (true)) { r2tao_gvl_call_arg<VALUE(*)(void*)> arg(func, data); void *rc = rb_thread_call_without_gvl(r2tao_call_without_gvl, &arg, unblock_func, unblock_data); return reinterpret_cast<VALUE> (rc); } #else ACE_UNUSED_ARG(unblock_func); ACE_UNUSED_ARG(unblock_data); #endif return (*func) (data); } R2TAO_RBFuncall::R2TAO_RBFuncall (ID fnid, bool throw_on_ex) : fn_id_ (fnid), throw_on_ex_ (throw_on_ex), ex_caught_ (false) { } R2TAO_RBFuncall::R2TAO_RBFuncall (const char* fn, bool throw_on_ex) : fn_id_ (rb_intern (fn)), throw_on_ex_ (throw_on_ex), ex_caught_ (false) { } VALUE R2TAO_RBFuncall::invoke (VALUE rcvr, VALUE args) { return this->_invoke (FuncArgArray (rcvr, args)); } VALUE R2TAO_RBFuncall::invoke (VALUE rcvr, int argc, VALUE *args) { return this->_invoke (FuncArgList (rcvr, argc, args)); } VALUE R2TAO_RBFuncall::invoke (VALUE rcvr) { return this->_invoke (FuncArgList (rcvr, 0, 0)); } VALUE R2TAO_RBFuncall::_invoke (const FuncArgs& fa) { static ID interface_repository_id_ID = rb_intern ("_interface_repository_id");; this->ex_caught_ = false; // reset int invoke_state = 0; HelperArgs ha (*this, fa); VALUE result = rb_protect (RUBY_INVOKE_FUNC (R2TAO_RBFuncall::invoke_helper), (VALUE)&ha, &invoke_state); if (invoke_state) { if (this->throw_on_ex_) { // handle exception VALUE rexc = rb_gv_get ("$!"); if (rb_obj_is_kind_of(rexc, r2tao_cUserException) == Qtrue) { VALUE rextc = rb_eval_string ("R2CORBA::CORBA::Any.typecode_for_any ($!)"); if (rextc != Qnil) { CORBA::Any _xval; CORBA::TypeCode_ptr _xtc = r2corba_TypeCode_r2t (rextc); r2tao_Ruby2Any(_xval, _xtc, rexc); throw ::CORBA::UnknownUserException (_xval); } } if (rb_obj_is_kind_of(rexc, r2tao_cSystemException) == Qtrue) { VALUE rid = rb_funcall (rexc, interface_repository_id_ID, 0); CORBA::SystemException* _exc = TAO::create_system_exception (RSTRING_PTR (rid)); _exc->minor ( static_cast<CORBA::ULong> (NUM2ULONG (rb_iv_get (rexc, "@minor")))); _exc->completed ( static_cast<CORBA::CompletionStatus> (NUM2ULONG (rb_iv_get (rexc, "@completed")))); std::unique_ptr<CORBA::SystemException> e_ptr(_exc); _exc->_raise (); } else { rb_eval_string ("STDERR.puts $!.to_s+\"\\n\"+$!.backtrace.join(\"\\n\")"); throw ::CORBA::UNKNOWN (0, CORBA::COMPLETED_MAYBE); } } else { this->ex_caught_ = true; } } else { return result; } return Qnil; } VALUE R2TAO_RBFuncall::FuncArgArray::rb_invoke (ID fnid) const { return rb_apply (this->receiver_, fnid, this->args_); } VALUE R2TAO_RBFuncall::FuncArgList::rb_invoke (ID fnid) const { return rb_funcall2 (this->receiver_, fnid, this->argc_, this->args_); } VALUE R2TAO_RBFuncall::invoke_inner (const FuncArgs& fnargs) { return fnargs.rb_invoke (this->fn_id_); } VALUE R2TAO_RBFuncall::invoke_helper (VALUE arg) { HelperArgs* ha = reinterpret_cast<HelperArgs*> (arg); return ha->caller_.invoke_inner (ha->fnargs_); }
27.725
126
0.677924
jwillemsen