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
08e03811b4b6fef2210c8cbc0245664a09e52dcc
1,434
cpp
C++
main/c++-class-templates/c-class-templates.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/c++-class-templates/c-class-templates.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/c++-class-templates/c-class-templates.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <cassert> using namespace std; namespace { template <typename T> class AddElements final { public: explicit AddElements(const T elem1) : elem1_{elem1} { } T add(const T elem2) { return elem1_ + elem2; } private: const T elem1_; }; template <> class AddElements<string> final { public: explicit AddElements(const string& elem1) : elem1_{elem1} { } string concatenate(const string& elem2) { return elem1_ + elem2; } private: const string elem1_; }; } // code from HackerRank (not to be modified while completing this exercise) int main () { int n,i; cin >> n; for(i=0;i<n;i++) { string type; cin >> type; if(type=="float") { double element1,element2; cin >> element1 >> element2; AddElements<double> myfloat (element1); cout << myfloat.add(element2) << endl; } else if(type == "int") { int element1, element2; cin >> element1 >> element2; AddElements<int> myint (element1); cout << myint.add(element2) << endl; } else if(type == "string") { string element1, element2; cin >> element1 >> element2; AddElements<string> mystring (element1); cout << mystring.concatenate(element2) << endl; } } return 0; }
24.305085
75
0.593445
EliahKagan
08e08cd072855ce935cf1840a2215b955421a32e
953
hpp
C++
color_detector/leds.hpp
Merryashji/TI-Individual-Propedeuse-Assessment
a9fccff323a4a667811c9917ef7d1b5c1237e478
[ "BSL-1.0" ]
null
null
null
color_detector/leds.hpp
Merryashji/TI-Individual-Propedeuse-Assessment
a9fccff323a4a667811c9917ef7d1b5c1237e478
[ "BSL-1.0" ]
null
null
null
color_detector/leds.hpp
Merryashji/TI-Individual-Propedeuse-Assessment
a9fccff323a4a667811c9917ef7d1b5c1237e478
[ "BSL-1.0" ]
null
null
null
#ifndef LEDS_HPP #define LEDS_HPP #include "hwlib.hpp" /// @file /// \brief /// leds class /// \details /// This is a class for color for 5 leds. class leds{ private: hwlib::pin_out & l1; hwlib::pin_out & l2; hwlib::pin_out & l3; hwlib::pin_out & l4; hwlib::pin_out & l5; /// \brief /// class public /// \details /// the public part contains the constructor of the leds color and the member functions. public: leds( hwlib::pin_out & l1 , hwlib::pin_out & l2 , hwlib::pin_out & l3 , hwlib::pin_out & l4 , hwlib::pin_out & l5): l1(l1), l2(l2) , l3(l3) , l4(l4) , l5(l5){} /// \brief /// show_color /// \details /// this function has a char parameter. According to this values the function turns the actual color led on. void show_color(char color ); /// \brief /// reset /// \details /// this function turns all the leds off. void reset(); }; #endif
20.276596
112
0.593914
Merryashji
08e1655a6ea40ca41ee8bd4ca653e5c30640d026
1,274
cpp
C++
src/math/tests/test_libaeon_math/test_size2d.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
7
2017-02-19T16:22:16.000Z
2021-03-02T05:47:39.000Z
src/math/tests/test_libaeon_math/test_size2d.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
61
2017-05-29T06:11:17.000Z
2021-03-28T21:51:44.000Z
src/math/tests/test_libaeon_math/test_size2d.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
2
2017-05-28T17:17:40.000Z
2017-07-14T21:45:16.000Z
// Distributed under the BSD 2-Clause License - Copyright 2012-2021 Robin Degen #include <aeon/math/size2d.h> #include <aeon/math/size2d_stream.h> #include <gtest/gtest.h> using namespace aeon; TEST(test_size2d, test_size2d_default_int) { [[maybe_unused]] math::size2d<int> size; } struct external_size2d { int width{}; int height{}; }; TEST(test_size2d, test_size2d_convert_from_unknown) { const external_size2d s{10, 20}; math::size2d<int> size{s}; EXPECT_EQ(size.width, 10); EXPECT_EQ(size.height, 20); const auto s2 = size.convert_to<external_size2d>(); EXPECT_EQ(s2.width, 10); EXPECT_EQ(s2.height, 20); } TEST(test_size2d, test_size2d_clamp) { const math::size2d min{5, 10}; const math::size2d max{50, 100}; EXPECT_EQ(math::clamp(math::size2d{10, 20}, min, max), (math::size2d{10, 20})); EXPECT_EQ(math::clamp(math::size2d{40, 90}, min, max), (math::size2d{40, 90})); EXPECT_EQ(math::clamp(math::size2d{4, 20}, min, max), (math::size2d{5, 20})); EXPECT_EQ(math::clamp(math::size2d{5, 9}, min, max), (math::size2d{5, 10})); EXPECT_EQ(math::clamp(math::size2d{51, 90}, min, max), (math::size2d{50, 90})); EXPECT_EQ(math::clamp(math::size2d{50, 110}, min, max), (math::size2d{50, 100})); }
28.311111
85
0.66562
aeon-engine
08e2d306237380b794321d0edbfd42c70a61b2bb
4,852
cpp
C++
src/classical/io/write_verilog.cpp
eletesta/cirkit
6d0939798ea25cecf92306ce796be154139b94f5
[ "MIT" ]
null
null
null
src/classical/io/write_verilog.cpp
eletesta/cirkit
6d0939798ea25cecf92306ce796be154139b94f5
[ "MIT" ]
null
null
null
src/classical/io/write_verilog.cpp
eletesta/cirkit
6d0939798ea25cecf92306ce796be154139b94f5
[ "MIT" ]
null
null
null
/* CirKit: A circuit toolkit * Copyright (C) 2009-2015 University of Bremen * Copyright (C) 2015-2017 EPFL * * 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 "write_verilog.hpp" #include <fstream> #include <boost/algorithm/string/join.hpp> #include <boost/assign/std/vector.hpp> #include <boost/format.hpp> #include <boost/range/algorithm.hpp> #include <classical/io/io_utils_p.hpp> using namespace boost::assign; using boost::format; namespace cirkit { /****************************************************************************** * Private functions * ******************************************************************************/ std::string remove_brackets( const std::string& s ) { std::string sc = s; size_t n = 0; while ( ( n = sc.find( '[', n ) ) != std::string::npos ) { auto n2 = sc.find( ']', n ); sc[n] = sc[n2] = '_'; n = n2; } return sc; } void create_possible_inverter( std::ostream& os, const aig_function& f, std::vector<aig_node>& inverter_created, const aig_graph& aig ) { if ( f.complemented && boost::find( inverter_created, f.node ) == inverter_created.end() ) { os << format( "not %1%_inv( %1%_inv, %1% );" ) % get_node_name_processed( f.node, aig, &remove_brackets ) << std::endl; inverter_created += f.node; } } /****************************************************************************** * Public functions * ******************************************************************************/ void write_verilog( const aig_graph& aig, std::ostream& os ) { const auto& aig_info = boost::get_property( aig, boost::graph_name ); std::vector<std::string> inputs, outputs; std::vector<aig_node> inverter_created; /* Inputs */ for ( const auto& v : aig_info.inputs ) { inputs += remove_brackets( aig_info.node_names.find( v )->second ); } /* Outputs */ for ( const auto& v : aig_info.outputs ) { outputs += remove_brackets( v.second ); } os << format( "module top(%s, %s);" ) % boost::join( inputs, ", " ) % boost::join( outputs, ", " ) << std::endl << format( "input %s;" ) % boost::join( inputs, ", " ) << std::endl << format( "output %s;" ) % boost::join( outputs, ", " ) << std::endl; /* AND gates */ for ( const auto& v : boost::make_iterator_range( boost::vertices( aig ) ) ) { /* skip outputs */ if ( boost::out_degree( v, aig ) == 0u ) continue; auto operands = get_operands( v, aig ); create_possible_inverter( os, operands.first, inverter_created, aig ); create_possible_inverter( os, operands.second, inverter_created, aig ); os << format( "and %1%( %1%, %2%%3%, %4%%5% );" ) % get_node_name_processed( v, aig, &remove_brackets ) % get_node_name_processed( operands.first.node, aig, &remove_brackets ) % ( operands.first.complemented ? "_inv" : "" ) % get_node_name_processed( operands.second.node, aig, &remove_brackets ) % ( operands.second.complemented ? "_inv" : "" ) << std::endl; } /* Output functions */ for ( const auto& v : aig_info.outputs ) { os << format( "%1% %2%( %2%, %3% );" ) % ( v.first.complemented ? "not" : "buf" ) % remove_brackets( v.second ) % get_node_name_processed( v.first.node, aig, &remove_brackets ) << std::endl; } os << "endmodule" << std::endl; } void write_verilog( const aig_graph& aig, const std::string& filename ) { std::ofstream os( filename.c_str(), std::ofstream::out ); write_verilog( aig, os ); os.close(); } } // Local Variables: // c-basic-offset: 2 // eval: (c-set-offset 'substatement-open 0) // eval: (c-set-offset 'innamespace 0) // End:
34.657143
141
0.591509
eletesta
08e4d6f55664305d11c4b22861efc87b3e154840
259
cpp
C++
tests/main.cpp
RotartsiORG/StoneMason
0f6efefad68b29e7e82524e705ce47606ba53665
[ "Apache-2.0" ]
1
2021-10-02T19:31:14.000Z
2021-10-02T19:31:14.000Z
tests/main.cpp
RotartsiORG/StoneMason
0f6efefad68b29e7e82524e705ce47606ba53665
[ "Apache-2.0" ]
1
2020-06-17T01:15:45.000Z
2020-06-17T01:16:08.000Z
tests/main.cpp
RotartsiORG/StoneMason
0f6efefad68b29e7e82524e705ce47606ba53665
[ "Apache-2.0" ]
1
2020-10-17T23:57:27.000Z
2020-10-17T23:57:27.000Z
// // Created by grant on 1/2/20. // #include "gtest/gtest.h" #include "stms/log_test.cpp" #include "stms/async_test.cpp" #include "stms/general.cpp" #if STMS_SSL_TESTS_ENABLED // Toggle SSL tests, disable for travis # include "stms/ssl_test.cpp" #endif
19.923077
67
0.718147
RotartsiORG
08e707f8036b8a1d6f86f75bd1152df0f04744d1
1,395
cc
C++
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/com_bitvectortest.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/com_bitvectortest.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/com_bitvectortest.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
#include "com_bitvectortest.h" // Library headers. #include <boost/shared_ptr.hpp> #include <boost/test/test_tools.hpp> #include <boost/test/unit_test_suite.hpp> // PCRaster library headers. // Module headers. #include "com_bitvector.h" /*! \file This file contains the implementation of the BitVectorTest class. */ //------------------------------------------------------------------------------ // DEFINITION OF STATIC BITVECTOR MEMBERS //------------------------------------------------------------------------------ //! suite boost::unit_test::test_suite*com::BitVectorTest::suite() { boost::unit_test::test_suite* suite = BOOST_TEST_SUITE(__FILE__); boost::shared_ptr<BitVectorTest> instance(new BitVectorTest()); suite->add(BOOST_CLASS_TEST_CASE(&BitVectorTest::test, instance)); return suite; } //------------------------------------------------------------------------------ // DEFINITION OF BITVECTOR MEMBERS //------------------------------------------------------------------------------ //! ctor com::BitVectorTest::BitVectorTest() { } //! setUp void com::BitVectorTest::setUp() { } //! tearDown void com::BitVectorTest::tearDown() { } void com::BitVectorTest::test() { BitVector bv(5); bv.set(0); bv.set(2); bv.set(4); BOOST_CHECK( bv[0]); BOOST_CHECK(!bv[1]); BOOST_CHECK( bv[2]); BOOST_CHECK(!bv[3]); BOOST_CHECK( bv[4]); }
18.116883
80
0.536201
quanpands
08e7bc9d26d1bca865b1ba8f1f8b54a2852db55e
336
hpp
C++
etl/utils/singleton.hpp
julienlopez/ETL
51c6e2c425d1bec29507a4f9a89c6211c9d7488f
[ "MIT" ]
null
null
null
etl/utils/singleton.hpp
julienlopez/ETL
51c6e2c425d1bec29507a4f9a89c6211c9d7488f
[ "MIT" ]
1
2015-03-25T09:42:10.000Z
2015-03-25T09:42:10.000Z
etl/utils/singleton.hpp
julienlopez/ETL
51c6e2c425d1bec29507a4f9a89c6211c9d7488f
[ "MIT" ]
null
null
null
#ifndef __SINGLETON_HPP__ #define __SINGLETON_HPP__ #include "noncopyable.hpp" namespace etl { namespace utils { template<class T> class singleton : public noncopyable { public: static T& instance() { static T i; return i; } protected: singleton() {} }; } //utils } //etl #endif // __SINGLETON_HPP__
12.923077
56
0.660714
julienlopez
08e8850381bddd9d41475a7b1eabc6b9dcaeb4b9
1,524
cpp
C++
ProjetGraph/ProjetGraph/tests/CUnit.cpp
RakSrinaNa/DI3---Projet-CPP
e5742941032f6a30f84868039b81b647fcf41cb5
[ "MIT" ]
null
null
null
ProjetGraph/ProjetGraph/tests/CUnit.cpp
RakSrinaNa/DI3---Projet-CPP
e5742941032f6a30f84868039b81b647fcf41cb5
[ "MIT" ]
null
null
null
ProjetGraph/ProjetGraph/tests/CUnit.cpp
RakSrinaNa/DI3---Projet-CPP
e5742941032f6a30f84868039b81b647fcf41cb5
[ "MIT" ]
null
null
null
#include <iostream> #include "CUnit.h" #include "CExceptionUnit.h" #include "CArcUnit.h" #include "CVertexUnit.h" #include "CGraphUnit.h" #include "CGraphParserUnit.h" #include "CHashMapUnit.h" #include "../CException.h" #include "CGraphToolboxUnit.h" void CUnit::UNITassertError(const char * pcMessage) { perror(pcMessage); perror("\n"); #ifdef _MSC_VER throw CException(0, (char *) "BREAKPOINT UNIT TESTS"); #else raise(SIGINT); #endif exit(EXIT_FAILURE); } void CUnit::UNITlaunchTests() { std::cout << "Starting CException tests..." << std::endl; CExceptionUnit::EXUnitTests(); std::cout << "CException OK" << std::endl << std::endl; std::cout << "Starting CHashMap tests..." << std::endl; CHashMapUnit::HMPUnitTest(); std::cout << "CHashMap OK" << std::endl << std::endl; std::cout << "Starting CArc tests..." << std::endl; CArcUnit::ARCUnitTests(); std::cout << "CArc OK" << std::endl << std::endl; std::cout << "Starting CVertex tests..." << std::endl; CVertexUnit::VERUnitTest(); std::cout << "CVertex OK" << std::endl << std::endl; std::cout << "Starting CGraphParser tests..." << std::endl; CGraphParserUnit::PGRAUnitTests(); std::cout << "CGraphParser OK" << std::endl << std::endl; std::cout << "Starting CGraph tests..." << std::endl; CGraphUnit::GRAUnitTests(); std::cout << "CGraph OK" << std::endl << std::endl; std::cout << "Starting CGraphToolbox tests..." << std::endl; CGraphToolboxUnit::GRTUnitTests(); std::cout << "CGraphToolbox OK" << std::endl << std::endl; }
28.222222
61
0.660105
RakSrinaNa
08f2dfb507e32aa9e718d9c6509667bf65db2812
14,440
cc
C++
cc_code/src/common/error-model.test.cc
erisyon/whatprot
176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c
[ "MIT" ]
null
null
null
cc_code/src/common/error-model.test.cc
erisyon/whatprot
176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c
[ "MIT" ]
1
2021-06-12T00:50:08.000Z
2021-06-15T17:59:12.000Z
cc_code/src/common/error-model.test.cc
erisyon/whatprot
176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c
[ "MIT" ]
1
2021-06-11T19:34:43.000Z
2021-06-11T19:34:43.000Z
/******************************************************************************\ * Author: Matthew Beauregard Smith * * Affiliation: The University of Texas at Austin * * Department: Oden Institute and Institute for Cellular and Molecular Biology * * PI: Edward Marcotte * * Project: Protein Fluorosequencing * \******************************************************************************/ // Boost unit test framework (recommended to be the first include): #include <boost/test/unit_test.hpp> // File under test: #include "error-model.h" // Standard C++ library headers: #include <cmath> #include <functional> namespace whatprot { namespace { using boost::unit_test::tolerance; using std::exp; using std::function; using std::log; const double TOL = 0.000000001; } // namespace BOOST_AUTO_TEST_SUITE(common_suite) BOOST_AUTO_TEST_SUITE(error_model_suite) BOOST_AUTO_TEST_CASE(constructor_test) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::LOGNORMAL; double mu = log(1.0); double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); BOOST_TEST(em.p_edman_failure == p_edman_failure); BOOST_TEST(em.p_detach == p_detach); BOOST_TEST(em.p_bleach == p_bleach); BOOST_TEST(em.p_dud == p_dud); BOOST_TEST(em.distribution_type == dist_type); BOOST_TEST(em.mu == mu); BOOST_TEST(em.sigma == sigma); BOOST_TEST(em.stuck_dye_ratio == stuck_dye_ratio); BOOST_TEST(em.p_stuck_dye_loss == p_stuck_dye_loss); } BOOST_AUTO_TEST_CASE(pdf_lognormal_state_zero_obs_zero_test) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::LOGNORMAL; double mu = log(1.0); double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 0.0; int state = 0; BOOST_TEST(pdf(observed, state) == 1.0); } BOOST_AUTO_TEST_CASE(pdf_lognormal_state_zero_obs_one_test) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::LOGNORMAL; double mu = log(1.0); double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 1.0; int state = 0; BOOST_TEST(pdf(observed, state) == 0.0); } BOOST_AUTO_TEST_CASE(pdf_lognormal_state_one_obs_zero_test) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::LOGNORMAL; double mu = log(1.0); double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 0.0; int state = 1; BOOST_TEST(pdf(observed, state) == 0.0); } BOOST_AUTO_TEST_CASE(pdf_lognormal_state_one_obs_one_test, *tolerance(TOL)) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::LOGNORMAL; double mu = log(1.0); double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 1.0; int state = 1; // The test value was found using an online lognormal distribution pdf // calculator. BOOST_TEST(pdf(observed, state) == 2.4933892525089547); } BOOST_AUTO_TEST_CASE(pdf_lognormal_state_eq_obs_ne_one_test, *tolerance(TOL)) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::LOGNORMAL; double mu = log(1.3); double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 1.3; int state = 1; // The test value was found using an online lognormal distribution pdf // calculator. BOOST_TEST(pdf(observed, state) == 2.4933892525089547 / 1.3); } BOOST_AUTO_TEST_CASE(pdf_override_state_zero_obs_zero_test) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::OVERRIDE; double mu = 1.0; double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 0.0; int state = 0; BOOST_TEST(pdf(observed, state) == 1.0); } BOOST_AUTO_TEST_CASE(pdf_override_state_zero_obs_one_test) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::OVERRIDE; double mu = 1.0; double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 1.0; int state = 0; BOOST_TEST(pdf(observed, state) == 1.0); } BOOST_AUTO_TEST_CASE(pdf_override_state_one_obs_zero_test) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::OVERRIDE; double mu = 1.0; double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 0.0; int state = 1; BOOST_TEST(pdf(observed, state) == 1.0); } BOOST_AUTO_TEST_CASE(pdf_override_state_one_obs_one_test, *tolerance(TOL)) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::OVERRIDE; double mu = 1.0; double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 1.0; int state = 1; BOOST_TEST(pdf(observed, state) == 1.0); } BOOST_AUTO_TEST_CASE(relative_distance_p_edman_failure_test, *tolerance(TOL)) { ErrorModel em1( 0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); ErrorModel em2(0.66, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5); BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66); } BOOST_AUTO_TEST_CASE(relative_distance_p_detach_test, *tolerance(TOL)) { ErrorModel em1( 0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); ErrorModel em2(0.5, 0.66, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5); BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66); } BOOST_AUTO_TEST_CASE(relative_distance_p_bleach_test, *tolerance(TOL)) { ErrorModel em1( 0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); ErrorModel em2(0.5, 0.5, 0.66, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5); BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66); } BOOST_AUTO_TEST_CASE(relative_distance_p_dud_test, *tolerance(TOL)) { ErrorModel em1( 0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); ErrorModel em2(0.5, 0.5, 0.5, 0.66, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5); BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66); } BOOST_AUTO_TEST_CASE(relative_distance_mu_test, *tolerance(TOL)) { ErrorModel em1( 0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); ErrorModel em2(0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.66, 0.5, 0.5, 0.5); BOOST_TEST(em1.relative_distance(em2) == (exp(0.66) - exp(0.5)) / exp(0.5)); BOOST_TEST(em2.relative_distance(em1) == (exp(0.66) - exp(0.5)) / exp(0.66)); } BOOST_AUTO_TEST_CASE(relative_distance_sigma_test, *tolerance(TOL)) { ErrorModel em1( 0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); ErrorModel em2(0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.66, 0.5, 0.5); BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5); BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66); } BOOST_AUTO_TEST_CASE(relative_distance_stuck_dye_ratio_test, *tolerance(TOL)) { ErrorModel em1( 0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); ErrorModel em2(0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.66, 0.5); BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5); BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66); } BOOST_AUTO_TEST_CASE(relative_distance_p_stuck_dye_loss_test, *tolerance(TOL)) { ErrorModel em1( 0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); ErrorModel em2(0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.66); BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5); BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66); } BOOST_AUTO_TEST_CASE(relative_distance_max_no_sum_test, *tolerance(TOL)) { ErrorModel em1(0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.66, 0.5, 0.5, 0.5); ErrorModel em2(0.7, 0.7, 0.7, 0.7, DistributionType::OVERRIDE, 0.66, 0.7, 0.7, 0.7); BOOST_TEST(em1.relative_distance(em2) == (0.7 - 0.5) / 0.5); BOOST_TEST(em2.relative_distance(em1) == (0.7 - 0.5) / 0.7); } BOOST_AUTO_TEST_SUITE_END() // error_model_suite BOOST_AUTO_TEST_SUITE_END() // common_suite } // namespace whatprot
32.304251
80
0.523546
erisyon
08f4420ae9b237e53d192e28ad209aaae3a6384b
2,524
cpp
C++
framework/L2DMatrix44.cpp
dragonflylee/Dango
3243a3ade6d8a4391b1d78c8bc4bb210779022cb
[ "MIT" ]
1
2018-01-09T02:43:57.000Z
2018-01-09T02:43:57.000Z
framework/L2DMatrix44.cpp
dragonflylee/Dango
3243a3ade6d8a4391b1d78c8bc4bb210779022cb
[ "MIT" ]
null
null
null
framework/L2DMatrix44.cpp
dragonflylee/Dango
3243a3ade6d8a4391b1d78c8bc4bb210779022cb
[ "MIT" ]
null
null
null
/** * * You can modify and use this source freely * only for the development of application related Live2D. * * (c) Live2D Inc. All rights reserved. */ #include "L2DMatrix44.h" namespace live2d { namespace framework { L2DMatrix44::L2DMatrix44() { identity(); } // 単位行列に初期化 void L2DMatrix44::identity(){ for (int i = 0; i < 16; i++) tr[i] = ((i % 5) == 0) ? 1.0f : 0.0f; } void L2DMatrix44::mul(float* a, float* b, float* dst) { float c[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int n = 4; int i, j, k; // 受け取った2つの行列の掛け算を行う。 for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { for (k = 0; k < n; k++) { //c[i*4+j]+=a[i*4+k]*b[k*4+j]; c[i + j * 4] += a[i + k * 4] * b[k + j * 4]; } } } for (i = 0; i < 16; i++) { dst[i] = c[i]; } } void L2DMatrix44::multTranslate(float x, float y) { float tr1[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, 0, 1 }; mul(tr1, tr, tr); } void L2DMatrix44::translate(float x, float y) { tr[12] = x; tr[13] = y; } void L2DMatrix44::multScale(float scaleX, float scaleY) { float tr1[16] = { scaleX, 0, 0, 0, 0, scaleY, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; mul(tr1, tr, tr); } void L2DMatrix44::scale(float scaleX, float scaleY) { tr[0] = scaleX; tr[5] = scaleY; } float L2DMatrix44::transformX(float src) { return tr[0] * src + tr[12]; } float L2DMatrix44::invertTransformX(float src) { return (src - tr[12]) / tr[0]; } float L2DMatrix44::transformY(float src) { return tr[5] * src + tr[13]; } float L2DMatrix44::invertTransformY(float src) { return (src - tr[13]) / tr[5]; } void L2DMatrix44::setMatrix(float* _tr) { for (int i = 0; i < 16; i++) tr[i] = _tr[i]; } void L2DMatrix44::append(L2DMatrix44* m) { mul(m->getArray(), tr, tr); } } }
22.336283
89
0.389857
dragonflylee
08f7b1a7196f0b681692d1bb2cbe0f9b9bb590ab
1,926
cpp
C++
test/unit_tests/tests/18_FFT_revtests.cpp
bacchus/bacchuslib
35c41b6a7244227c0779c99b3c2f98b9a8349477
[ "MIT" ]
null
null
null
test/unit_tests/tests/18_FFT_revtests.cpp
bacchus/bacchuslib
35c41b6a7244227c0779c99b3c2f98b9a8349477
[ "MIT" ]
null
null
null
test/unit_tests/tests/18_FFT_revtests.cpp
bacchus/bacchuslib
35c41b6a7244227c0779c99b3c2f98b9a8349477
[ "MIT" ]
null
null
null
#include "setting.h" #include "math/fft.h" #include "utils/logger.h" #include "audio/audio_tools.h" using namespace bacchus; const float tol18 = 1e-4f; const int ulpDif = 256*1024; void FftCrossTest(const matxf& x, const matxcx& resy) { matxcx y = DFT(x); int n = y.size(); EXPECT_EQ(resy.size(), n); for (int i = 0; i < n; ++i) { EXPECT_LE(ulp_difference(resy[i].real(),y[i].real(), tol18), i); EXPECT_LE(ulp_difference(resy[i].imag(),y[i].imag(), tol18), i); } matxcx y1 = fft(x); int n1 = y1.size(); EXPECT_EQ(resy.size(), n1); for (int i = 0; i < n1; ++i) { EXPECT_LE(ulp_difference(resy[i].real(),y1[i].real(), tol18), i); EXPECT_LE(ulp_difference(resy[i].imag(),y1[i].imag(), tol18), i); } } void FftCrossTest(const matxf& x) { matxcx resy = DFT(x); matxcx y1 = fft(x); //PRINT(resy); //PRINT(y1); // int bd = x.size() > 1000 ? 948 : 0; // EXPECT_FLOAT_EQ(resy[bd].real(),y1[bd].real()); int n1 = y1.size(); EXPECT_EQ(resy.size(), n1); for (int i = 0; i < n1; ++i) { EXPECT_LE(ulp_difference(resy[i].real(),y1[i].real(), tol18), i); EXPECT_LE(ulp_difference(resy[i].imag(),y1[i].imag(), tol18), i); } } TEST(FFT2, CrossTest) { matxf x = {1,2,3,4}; matxcx resy = {cplx{10,0}, cplx{-2,2}, cplx{-2,0}, cplx{-2,-2}}; FftCrossTest(x,resy); } TEST(FFT2, DftNoRes) { matxf x = {1,2,3,4}; FftCrossTest(x); } TEST(FFT2, Sine) { int fs = 1024*100; int f1 = 100; matxcx x1 = genSine(1,f1,0,fs,1024); matxcx y = fft(x1); //PRINT(y); matxcx res = fftrev(y); int n1 = x1.size(); EXPECT_EQ(res.size(), n1); for (int i = 0; i < n1; ++i) { EXPECT_LE(ulp_difference(res[i].real(),x1[i].real(), tol18), i); EXPECT_LE(ulp_difference(res[i].imag(),x1[i].imag(), tol18), i); } //FftCrossTest(x1); //FftCrossTest(x2); }
25.342105
73
0.558152
bacchus
08fcbe77618e5dfaad7de00fe7b983a15598ca9f
25,842
cc
C++
src/mavsdk_server/src/generated/gimbal/gimbal.grpc.pb.cc
fpersson/MAVSDK
a7161d7634cd04de97f7fbcea10c2da21136892c
[ "BSD-3-Clause" ]
1
2020-03-30T07:53:19.000Z
2020-03-30T07:53:19.000Z
src/mavsdk_server/src/generated/gimbal/gimbal.grpc.pb.cc
fpersson/MAVSDK
a7161d7634cd04de97f7fbcea10c2da21136892c
[ "BSD-3-Clause" ]
1
2021-03-15T18:34:13.000Z
2021-03-15T18:34:13.000Z
src/mavsdk_server/src/generated/gimbal/gimbal.grpc.pb.cc
SEESAI/MAVSDK
5a9289eb09eb6b13f24e9d8d69f5644d2210d6b2
[ "BSD-3-Clause" ]
null
null
null
// Generated by the gRPC C++ plugin. // If you make any local change, they will be lost. // source: gimbal/gimbal.proto #include "gimbal/gimbal.pb.h" #include "gimbal/gimbal.grpc.pb.h" #include <functional> #include <grpcpp/impl/codegen/async_stream.h> #include <grpcpp/impl/codegen/async_unary_call.h> #include <grpcpp/impl/codegen/channel_interface.h> #include <grpcpp/impl/codegen/client_unary_call.h> #include <grpcpp/impl/codegen/client_callback.h> #include <grpcpp/impl/codegen/message_allocator.h> #include <grpcpp/impl/codegen/method_handler.h> #include <grpcpp/impl/codegen/rpc_service_method.h> #include <grpcpp/impl/codegen/server_callback.h> #include <grpcpp/impl/codegen/server_callback_handlers.h> #include <grpcpp/impl/codegen/server_context.h> #include <grpcpp/impl/codegen/service_type.h> #include <grpcpp/impl/codegen/sync_stream.h> namespace mavsdk { namespace rpc { namespace gimbal { static const char* GimbalService_method_names[] = { "/mavsdk.rpc.gimbal.GimbalService/SetPitchAndYaw", "/mavsdk.rpc.gimbal.GimbalService/SetPitchRateAndYawRate", "/mavsdk.rpc.gimbal.GimbalService/SetMode", "/mavsdk.rpc.gimbal.GimbalService/SetRoiLocation", "/mavsdk.rpc.gimbal.GimbalService/TakeControl", "/mavsdk.rpc.gimbal.GimbalService/ReleaseControl", "/mavsdk.rpc.gimbal.GimbalService/SubscribeControl", }; std::unique_ptr< GimbalService::Stub> GimbalService::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) { (void)options; std::unique_ptr< GimbalService::Stub> stub(new GimbalService::Stub(channel)); return stub; } GimbalService::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) : channel_(channel), rpcmethod_SetPitchAndYaw_(GimbalService_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_SetPitchRateAndYawRate_(GimbalService_method_names[1], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_SetMode_(GimbalService_method_names[2], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_SetRoiLocation_(GimbalService_method_names[3], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_TakeControl_(GimbalService_method_names[4], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_ReleaseControl_(GimbalService_method_names[5], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_SubscribeControl_(GimbalService_method_names[6], ::grpc::internal::RpcMethod::SERVER_STREAMING, channel) {} ::grpc::Status GimbalService::Stub::SetPitchAndYaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest& request, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::SetPitchAndYawRequest, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_SetPitchAndYaw_, context, request, response); } void GimbalService::Stub::experimental_async::SetPitchAndYaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest* request, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::SetPitchAndYawRequest, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetPitchAndYaw_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::SetPitchAndYaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest* request, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetPitchAndYaw_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetPitchAndYawResponse>* GimbalService::Stub::PrepareAsyncSetPitchAndYawRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::SetPitchAndYawResponse, ::mavsdk::rpc::gimbal::SetPitchAndYawRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_SetPitchAndYaw_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetPitchAndYawResponse>* GimbalService::Stub::AsyncSetPitchAndYawRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncSetPitchAndYawRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status GimbalService::Stub::SetPitchRateAndYawRate(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest& request, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_SetPitchRateAndYawRate_, context, request, response); } void GimbalService::Stub::experimental_async::SetPitchRateAndYawRate(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest* request, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetPitchRateAndYawRate_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::SetPitchRateAndYawRate(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest* request, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetPitchRateAndYawRate_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse>* GimbalService::Stub::PrepareAsyncSetPitchRateAndYawRateRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_SetPitchRateAndYawRate_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse>* GimbalService::Stub::AsyncSetPitchRateAndYawRateRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncSetPitchRateAndYawRateRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status GimbalService::Stub::SetMode(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest& request, ::mavsdk::rpc::gimbal::SetModeResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::SetModeRequest, ::mavsdk::rpc::gimbal::SetModeResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_SetMode_, context, request, response); } void GimbalService::Stub::experimental_async::SetMode(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest* request, ::mavsdk::rpc::gimbal::SetModeResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::SetModeRequest, ::mavsdk::rpc::gimbal::SetModeResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetMode_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::SetMode(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest* request, ::mavsdk::rpc::gimbal::SetModeResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetMode_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetModeResponse>* GimbalService::Stub::PrepareAsyncSetModeRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::SetModeResponse, ::mavsdk::rpc::gimbal::SetModeRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_SetMode_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetModeResponse>* GimbalService::Stub::AsyncSetModeRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncSetModeRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status GimbalService::Stub::SetRoiLocation(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest& request, ::mavsdk::rpc::gimbal::SetRoiLocationResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::SetRoiLocationRequest, ::mavsdk::rpc::gimbal::SetRoiLocationResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_SetRoiLocation_, context, request, response); } void GimbalService::Stub::experimental_async::SetRoiLocation(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest* request, ::mavsdk::rpc::gimbal::SetRoiLocationResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::SetRoiLocationRequest, ::mavsdk::rpc::gimbal::SetRoiLocationResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetRoiLocation_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::SetRoiLocation(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest* request, ::mavsdk::rpc::gimbal::SetRoiLocationResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetRoiLocation_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetRoiLocationResponse>* GimbalService::Stub::PrepareAsyncSetRoiLocationRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::SetRoiLocationResponse, ::mavsdk::rpc::gimbal::SetRoiLocationRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_SetRoiLocation_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetRoiLocationResponse>* GimbalService::Stub::AsyncSetRoiLocationRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncSetRoiLocationRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status GimbalService::Stub::TakeControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest& request, ::mavsdk::rpc::gimbal::TakeControlResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::TakeControlRequest, ::mavsdk::rpc::gimbal::TakeControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_TakeControl_, context, request, response); } void GimbalService::Stub::experimental_async::TakeControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest* request, ::mavsdk::rpc::gimbal::TakeControlResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::TakeControlRequest, ::mavsdk::rpc::gimbal::TakeControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_TakeControl_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::TakeControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest* request, ::mavsdk::rpc::gimbal::TakeControlResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_TakeControl_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::TakeControlResponse>* GimbalService::Stub::PrepareAsyncTakeControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::TakeControlResponse, ::mavsdk::rpc::gimbal::TakeControlRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_TakeControl_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::TakeControlResponse>* GimbalService::Stub::AsyncTakeControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncTakeControlRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status GimbalService::Stub::ReleaseControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest& request, ::mavsdk::rpc::gimbal::ReleaseControlResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::ReleaseControlRequest, ::mavsdk::rpc::gimbal::ReleaseControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_ReleaseControl_, context, request, response); } void GimbalService::Stub::experimental_async::ReleaseControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest* request, ::mavsdk::rpc::gimbal::ReleaseControlResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::ReleaseControlRequest, ::mavsdk::rpc::gimbal::ReleaseControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_ReleaseControl_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::ReleaseControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest* request, ::mavsdk::rpc::gimbal::ReleaseControlResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_ReleaseControl_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::ReleaseControlResponse>* GimbalService::Stub::PrepareAsyncReleaseControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::ReleaseControlResponse, ::mavsdk::rpc::gimbal::ReleaseControlRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_ReleaseControl_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::ReleaseControlResponse>* GimbalService::Stub::AsyncReleaseControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncReleaseControlRaw(context, request, cq); result->StartCall(); return result; } ::grpc::ClientReader< ::mavsdk::rpc::gimbal::ControlResponse>* GimbalService::Stub::SubscribeControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SubscribeControlRequest& request) { return ::grpc::internal::ClientReaderFactory< ::mavsdk::rpc::gimbal::ControlResponse>::Create(channel_.get(), rpcmethod_SubscribeControl_, context, request); } void GimbalService::Stub::experimental_async::SubscribeControl(::grpc::ClientContext* context, ::mavsdk::rpc::gimbal::SubscribeControlRequest* request, ::grpc::experimental::ClientReadReactor< ::mavsdk::rpc::gimbal::ControlResponse>* reactor) { ::grpc::internal::ClientCallbackReaderFactory< ::mavsdk::rpc::gimbal::ControlResponse>::Create(stub_->channel_.get(), stub_->rpcmethod_SubscribeControl_, context, request, reactor); } ::grpc::ClientAsyncReader< ::mavsdk::rpc::gimbal::ControlResponse>* GimbalService::Stub::AsyncSubscribeControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SubscribeControlRequest& request, ::grpc::CompletionQueue* cq, void* tag) { return ::grpc::internal::ClientAsyncReaderFactory< ::mavsdk::rpc::gimbal::ControlResponse>::Create(channel_.get(), cq, rpcmethod_SubscribeControl_, context, request, true, tag); } ::grpc::ClientAsyncReader< ::mavsdk::rpc::gimbal::ControlResponse>* GimbalService::Stub::PrepareAsyncSubscribeControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SubscribeControlRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncReaderFactory< ::mavsdk::rpc::gimbal::ControlResponse>::Create(channel_.get(), cq, rpcmethod_SubscribeControl_, context, request, false, nullptr); } GimbalService::Service::Service() { AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::SetPitchAndYawRequest, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest* req, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse* resp) { return service->SetPitchAndYaw(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[1], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest* req, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse* resp) { return service->SetPitchRateAndYawRate(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[2], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::SetModeRequest, ::mavsdk::rpc::gimbal::SetModeResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::SetModeRequest* req, ::mavsdk::rpc::gimbal::SetModeResponse* resp) { return service->SetMode(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[3], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::SetRoiLocationRequest, ::mavsdk::rpc::gimbal::SetRoiLocationResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest* req, ::mavsdk::rpc::gimbal::SetRoiLocationResponse* resp) { return service->SetRoiLocation(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[4], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::TakeControlRequest, ::mavsdk::rpc::gimbal::TakeControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::TakeControlRequest* req, ::mavsdk::rpc::gimbal::TakeControlResponse* resp) { return service->TakeControl(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[5], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::ReleaseControlRequest, ::mavsdk::rpc::gimbal::ReleaseControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::ReleaseControlRequest* req, ::mavsdk::rpc::gimbal::ReleaseControlResponse* resp) { return service->ReleaseControl(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[6], ::grpc::internal::RpcMethod::SERVER_STREAMING, new ::grpc::internal::ServerStreamingHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::SubscribeControlRequest, ::mavsdk::rpc::gimbal::ControlResponse>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::SubscribeControlRequest* req, ::grpc::ServerWriter<::mavsdk::rpc::gimbal::ControlResponse>* writer) { return service->SubscribeControl(ctx, req, writer); }, this))); } GimbalService::Service::~Service() { } ::grpc::Status GimbalService::Service::SetPitchAndYaw(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest* request, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::SetPitchRateAndYawRate(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest* request, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::SetMode(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest* request, ::mavsdk::rpc::gimbal::SetModeResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::SetRoiLocation(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest* request, ::mavsdk::rpc::gimbal::SetRoiLocationResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::TakeControl(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest* request, ::mavsdk::rpc::gimbal::TakeControlResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::ReleaseControl(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest* request, ::mavsdk::rpc::gimbal::ReleaseControlResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::SubscribeControl(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::SubscribeControlRequest* request, ::grpc::ServerWriter< ::mavsdk::rpc::gimbal::ControlResponse>* writer) { (void) context; (void) request; (void) writer; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } } // namespace mavsdk } // namespace rpc } // namespace gimbal
76.910714
317
0.747581
fpersson
1c00ca7ebcb8c0ce9aeeb4784f8e788502f27923
9,983
cc
C++
src/xzero/http/http1/Parser-test.cc
pjsaksa/x0
96b69e5a54b006e3d929b9934c2708f7967371bb
[ "MIT" ]
24
2016-07-10T08:05:11.000Z
2021-11-16T10:53:48.000Z
src/xzero/http/http1/Parser-test.cc
pjsaksa/x0
96b69e5a54b006e3d929b9934c2708f7967371bb
[ "MIT" ]
14
2015-04-12T10:45:26.000Z
2016-06-28T22:27:50.000Z
src/xzero/http/http1/Parser-test.cc
pjsaksa/x0
96b69e5a54b006e3d929b9934c2708f7967371bb
[ "MIT" ]
4
2016-10-05T17:51:38.000Z
2020-04-20T07:45:23.000Z
// This file is part of the "x0" project, http://github.com/christianparpart/x0> // (c) 2009-2018 Christian Parpart <christian@parpart.family> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #include <xzero/http/http1/Parser.h> #include <xzero/http/HttpListener.h> #include <xzero/http/HttpStatus.h> #include <xzero/io/FileUtil.h> #include <xzero/RuntimeError.h> #include <xzero/Buffer.h> #include <vector> #include <xzero/testing.h> using namespace xzero; using namespace xzero::http; using namespace xzero::http::http1; class ParserListener : public HttpListener { // {{{ public: ParserListener(); void onMessageBegin(const BufferRef& method, const BufferRef& entity, HttpVersion version) override; void onMessageBegin(HttpVersion version, HttpStatus code, const BufferRef& text) override; void onMessageBegin() override; void onMessageHeader(const BufferRef& name, const BufferRef& value) override; void onMessageHeaderEnd() override; void onMessageContent(const BufferRef& chunk) override; void onMessageContent(FileView&& chunk) override; void onMessageEnd() override; void onError(std::error_code ec) override; public: std::string method; std::string entity; HttpVersion version; HttpStatus statusCode; std::string statusReason; std::vector<std::pair<std::string, std::string>> headers; Buffer body; HttpStatus errorCode; bool messageBegin; bool headerEnd; bool messageEnd; }; ParserListener::ParserListener() : method(), entity(), version(HttpVersion::UNKNOWN), statusCode(HttpStatus::Undefined), statusReason(), headers(), errorCode(HttpStatus::Undefined), messageBegin(false), headerEnd(false), messageEnd(false) { } void ParserListener::onMessageBegin(const BufferRef& method, const BufferRef& entity, HttpVersion version) { this->method = method.str(); this->entity = entity.str(); this->version = version; } void ParserListener::onMessageBegin(HttpVersion version, HttpStatus code, const BufferRef& text) { this->version = version; this->statusCode = code; this->statusReason = text.str(); } void ParserListener::onMessageBegin() { messageBegin = true; } void ParserListener::onMessageHeader(const BufferRef& name, const BufferRef& value) { headers.push_back(std::make_pair(name.str(), value.str())); } void ParserListener::onMessageHeaderEnd() { headerEnd = true; } void ParserListener::onMessageContent(const BufferRef& chunk) { body += chunk; } void ParserListener::onMessageContent(FileView&& chunk) { body += FileUtil::read(chunk); } void ParserListener::onMessageEnd() { messageEnd = true; } void ParserListener::onError(std::error_code ec) { errorCode = static_cast<HttpStatus>(ec.value()); } // }}} TEST(http_http1_Parser, requestLine0) { /* Seems like in HTTP/0.9 it was possible to create * very simple request messages. */ ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET /\r\n"); ASSERT_EQ("GET", listener.method); ASSERT_EQ("/", listener.entity); ASSERT_EQ(HttpVersion::VERSION_0_9, listener.version); ASSERT_TRUE(listener.headerEnd); ASSERT_TRUE(listener.messageEnd); ASSERT_EQ(0, listener.headers.size()); ASSERT_EQ(0, listener.body.size()); } TEST(http_http1_Parser, requestLine1) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET / HTTP/0.9\r\n\r\n"); ASSERT_EQ("GET", listener.method); ASSERT_EQ("/", listener.entity); ASSERT_EQ(HttpVersion::VERSION_0_9, listener.version); ASSERT_EQ(0, listener.headers.size()); ASSERT_EQ(0, listener.body.size()); } TEST(http_http1_Parser, requestLine2) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("HEAD /foo?bar HTTP/1.0\r\n\r\n"); ASSERT_EQ("HEAD", listener.method); ASSERT_EQ("/foo?bar", listener.entity); ASSERT_EQ(HttpVersion::VERSION_1_0, listener.version); ASSERT_EQ(0, listener.headers.size()); ASSERT_EQ(0, listener.body.size()); } TEST(http_http1_Parser, requestLine_invalid1_MissingPathAndProtoVersion) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET\r\n\r\n"); ASSERT_EQ(HttpStatus::BadRequest, listener.errorCode); } TEST(http_http1_Parser, requestLine_invalid3_InvalidVersion) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET / HTTP/0\r\n\r\n"); ASSERT_EQ((int)HttpStatus::BadRequest, (int)listener.errorCode); } TEST(http_http1_Parser, requestLine_invalid3_CharsAfterVersion) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET / HTTP/1.1b\r\n\r\n"); ASSERT_EQ((int)HttpStatus::BadRequest, (int)listener.errorCode); } TEST(http_http1_Parser, requestLine_invalid5_SpaceAfterVersion) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET / HTTP/1.1 \r\n\r\n"); ASSERT_EQ((int)HttpStatus::BadRequest, (int)listener.errorCode); } TEST(http_http1_Parser, requestLine_invalid6_UnsupportedVersion) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); // Actually, we could make it a ParserError, or HttpClientError or so, // But to make googletest lib happy, we should make it even a distinct class. ASSERT_THROW(parser.parseFragment("GET / HTTP/1.2\r\n\r\n"), RuntimeError); } TEST(http_http1_Parser, headers1) { ParserListener listener; Parser parser(Parser::MESSAGE, &listener); parser.parseFragment( "Foo: the foo\r\n" "Content-Length: 6\r\n" "\r\n" "123456"); ASSERT_EQ("Foo", listener.headers[0].first); ASSERT_EQ("the foo", listener.headers[0].second); ASSERT_EQ("123456", listener.body); } TEST(http_http1_Parser, invalidHeader1) { ParserListener listener; Parser parser(Parser::MESSAGE, &listener); size_t n = parser.parseFragment("Foo : the foo\r\n" "\r\n"); ASSERT_EQ(HttpStatus::BadRequest, listener.errorCode); ASSERT_EQ(3, n); ASSERT_EQ(0, listener.headers.size()); } TEST(http_http1_Parser, invalidHeader2) { ParserListener listener; Parser parser(Parser::MESSAGE, &listener); size_t n = parser.parseFragment("Foo\r\n" "\r\n"); ASSERT_EQ(HttpStatus::BadRequest, listener.errorCode); ASSERT_EQ(5, n); ASSERT_EQ(0, listener.headers.size()); } TEST(http_http1_Parser, requestWithHeaders) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment( "GET / HTTP/0.9\r\n" "Foo: the foo\r\n" "X-Bar: the bar\r\n" "\r\n"); ASSERT_EQ("GET", listener.method); ASSERT_EQ("/", listener.entity); ASSERT_EQ(HttpVersion::VERSION_0_9, listener.version); ASSERT_EQ(2, listener.headers.size()); ASSERT_EQ(0, listener.body.size()); ASSERT_EQ("Foo", listener.headers[0].first); ASSERT_EQ("the foo", listener.headers[0].second); ASSERT_EQ("X-Bar", listener.headers[1].first); ASSERT_EQ("the bar", listener.headers[1].second); } TEST(http_http1_Parser, requestWithHeadersAndBody) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment( "GET / HTTP/0.9\r\n" "Foo: the foo\r\n" "X-Bar: the bar\r\n" "Content-Length: 6\r\n" "\r\n" "123456"); ASSERT_EQ("123456", listener.body); } // no chunks except the EOS-chunk TEST(http_http1_Parser, requestWithHeadersAndBodyChunked1) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment( "GET / HTTP/0.9\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "0\r\n" "\r\n"); ASSERT_EQ("", listener.body); } // exactly one data chunk TEST(http_http1_Parser, requestWithHeadersAndBodyChunked2) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment( "GET / HTTP/0.9\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "6\r\n" "123456" "\r\n" "0\r\n" "\r\n"); ASSERT_EQ("123456", listener.body); } // more than one data chunk TEST(http_http1_Parser, requestWithHeadersAndBodyChunked3) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment( "GET / HTTP/0.9\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "6\r\n" "123456" "\r\n" "6\r\n" "123456" "\r\n" "0\r\n" "\r\n"); ASSERT_EQ("123456123456", listener.body); } // first chunk is missing CR LR TEST(http_http1_Parser, requestWithHeadersAndBodyChunked_invalid1) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); size_t n = parser.parseFragment( "GET / HTTP/0.9\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "6\r\n" "123456" //"\r\n" // should bailout here "0\r\n" "\r\n"); ASSERT_EQ(55, n); ASSERT_EQ(HttpStatus::BadRequest, listener.errorCode); } TEST(http_http1_Parser, pipelined1) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); constexpr BufferRef input = "GET /foo HTTP/1.1\r\n\r\n" "HEAD /bar HTTP/0.9\r\n\r\n"; size_t n = parser.parseFragment(input); EXPECT_EQ("GET", listener.method); EXPECT_EQ("/foo", listener.entity); EXPECT_EQ(HttpVersion::VERSION_1_1, listener.version); parser.parseFragment(input.ref(n)); EXPECT_EQ("HEAD", listener.method); EXPECT_EQ("/bar", listener.entity); EXPECT_EQ(HttpVersion::VERSION_0_9, listener.version); }
28.280453
80
0.683863
pjsaksa
1c071123e27cd580970c23437b07e9d79b516281
78,938
cpp
C++
ImportantExample/QTDbfDemo/src/dbfeditor.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
3
2018-12-24T19:35:52.000Z
2022-02-04T14:45:59.000Z
ImportantExample/QTDbfDemo/src/dbfeditor.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
null
null
null
ImportantExample/QTDbfDemo/src/dbfeditor.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
1
2019-05-09T02:42:40.000Z
2019-05-09T02:42:40.000Z
#/********************************************************************************/ #/* */ #/* Copyright 2011 Alexander Vorobyev (Voral) */ #/* http://va-soft.ru/ */ #/* */ #/* Copyright (C) 2009 Hevele Hegyi Istvan. */ #/* */ #/* This file is part of qtDbf. */ #/* */ #/* Basetest 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 3 of the License, or */ #/* (at your option) any later version. */ #/* */ #/* Basetest 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 protime. If not, see <http://www.gnu.org/licenses/>. */ #/* */ #/********************************************************************************/ #include <QtSql> #include <QDateEdit> #include <QClipboard> #include <QMessageBox> #include <QFileDialog> #include <QApplication> #include <QPlainTextEdit> #include "structures.h" #include "dbfeditor.h" #include "widgets.h" #include "customsqlmodel.h" #include "qtcalculator.h" #include "dbfconfig.h" #include "globals.h" #include "dialogfilter.h" #include "dialogagregat.h" QDbfEditor::QDbfEditor(QString &a_dbfFileName, const QString &title, QWidget *parent) : QWidget(parent) { QHBoxLayout *mainLayout = new QHBoxLayout(this); view = new QDbfTableView(this); openAction = new QAction(QIcon(":/open.png"),tr("Open").append(" Ctrl + O"), this); openAction->setShortcut(Qt::CTRL + Qt::Key_O); connect(openAction, SIGNAL(triggered()), this, SLOT(openNewFile())); addAction(openAction); fillAction = new QAction(QIcon(":/fill.png"),tr("Fill"), this); connect(fillAction, SIGNAL(triggered()), this, SLOT(fillCells())); addAction(fillAction); editAction = new QAction(QIcon(":/edit.png"),tr("Edit").append(" Enter"), this); editAction->setShortcut(Qt::Key_Return); connect(editAction, SIGNAL(triggered()), this, SLOT(editRecord())); addAction(editAction); insertAction = new QAction(QIcon(":/add.png"),tr("Add").append(" Ins"), this); insertAction->setShortcut(Qt::Key_Insert); connect(insertAction, SIGNAL(triggered()), this, SLOT(insertRecord())); addAction(insertAction); deleteAction = new QAction(QIcon(":/remove.png"),tr("Delete").append(" Del"), this); deleteAction->setShortcut(Qt::Key_Delete); connect(deleteAction, SIGNAL(triggered()), this, SLOT(deleteRecord())); addAction(deleteAction); saveAction = new QAction(QIcon(":/save.png"),tr("Save").append(" Ctrl + S"), this); connect(saveAction, SIGNAL(triggered()), this, SLOT(saveDbfFile())); saveAction->setShortcut(Qt::CTRL + Qt::Key_S); addAction(saveAction); configAction = new QAction(QIcon(":/config.png"),tr("Configure"), this); connect(configAction, SIGNAL(triggered()), this, SLOT(configApp())); addAction(configAction); helpAction = new QAction(QIcon(":/help.png"),tr("Help").append(" F1"), this); helpAction->setShortcut(Qt::Key_F1); connect(helpAction, SIGNAL(triggered()), this, SLOT(helpDbf())); addAction(helpAction); calcAction = new QAction(QIcon(":/calc.png"),tr("Calculator").append(" Ctrl + E"), this); saveAction->setShortcut(Qt::CTRL + Qt::Key_E); connect(calcAction, SIGNAL(triggered()), this, SLOT(calculator())); addAction(calcAction); quitAction = new QAction(QIcon(":/quit.png"),tr("Close").append(" Esc"), this); saveAction->setShortcut(Qt::Key_Escape); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(closeAllWindows())); addAction(quitAction); filterAction = new QAction(QIcon(":/filter.png"),tr("Set filter").append(" Ctrl + F"), this); filterAction->setShortcut(Qt::CTRL + Qt::Key_F); filterAction->setCheckable(true); connect(filterAction, SIGNAL(triggered(bool)), this, SLOT(filter(bool))); addAction(filterAction); agregatAction = new QAction(QIcon(":/functions.png"),tr("Average functions").append(" Ctrl + A"), this); agregatAction->setShortcut(Qt::CTRL + Qt::Key_A); connect(agregatAction, SIGNAL(triggered()), this, SLOT(agregat())); addAction(agregatAction); openButton = new QDbfToolButton(this); openButton->setDefaultAction(openAction); editButton = new QDbfToolButton(this); editButton->setDefaultAction(editAction); insertButton = new QDbfToolButton(this); insertButton->setDefaultAction(insertAction); deleteButton = new QDbfToolButton(this); deleteButton->setDefaultAction(deleteAction); saveButton = new QDbfToolButton(this); saveButton->setDefaultAction(saveAction); fillButton = new QDbfToolButton(this); fillButton->setDefaultAction(fillAction); configButton = new QDbfToolButton(this); configButton->setDefaultAction(configAction); helpButton = new QDbfToolButton(this); helpButton->setDefaultAction(helpAction); calcButton = new QDbfToolButton(this); calcButton->setDefaultAction(calcAction); quitButton = new QDbfToolButton(this); quitButton->setDefaultAction(quitAction); filterButton = new QDbfToolButton(this); filterButton->setDefaultAction(filterAction); agregatButton = new QDbfToolButton(this); agregatButton->setDefaultAction(agregatAction); openButton->setFocusPolicy(Qt::NoFocus); editButton->setFocusPolicy(Qt::NoFocus); insertButton->setFocusPolicy(Qt::NoFocus); deleteButton->setFocusPolicy(Qt::NoFocus); fillButton->setFocusPolicy(Qt::NoFocus); saveButton->setFocusPolicy(Qt::NoFocus); configButton->setFocusPolicy(Qt::NoFocus); helpButton->setFocusPolicy(Qt::NoFocus); calcButton->setFocusPolicy(Qt::NoFocus); quitButton->setFocusPolicy(Qt::NoFocus); filterButton->setFocusPolicy(Qt::NoFocus); agregatButton->setFocusPolicy(Qt::NoFocus); QVBoxLayout *buttonLayout = new QVBoxLayout; buttonLayout->addWidget(openButton); buttonLayout->addWidget(fillButton); buttonLayout->addWidget(editButton); buttonLayout->addWidget(insertButton); buttonLayout->addWidget(deleteButton); buttonLayout->addWidget(saveButton); buttonLayout->addWidget(filterButton); buttonLayout->addWidget(agregatButton); buttonLayout->addWidget(configButton); buttonLayout->addWidget(calcButton); buttonLayout->addWidget(helpButton); buttonLayout->addStretch(1); buttonLayout->addWidget(quitButton); mainLayout->addWidget(view); mainLayout->addLayout(buttonLayout); connect(this, SIGNAL(modelIsEmpty(bool)), editAction, SLOT(setDisabled(bool))); connect(this, SIGNAL(modelIsEmpty(bool)), deleteAction, SLOT(setDisabled(bool))); connect(this, SIGNAL(modelIsEmpty(bool)), fillAction, SLOT(setDisabled(bool))); connect(view, SIGNAL(editSignal()), this, SLOT(editRecord())); connect(view, SIGNAL(insertSignal()), this, SLOT(insertRecord())); connect(view, SIGNAL(deleteSignal()), this, SLOT(deleteRecord())); connect(view, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(editRecord())); connect(view, SIGNAL(quitSignal()), qApp, SLOT(closeAllWindows())); connect(parent, SIGNAL(setToolButtonIconSize(int)), this, SLOT(setToolButtonIconSize(int))); openFile(a_dbfFileName,false); if (model->rowCount() == 0) emit modelIsEmpty(true); else emit modelIsEmpty(false); view->setFocus(); } void QDbfEditor::setModified(bool value) { modified = value; emit modifiedChanged(value); saveAction->setEnabled(value); } void QDbfEditor::openFile(QString &a_dbfFileName,bool fresh = false) { where = ""; order = ""; filterAction->setChecked(false); if (fresh) { delete this->model; delete fieldsItem; while (fieldsCollection.count()>0) { fieldsCollection.removeLast(); } } setModified(false); dbfFileName = a_dbfFileName; int current; readSettings(); openDbfFile(); QString query; QSqlQuery getData(QSqlDatabase::database("dbfEditor")); int i; query = "SELECT id_"; query += tableName; query += ","; for (i=0;i<fieldsCollection.count();i++) { query += ("`"+fieldsCollection.at(i)->fieldName+"`"); if (i<fieldsCollection.count()-1) query += ","; } query +=" FROM "; query += tableName; model = new QDbfSqlModel(this); for (i=0;i<fieldsCollection.count();i++) { if (fieldsCollection.at(i)->fieldType == "C") model->addCharField(i+1); if (fieldsCollection.at(i)->fieldType == "Y") model->addCurrencyField(i+1); if (fieldsCollection.at(i)->fieldType == "N") model->addNumericField(i+1); if (fieldsCollection.at(i)->fieldType == "F") model->addNumericField(i+1); if (fieldsCollection.at(i)->fieldType == "D") model->addDateField(i+1); if (fieldsCollection.at(i)->fieldType == "T") model->addTimeField(i+1); if (fieldsCollection.at(i)->fieldType == "B") model->addDoubleField(i+1); if (fieldsCollection.at(i)->fieldType == "I") model->addIntField(i+1); if (fieldsCollection.at(i)->fieldType == "L") model->addLogicalField(i+1); if ((fieldsCollection.at(i)->fieldType == "M") && (fieldsCollection.at(i)->fieldSize == 10)) model->addMemoField(i+1); if ((fieldsCollection.at(i)->fieldType == "M") && (fieldsCollection.at(i)->fieldSize == 4)) model->addMemo4Field(i+1); if (fieldsCollection.at(i)->fieldType == "G") model->addGeneralField(i+1); } model->setQuery(query, QSqlDatabase::database("dbfEditor")); if (model->lastError().isValid()) { QMessageBox::critical(this, tr("Error"), model->lastError().text()); } QString tempChar; QString tempValue; model->setHeaderData(0, Qt::Horizontal, tr("ID")); for (int i=0; i<fieldsCollection.count(); ++i) { tempValue = fieldsCollection.at(i)->fieldName; tempValue += " ("; tempValue += fieldsCollection.at(i)->fieldType; tempChar.setNum(fieldsCollection.at(i)->fieldSize); tempValue += tempChar; if (fieldsCollection.at(i)->fieldDecimals != 0) { tempValue += ","; tempChar.setNum(fieldsCollection.at(i)->fieldDecimals); tempValue += tempChar; } tempValue += ")"; model->setHeaderData(i+1, Qt::Horizontal, tempValue); } view->setModel(model); refresh(0); current = view->currentIndex().row(); QSqlRecord record = model->record(current); recordId = record.value(0).toString(); setModified(false); } void QDbfEditor::writeSettings() { QSettings settings; settings.setValue("dbfeditor/Size", size()); settings.setValue("dbfeditor/edSize", editDialogSize); } void QDbfEditor::readSettings() { QSettings settings; QSize size = settings.value("dbfeditor/Size", QSize(900, 600)).toSize(); resize(size); editDialogSize = settings.value("dbfeditor/edSize", QSize(400,217)).toSize(); } void QDbfEditor::filter(bool on) { if (on) { int c = view->currentIndex().column(); DialogFilter *dlg = new DialogFilter(fieldsCollection,tr("Filter"),fieldsCollection.at(c-1)->fieldName,this); if (dlg->exec() == QDialog::Accepted) where = dlg->getWhere(); else filterAction->setChecked(false); dlg->deleteLater(); } else { filterAction->setChecked(false); where = ""; } QString query; query = "SELECT * FROM "; query += tableName; if (where != "") query += " WHERE " + where; if (order != "") query += " ORDER BY " + order; model->setQuery(query, QSqlDatabase::database("dbfEditor")); if (model->lastError().isValid()) { QMessageBox::critical(this, tr("Error"), model->lastError().text()); return; } refresh(0); } void QDbfEditor::editRecord() { QModelIndexList currentSelection = view->selectionModel()->selectedIndexes(); QModelIndex currentIndex = view->currentIndex(); //int i; QDate tempDate; if (currentSelection.count() == 0) { QMessageBox::critical(this, tr("Error"), tr("Select at least a cell")); return; } int r = view->currentIndex().row(); int c = view->currentIndex().column(); QSqlRecord record = model->record(r); recordId = record.value(0).toString(); QSqlQuery modelQuery = model->query(); QString oldQuery = modelQuery.lastQuery(); QSqlQuery getData(QSqlDatabase::database("dbfEditor")); QString query; QString editValue; QByteArray editByteArray; query = "SELECT "; query += ("`"+fieldsCollection.at(c-1)->fieldName+"`"); query += " FROM "; query += tableName; query += " WHERE id_"; query += tableName; query += "="; query += recordId; query += ""; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } while (getData.next()) { editByteArray = getData.value(0).toByteArray(); editValue = getData.value(0).toString().simplified(); tempDate = getData.value(0).toDate(); } bool ok; if (fieldsCollection.at(c-1)->fieldType == "M") { /* 0x02 FoxBASE 0x03 FoxBASE+/Dbase III plus, no memo 0x30 Visual FoxPro 0x31 Visual FoxPro, autoincrement enabled 0x32 Visual FoxPro with field type Varchar or Varbinary 0x43 dBASE IV SQL table files, no memo 0x63 dBASE IV SQL system files, no memo 0x83 FoxBASE+/dBASE III PLUS, with memo 0x8B dBASE IV with memo 0xCB dBASE IV SQL table files, with memo 0xF5 FoxPro 2.x (or earlier) with memo 0xE5 HiPer-Six format with SMT memo file 0xFB FoxBASE */ //0x83 FoxBASE+/dBASE III PLUS, with memo if ((dbfFileHeader[0] == '\x83')) readDbtFile(editValue.toInt(&ok,10)); //0xF5 FoxPro 2.x (or earlier) with memo if (dbfFileHeader[0] == '\xF5') (editValue.toInt(&ok,10)); /* 0x30 Visual FoxPro 0x31 Visual FoxPro, autoincrement enabled 0x32 Visual FoxPro with field type Varchar or Varbinary */ if ((dbfFileHeader[0] == '\x30') ||(dbfFileHeader[0] == '\x31') || (dbfFileHeader[0] == '\x32')) { editByteArray = QByteArray::fromHex(editByteArray); quint32 l = *(quint32 *)editByteArray.data(); readFptFile(l); } //0x8B dBASE IV with memo if (dbfFileHeader[0] == '\x8B') readDbt4File(editValue.toInt(&ok,10)); return; } QDbfDialog *d = new QDbfDialog(tr("Edit"), this); QSettings settings; d->resize(settings.value("dbfeditor/edsize", QSize(140,40)).toSize()); QVBoxLayout *mainLayout = new QVBoxLayout; QString labelText; QString tempValue; tempValue = ""; labelText = "<b>"; labelText += fieldsCollection.at(c-1)->fieldName; labelText += " "; labelText += fieldsCollection.at(c-1)->fieldType; labelText += "("; tempValue.setNum(fieldsCollection.at(c-1)->fieldSize); labelText += tempValue; if (fieldsCollection.at(c-1)->fieldDecimals != 0) { labelText += ","; tempValue.clear(); tempValue.setNum(fieldsCollection.at(c-1)->fieldDecimals); labelText += tempValue; } labelText += ")</b>"; QLabel *label = new QLabel(labelText, d); QDbfLineEdit *l; QDateTimeEdit *dte; QDateEdit *de; QString inputMaskFormat; QTime tempTime; quint32 l1; qint32 l2; qint64 l3; double db; quint8 tempByte; if (fieldsCollection.at(c-1)->fieldType == "C") { l = new QDbfLineEdit(editValue,d); l->setMaxLength(fieldsCollection.at(c-1)->fieldSize); l->selectAll(); } else if (fieldsCollection.at(c-1)->fieldType == "L") { l = new QDbfLineEdit(editValue,d); l->setMaxLength(fieldsCollection.at(c-1)->fieldSize); } else if (fieldsCollection.at(c-1)->fieldType == "D") { de = new QDateEdit(tempDate, d); QFont font = de->font(); font.setPointSize(font.pointSize() + 5); de->setFont(font); de->setCalendarPopup(true); de->setDisplayFormat("dd.MM.yyyy"); } else if (fieldsCollection.at(c-1)->fieldType == "Y") { editByteArray = QByteArray::fromHex(editByteArray); l3 = *(qint64 *)editByteArray.data(); db = l3; tempValue.setNum(db/10000,'f',4); l = new QDoubleLineEdit(tempValue,d); l->selectAll(); } else if (fieldsCollection.at(c-1)->fieldType == "T") { editByteArray = QByteArray::fromHex(editByteArray); l1 = *(quint32 *)editByteArray.data(); tempDate = QDate::fromJulianDay(l1); l1 = *(quint32 *)(editByteArray.data()+4); tempTime.setHMS(0,0,0); tempTime = tempTime.addMSecs(l1); QDateTime dt(tempDate,tempTime); dte = new QDateTimeEdit(dt,d); dte->setDisplayFormat("dd.MM.yyyy hh:mm:ss.zzz"); QFont font = dte->font(); font.setPointSize(font.pointSize() + 5); dte->setFont(font); dte->setCalendarPopup(true); } else if (fieldsCollection.at(c-1)->fieldType == "I") { editByteArray = QByteArray::fromHex(editByteArray); l2 = *(qint32 *)editByteArray.data(); tempValue.setNum(l2, 10); l = new QDoubleLineEdit(tempValue,d); l->setMaxLength(fieldsCollection.at(c-1)->fieldSize); l->selectAll(); } else if (fieldsCollection.at(c-1)->fieldType == "B") { editByteArray = QByteArray::fromHex(editByteArray); db = *(double *)editByteArray.data(); tempValue.setNum(db); l = new QDoubleLineEdit(tempValue,d); l->selectAll(); } else if ((fieldsCollection.at(c-1)->fieldType == "N") || (fieldsCollection.at(c-1)->fieldType == "F")) { l = new QDoubleLineEdit(editValue,d); l->setMaxLength(fieldsCollection.at(c-1)->fieldSize); l->selectAll(); } else { QMessageBox::information(this, tr("Edit"), tr("Unsupported field (yet)")); return; } if (fieldsCollection.at(c-1)->fieldType == "T") { label->setBuddy(dte); } else if (fieldsCollection.at(c-1)->fieldType == "D") { label->setBuddy(de); } else { d->insertLineEditToVerify(l); label->setBuddy(l); } QPushButton *okButton = new QPushButton(tr("OK"), d); QPushButton *cancelButton = new QPushButton(tr("Cancel"), d); QHBoxLayout *buttonLayout = new QHBoxLayout; buttonLayout->addStretch(1); buttonLayout->addWidget(okButton); buttonLayout->addWidget(cancelButton); mainLayout->addWidget(label); if (fieldsCollection.at(c-1)->fieldType == "T") { mainLayout->addWidget(dte); } else if (fieldsCollection.at(c-1)->fieldType == "D") { mainLayout->addWidget(de); } else { mainLayout->addWidget(l); } mainLayout->addStretch(1); mainLayout->addLayout(buttonLayout); connect(okButton, SIGNAL(clicked()), d, SLOT(verifyDbfInputLines())); connect(cancelButton, SIGNAL(clicked()), d, SLOT(reject())); d->setLayout(mainLayout); if (d->exec()) { if (d->result() == QDialog::Accepted) { if (fieldsCollection.at(c-1)->fieldType == "T") { setModified(true); } else if (fieldsCollection.at(c-1)->fieldType == "D") { setModified(true); } else { if (l->text() != editValue) { setModified(true); } } query = "UPDATE "; query += tableName; query += " SET "; query += ("`"+fieldsCollection.at(c-1)->fieldName+"`"); query += "='"; if ((fieldsCollection.at(c-1)->fieldType == "N") || ((fieldsCollection.at(c-1)->fieldType == "F"))) { db = l->text().toDouble(&ok); tempValue.setNum(db,'f',fieldsCollection.at(c-1)->fieldDecimals); query += tempValue; } else if (fieldsCollection.at(c-1)->fieldType == "T") { editByteArray.clear(); l1 = dte->dateTime().date().toJulianDay(); tempByte = l1; editByteArray.append(tempByte); tempByte = l1 >> 8; editByteArray.append(tempByte); tempByte = l1 >> 16; editByteArray.append(tempByte); tempByte = l1 >> 24; editByteArray.append(tempByte); l1 = dte->dateTime().time().msecsTo(QTime(0,0,0)); l1 = l1*(-1); tempByte = l1; editByteArray.append(tempByte); tempByte = l1 >> 8; editByteArray.append(tempByte); tempByte = l1 >> 16; editByteArray.append(tempByte); tempByte = l1 >> 24; editByteArray.append(tempByte); query += editByteArray.toHex().toUpper(); } else if (fieldsCollection.at(c-1)->fieldType == "D") { query+= de->date().toString("yyyy-MM-dd"); } else if (fieldsCollection.at(c-1)->fieldType == "I") { l2 = l->text().toLong(&ok, 10); editByteArray.clear(); editByteArray = editByteArray.fromRawData((const char*)&l2,4); query += editByteArray.toHex().toUpper(); } else if (fieldsCollection.at(c-1)->fieldType == "Y") { db = l->text().toDouble(&ok); db = db*10000; tempValue.setNum(db,'f',0); l3 = tempValue.toLongLong(&ok, 10); editByteArray.clear(); editByteArray = editByteArray.fromRawData((const char*)&l3,8); query += editByteArray.toHex().toUpper(); } else if (fieldsCollection.at(c-1)->fieldType == "B") { db = l->text().toDouble(&ok); editByteArray.clear(); editByteArray = editByteArray.fromRawData((const char*)&db,8); query += editByteArray.toHex().toUpper(); } else { query += l->text(); } query += "' WHERE id_"; query += tableName; query += "='"; query += recordId; query += "'"; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } model->setQuery(oldQuery, QSqlDatabase::database("dbfEditor")); if (model->lastError().isValid()) { QMessageBox::critical(this, tr("Error"), model->lastError().text()); return; } refresh(c); view->setCurrentIndex(currentIndex); } } settings.setValue("dbfeditor/edsize", d->size()); delete d; } void QDbfEditor::insertRecord() { QSqlQuery modelQuery = model->query(); QString oldQuery = modelQuery.lastQuery(); QSqlQuery getData(QSqlDatabase::database("dbfEditor")); QString query; int j; QStringList fieldTypes; bool ok = true; for (j = 0;j<fieldsCollection.count();j++) { fieldsItem = fieldsCollection.at(j); //if ((fieldsItem->fieldType == "M") && (fieldsItem->fieldSize == 4)) // ok = false; if (!fieldTypes.contains(fieldsItem->fieldType)) fieldTypes.append(fieldsItem->fieldType); } if (fieldTypes.contains("0")) { ok = false; } if (!ok) { QMessageBox::information(this, tr("Insert"), tr("The file contains unsupported fields.")); return; } query = "INSERT INTO "; query += tableName; query += " ("; for (j=0; j<fieldsCollection.count(); ++j) { query += ("`"+fieldsCollection.at(j)->fieldName+"`"); if (j<fieldsCollection.count()-1) query += ","; } query += ") VALUES ("; QString tempValue; for (j=0; j<fieldsCollection.count(); j++) { fieldsItem = fieldsCollection.at(j); if (fieldsItem->fieldType == "D") { query += "' '"; } else if (fieldsItem->fieldType == "L") { query += "'F'"; } else if (fieldsItem->fieldType == "C") { query += "' '"; } else if (fieldsItem->fieldType == "N") { query += "0"; } else if ((fieldsItem->fieldType == "Y") || (fieldsItem->fieldType == "T") || (fieldsItem->fieldType == "B") || (fieldsItem->fieldType == "I") || (fieldsItem->fieldType == "G") || ((fieldsItem->fieldType == "M") && (fieldsItem->fieldSize == 4))) { query += "'"; for (int i=0;i<fieldsItem->fieldSize;i++) query += "00"; query += "'"; } else { query += "''"; } if (j<fieldsCollection.count()-1) query += ","; } query += ")"; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } model->setQuery(oldQuery, QSqlDatabase::database("dbfEditor")); if (model->lastError().isValid()) { QMessageBox::critical(this, tr("Error"), model->lastError().text()); return; } if (model->rowCount() == 0) emit modelIsEmpty(true); else emit modelIsEmpty(false); setModified(true); } void QDbfEditor::deleteRecord() { int current; QModelIndexList currentSelection = view->selectionModel()->selectedIndexes(); if (currentSelection.count() == 0) { QMessageBox::critical(this, tr("Error"), tr("Select at least a row")); return; } QString ids; int i; int k; QList <int> rowCollection; ids = "("; for (i = 0; i < currentSelection.count(); i++) { current = currentSelection.at(i).row(); if (!rowCollection.contains(current)) rowCollection.append(current); } for (i=0;i<rowCollection.count();i++) { QSqlRecord record = model->record(rowCollection.at(i)); ids += record.value(0).toString(); ids += ","; } k = ids.length(); ids.truncate(k-1); ids += ")"; QSqlQuery modelQuery = model->query(); QString oldQuery = modelQuery.lastQuery(); QSqlRecord record = model->record(current); recordId = record.value(0).toString(); QString query; QSqlQuery getData(QSqlDatabase::database("dbfEditor")); QMessageBox::StandardButton reply; reply = QMessageBox::question(this, tr("Delete current row"),tr("<center><h1><font color='red'>Warning !</font></h1>" "<h3>You are about to delete the current record</h3>" "<h2>Are you sure?</h2></center>"), QMessageBox::Yes | QMessageBox::No ); if (reply == QMessageBox::Yes) { query = "DELETE FROM "; query += tableName; query += " WHERE id_"; query += tableName; query += " IN "; query += ids; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Eroare"), getData.lastError().text()); return; } model->setQuery(oldQuery, QSqlDatabase::database("dbfEditor")); if (model->lastError().isValid()) { QMessageBox::critical(this, tr("Eroare"), model->lastError().text()); return; } if (model->rowCount() != 0) { current--; } refresh(current); QSqlRecord record = model->record(current); recordId = record.value(0).toString(); setModified(true); } if (model->rowCount() == 0) emit modelIsEmpty(true); else emit modelIsEmpty(false); } void QDbfEditor::openNewFile() { // Временная мера. Пока не сделан рефактоинг кода. if (modified) { QMessageBox::StandardButton reply; reply = QMessageBox::question(this, tr("Save"),tr("<center><h2>Do you want to save the changes?</h2></center>"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes ); if (reply == QMessageBox::Yes) { saveDbfFile(); } } QString currentDirectory; QSettings settings; currentDirectory= settings.value("dbfeditor/currentdir", "./").toString(); dbfFileName = QFileDialog::getOpenFileName(0, QObject::tr("Open File"),currentDirectory,"DBF Files(*.dbf);;All Files (*)"); if (dbfFileName.isEmpty()) { return; } emit fileOpened(dbfFileName); QFileInfo fileInfo(dbfFileName); currentDirectory = fileInfo.absolutePath(); settings.setValue("dbfeditor/currentdir", currentDirectory); openFile(dbfFileName,true); } void QDbfEditor::openDbfFile() { /* DBF File Header Byte offset Description 0 File type: 0x02 FoxBASE 0x03 FoxBASE+/Dbase III plus, no memo 0x30 Visual FoxPro 0x31 Visual FoxPro, autoincrement enabled 0x32 Visual FoxPro with field type Varchar or Varbinary 0x43 dBASE IV SQL table files, no memo 0x63 dBASE IV SQL system files, no memo 0x83 FoxBASE+/dBASE III PLUS, with memo 0x8B dBASE IV with memo 0xCB dBASE IV SQL table files, with memo 0xF5 FoxPro 2.x (or earlier) with memo 0xE5 HiPer-Six format with SMT memo file 0xFB FoxBASE 1 - 3 Last update (YYMMDD) 4 – 7 Number of records in file 8 – 9 Position of first data record 10 – 11 Length of one data record, including delete flag 12 – 27 Reserved 28 Table flags: 0x01 file has a structural .cdx 0x02 file has a Memo field 0x04 file is a database (.dbc) This byte can contain the sum of any of the above values. For example, the value 0x03 indicates the table has a structural .cdx and a Memo field. 29 Code page mark 30 – 31 Reserved, contains 0x00 32 – n Field subrecords The number of fields determines the number of field subrecords. One field subrecord exists for each field in the table. n+1 Header record terminator (0x0D) n+2 to n+264 A 263-byte range that contains the backlink, which is the relative path of an associated database (.dbc) file, information. If the first byte is 0x00, the file is not associated with a database. Therefore, database files always contain 0x00. Field Subrecords Structure Byte offset Description 0 – 10 Field name with a maximum of 10 characters. If less than 10, it is padded with null characters (0x00). 11 Field type: C – Character 255 bytes ASCII Y – Currency 8 bytes 64 bit integer, allways 4 decimal points N – Numeric F – Float Same as numeric 1 to 20 bytes in table D – Date yyyymmdd T – DateTime It's stored as an 8 byte field. The first 4 bytes stores the date as julian day number. The second 4 bytes stores the number of milliseconds after midnight. B – Double 8 bytes I – Integer 4 bytes L – Logical M – Memo 10 bytes ASCII integer in dBase FoxPro 4 bytes binary integer in Visual FoxPro G – General 4 byte reference to an OLE object C – Character (binary) M – Memo (binary) P – Picture 12 – 15 Displacement of field in record 16 Length of field (in bytes) 17 Number of decimal places 18 Field flags: 0x01 System Column (not visible to user) 0x02 Column can store null values 0x04 Binary column (for CHAR and MEMO only) 0x06 (0x02+0x04) When a field is NULL and binary (Integer, Currency, and Character/Memo fields) 0x0C Column is autoincrementing 19 - 22 Value of autoincrement Next value 23 Value of autoincrement Step value 24 – 31 Reserved */ QString query; QFile file; QByteArray fieldDescription; int i; int j; unsigned char a,b,c,d,e,f,g,h; double db; tableName = "d_table"; strTableName = "s_table"; file.setFileName(dbfFileName); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), tr("DBF open error")); return; } // QTextCodec::setCodecForCStrings(QTextCodec::codecForName(generalTextCodec.toAscii().data())); sizesHeader.clear(); sizesHeader = file.read(16); a = sizesHeader.at(4); b = sizesHeader.at(5); c = sizesHeader.at(6); d = sizesHeader.at(7); e = sizesHeader.at(8); f = sizesHeader.at(9); g = sizesHeader.at(10); h = sizesHeader.at(11); numberOfRecords = a + (b << 8) + (c << 16) + (d << 24); headerLength = e + (f << 8); recordLength = g + (h << 8); file.seek(0); dbfFileHeader = file.read(headerLength); file.seek(32); fieldDescriptions.clear(); fieldDescriptions = file.read(headerLength - 32); fieldDescriptions.truncate(fieldDescriptions.lastIndexOf('\x0D')); numberOfFields = fieldDescriptions.count() >> 5; qint16 tempOffset = 1; for (i=0;i<numberOfFields;i++) { fieldDescription = fieldDescriptions.mid(i*32,32); fieldsItem = new QFieldsItem; fieldsItem->fieldName = ""; j = 0; while (fieldDescription[j] != '\x00') { fieldsItem->fieldName += fieldDescription[j]; j++; } a = fieldDescription.at(12); b = fieldDescription.at(13); c = fieldDescription.at(14); d = fieldDescription.at(15); e = fieldDescription.at(16); f = fieldDescription.at(17); fieldsItem->fieldType = fieldDescription[11]; fieldsItem->fieldOffset = a + (b << 8) + (c << 16) + (d << 24); fieldsItem->fieldOffset = tempOffset; tempOffset += e; fieldsItem->fieldSize = e; fieldsItem->fieldDecimals = f; fieldsCollection.append(fieldsItem); } QSqlQuery getData(QSqlDatabase::database("dbfEditor")); query = "DROP TABLE IF EXISTS '"; query += tableName; query += "'"; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } QString tempValue; query = "CREATE TABLE '"; query += tableName; query += "' ( 'id_"; query += tableName; query += "' integer primary key autoincrement,"; for (i=0; i<fieldsCollection.count(); ++i) { query += ("`"+fieldsCollection.at(i)->fieldName+"`"); if (fieldsCollection.at(i)->fieldType == "C") { query += " text"; } else if (fieldsCollection.at(i)->fieldType == "L") { query += " text"; } else if (fieldsCollection.at(i)->fieldType == "M") { if (fieldsCollection.at(i)->fieldSize == 10) { query += " numeric"; } if (fieldsCollection.at(i)->fieldSize == 4) { query += " blob"; } } else if (fieldsCollection.at(i)->fieldType == "N") { query += " text"; } else if (fieldsCollection.at(i)->fieldType == "F") { query += " text"; } else if (fieldsCollection.at(i)->fieldType == "D") { query += " text"; } else { query += " blob"; } if (i<(fieldsCollection.count()-1)) query += ",\n"; } query += ")"; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } quint32 q; bool ok; for (q=0;q<numberOfRecords;q++) { query = "INSERT INTO "; query += tableName; query += " ("; for (j=0; j<fieldsCollection.count(); ++j) { query += ("`"+fieldsCollection.at(j)->fieldName+"`"); if (j<fieldsCollection.count()-1) query += ","; } query += ") VALUES ("; recordData.clear(); file.seek(headerLength + q*recordLength); recordData=file.read(recordLength); if (recordData.at(0) == '*') continue; QString tempDate; QString tempString; for (j=0; j<fieldsCollection.count(); j++) { fieldsItem = fieldsCollection.at(j); fieldsItem->fields = "'"; if (fieldsItem->fieldType == "D") { tempDate = recordData.mid(fieldsItem->fieldOffset,fieldsItem->fieldSize); if (tempDate == " ") fieldsItem->fields+=""; else { fieldsItem->fields += tempDate.mid(0,4); fieldsItem->fields += "-"; fieldsItem->fields += tempDate.mid(4,2); fieldsItem->fields += "-"; fieldsItem->fields += tempDate.mid(6,2); } } else if (fieldsItem->fieldType == "C") { tempString = recordData.mid(fieldsItem->fieldOffset,fieldsItem->fieldSize); fieldsItem->fields += tempString.replace("'","''"); } else if ((fieldsItem->fieldType == "N") || (fieldsItem->fieldType == "F")) { tempString = recordData.mid(fieldsItem->fieldOffset,fieldsItem->fieldSize); db = tempString.toDouble(&ok); tempString.setNum(db,'f',fieldsItem->fieldDecimals); fieldsItem->fields += tempString; } else if (fieldsItem->fieldType == "L") { tempString = recordData.mid(fieldsItem->fieldOffset,fieldsItem->fieldSize); fieldsItem->fields += tempString; } else if ((fieldsItem->fieldType == "M") && (fieldsItem->fieldSize == 10)) { tempString = recordData.mid(fieldsItem->fieldOffset,fieldsItem->fieldSize); fieldsItem->fields += tempString; } else { tempString = recordData.mid(fieldsItem->fieldOffset,fieldsItem->fieldSize).toHex().toUpper(); fieldsItem->fields += tempString; } fieldsItem->fields += "'"; query += fieldsItem->fields; if (j<fieldsCollection.count()-1) query += ","; } query += ")"; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } } query = "DROP TABLE IF EXISTS "; query += strTableName; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } query = "CREATE TABLE "; query += strTableName; query += " ( id_"; query += strTableName; query += " integer primary key autoincrement, \n"; query += "fieldName text, \n"; query += "fieldType text, \n"; query += "fieldLength numeric, \n"; query += "fieldDecimals numeric)"; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } for (i=0; i<fieldsCollection.count(); i++) { query = "INSERT INTO "; query += strTableName; query += " (fieldName, fieldType, fieldLength, fieldDecimals) VALUES ('"; query += ("`"+fieldsCollection.at(i)->fieldName+"`"); query += "','"; query += fieldsCollection.at(i)->fieldType; query += "','"; tempValue.setNum(fieldsCollection.at(i)->fieldSize,10); query += tempValue; query += "','"; tempValue.setNum(fieldsCollection.at(i)->fieldDecimals,10); query += tempValue; query += "')"; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } } file.close(); } void QDbfEditor::saveDbfFile() { qint32 nr; QSqlQuery getData(QSqlDatabase::database("dbfEditor")); QString query; bool ok; int i; nr = 0; query = "SELECT count(*) FROM "; query += tableName; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } while (getData.next()) nr = getData.value(0).toString().toULong(&ok, 10); qint16 lnrt = nr; qint16 hnrt = nr >> 16; qint8 llnrt = lnrt ; qint8 hlnrt = lnrt >> 8; qint8 lhnrt = hnrt; qint8 hhnrt = hnrt >> 8; dbfFileHeader[4]= llnrt; dbfFileHeader[5]= hlnrt; dbfFileHeader[6]= lhnrt; dbfFileHeader[7]= hhnrt; QFile dbfFile; dbfFile.setFileName(dbfFileName+".temp"); if (!dbfFile.open(QIODevice::WriteOnly)) { QMessageBox::critical(0, tr("Error"), tr("DBF write error")); return; } dbfFile.write(dbfFileHeader); QString tempValue; QTextStream textStream(&tempValue); query = "SELECT "; for (i=0;i<fieldsCollection.size();i++) { fieldsItem = fieldsCollection.at(i); query += ("`"+fieldsItem->fieldName+"`"); if ( i != fieldsCollection.size()-1 ) query += ","; else query += " "; } query += " FROM "; query += tableName; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(0, tr("Error"), getData.lastError().text()); return; } int l,l1,j; QString tempNumericValue; QDate tempDateValue; QString tempCharValue; QByteArray tempBinaryValue; while (getData.next()) { recordData.clear(); recordData.append(QChar(' ')); for (i=0;i<fieldsCollection.size();i++) { if ((fieldsCollection.at(i)->fieldType == "C") || (fieldsCollection.at(i)->fieldType == "L")) { tempCharValue = getData.value(i).toString(); tempValue = ""; l = fieldsCollection.at(i)->fieldSize; l1 = tempCharValue.length(); tempCharValue.truncate(l); tempValue = tempCharValue; for (j=0;j<l-l1;j++) tempValue+=" "; recordData.append(tempValue); } else if ((fieldsCollection.at(i)->fieldType == "N") || (fieldsCollection.at(i)->fieldType == "F") || ((fieldsCollection.at(i)->fieldType == "M") && (fieldsCollection.at(i)->fieldSize == 10))) { tempNumericValue = getData.value(i).toString().simplified(); tempValue = ""; l = fieldsCollection.at(i)->fieldSize; l1 = tempNumericValue.length(); tempNumericValue.truncate(l); for (j=0;j<l-l1;j++) tempValue+=" "; tempValue += tempNumericValue; recordData.append(tempValue); } else if (fieldsCollection.at(i)->fieldType == "D") { tempDateValue = getData.value(i).toDate(); if (tempDateValue.isNull()) tempValue = " "; else tempValue = tempDateValue.toString("yyyyMMdd"); recordData.append(tempValue); } else { tempBinaryValue = getData.value(i).toByteArray(); tempBinaryValue = tempBinaryValue.fromHex(tempBinaryValue); recordData.append(tempBinaryValue); } } dbfFile.write(recordData); } recordData.clear(); recordData.append('\x1A'); dbfFile.write(recordData); dbfFile.close(); QFile oldFile; oldFile.setFileName(dbfFileName); oldFile.remove(); dbfFile.rename(dbfFileName); setModified(false); } void QDbfEditor::fillCells() { QSqlQuery modelQuery = model->query(); QString oldQuery = modelQuery.lastQuery(); QSqlQuery getData(QSqlDatabase::database("dbfEditor")); QString query; QModelIndexList currentSelection = view->selectionModel()->selectedIndexes(); QModelIndexList currentRowSelection = view->selectionModel()->selectedRows(); QModelIndexList currentColumnSelection = view->selectionModel()->selectedColumns(); if (currentSelection.count() == 0) { QMessageBox::critical(this, tr("Error"), tr("Select at least a cell")); return; } QDbfDialog *d = new QDbfDialog(tr("Fill"), this); QSettings settings; d->resize(settings.value("dbfeditor/filledsize", QSize(140,40)).toSize()); QString sql = settings.value("dbfeditor/fillcommand", "").toString(); QVBoxLayout *mainLayout = new QVBoxLayout; QLabel *label = new QLabel(tr("Fill value or expression"), d); QDbfLineEdit *t = new QDbfLineEdit(sql,d); label->setBuddy(t); QPushButton *okButton = new QPushButton(tr("OK"), d); QPushButton *cancelButton = new QPushButton(tr("Cancel"), d); QHBoxLayout *buttonLayout = new QHBoxLayout; buttonLayout->addStretch(1); buttonLayout->addWidget(okButton); buttonLayout->addWidget(cancelButton); mainLayout->addWidget(label); mainLayout->addWidget(t); mainLayout->addStretch(1); mainLayout->addLayout(buttonLayout); connect(okButton, SIGNAL(clicked()), d, SLOT(accept())); connect(cancelButton, SIGNAL(clicked()), d, SLOT(reject())); d->setLayout(mainLayout); int i; if (d->exec()) { if (d->result() == QDialog::Accepted) { for (i=0;i<currentSelection.count();i++) { if (currentSelection.at(i).column() == 0) continue; fieldsItem = fieldsCollection.at(currentSelection.at(i).column()-1); if ((fieldsItem->fieldType == "M") || (fieldsItem->fieldType == "Y") || (fieldsItem->fieldType == "T") || (fieldsItem->fieldType == "B") || (fieldsItem->fieldType == "I") || (fieldsItem->fieldType == "G")) continue; query = "UPDATE "; query += tableName; query += " SET "; query += ("`"+fieldsItem->fieldName+"`"); query += "="; query += t->text().simplified(); QSqlRecord record = model->record(currentSelection.at(i).row()); query += " WHERE id_"; query += tableName; query += "="; query += record.value(0).toString(); getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } } model->setQuery(oldQuery, QSqlDatabase::database("dbfEditor")); if (model->lastError().isValid()) { QMessageBox::critical(this, tr("Error"), model->lastError().text()); return; } refresh(1); view->selectRow(0); setModified(true); } } settings.setValue("dbfeditor/fillcommand", t->text().simplified()); settings.setValue("dbfeditor/filledsize", d->size()); delete d; } void QDbfEditor::refresh(int current) { view->hideColumn(0); view->setAlternatingRowColors(true); view->resizeColumnsToContents(); view->selectColumn(0); view->selectRow(current); } void QDbfEditor::closeEvent(QCloseEvent *event) { if (modified) { QMessageBox::StandardButton reply; reply = QMessageBox::question(this, tr("Save"),tr("<center><h2>Do you want to save the changes?</h2></center>"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes ); if (reply == QMessageBox::Yes) { saveDbfFile(); } } writeSettings(); event->accept(); } void QDbfEditor::readDbtFile(int i) { /* dBASE III+ _______________________ _______ 0 | Number of next | ^ ^ 1 | available block | | | 2 | for appending data | | Header 3 | (binary) | | | |-----------------------| _|__v__ 4 | ( Reserved ) | | | | | | | | 7 | | | |-----------------------| | 8 | ( Reserved ) | | : : | 15 | | | |-----------------------| | 16 | Version no. (03h) | | |-----------------------| | 17 | (i.e. garbage) | | : : First block : : | 511| | | |=======================| _v_____ 512| | ^ | | | | | 512 Bytes | | text blocks : : | : : | | | | |-----------------------| _|_____ | Field terminator (1Ah)| | ^ |-----------------------| | |Terminating field | Field terminator (1Ah)| | |within the block *1 |-----------------------| _|__v__ : ( Unused ) : | 1023 : | |=======================| _v_____ | | ^ | | | | | 512 Bytes | | text blocks : : | : : | | | | | | _v_____ |=======================| *1 - field terminator Is reported to use only one field terminator (1Ah) - (FoxPro, Fox??) */ QByteArray memoData; QString dbtFileName = dbfFileName; int k = dbtFileName.length(); dbtFileName.truncate(k-1); dbtFileName += "t"; QFile file; file.setFileName(dbtFileName); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), tr("DBT open error")); return; } file.seek(i << 9); memoData = file.read(512); int p = memoData.indexOf('\x1A'); int q=1; while (p == -1) { file.seek((i+q) << 9); memoData.append(file.read(512)); p = memoData.indexOf('\x1A'); q++; } if (p==-1) p=0; memoData.truncate(p); //QString memoText = QString(memoData).toAscii(); //QByteArray encodedString = "..."; QTextCodec *codec = QTextCodec::codecForName("IBM850"); QString memoText = codec->toUnicode(memoData); QDbfDialog *dialog = new QDbfDialog(tr("Memo data"), this); QSettings settings; dialog->resize(settings.value("dbfeditor/memoedsize", QSize(880,560)).toSize()); QVBoxLayout *mainLayout = new QVBoxLayout; QLabel *label = new QLabel(tr("The text from the memo file"), dialog); //QPlainTextEdit *t = new QPlainTextEdit(memoText,dialog); QTextEdit *t = new QTextEdit(dialog); t->setPlainText(memoText); t->setReadOnly(true); t->setWordWrapMode(QTextOption::NoWrap); label->setBuddy(t); QFont font=t->font(); #ifdef UNIX font.setFamily("Monospace"); #else font.setFamily("Lucida Console"); #endif font.setItalic(false); t->setFont(font); QPushButton *closeButton = new QPushButton(tr("Close"), dialog); QHBoxLayout *buttonLayout = new QHBoxLayout; buttonLayout->addStretch(1); buttonLayout->addWidget(closeButton); mainLayout->addWidget(label); mainLayout->addWidget(t); //mainLayout->addStretch(1); mainLayout->addLayout(buttonLayout); connect(closeButton, SIGNAL(clicked()), dialog, SLOT(accept())); dialog->setLayout(mainLayout); dialog->exec(); settings.setValue("dbfeditor/memoedsize", dialog->size()); delete dialog; } void QDbfEditor::readFptFile(int i) { /* Xbase: FoxPro Object and Memo Field Files (*.fpt) The file format is used by Fox Pro 2.x and later The size of the header is 512 bytes _______________________ _______ 00h / 0 | Number of next | ^ 00h / 1 | available block | | 00h / 2 | for appending data | Header 00h / 3 | (binary) *1| | |-----------------------| | 00h / 4 | ( Reserved ) | | 00h / 5 | | | |-----------------------| | 00h / 6 | Size of blocks N *1| | 00h / 7 | *2| | |-----------------------| | 00h / 8 | ( Reserved ) | | | | | | | | | (i.e. garbage) | | : : | : : | 00h / 511| | | |=======================| _v_____ 00h / 0| | ^ Used block | | | __ |=======================| | | | / 0| Record type *3| : : | / 1| *1| : : | / 2| | | | | / 3| | 00h / N| | | / |-----------------------| |=======================| _|_____/ 4| Length of memo field | 00h / 0| | | 5| *1| : : | 6| | : : | 7| | | | | |-----------------------| 00h / N| | _|_____ 8| Memo data | |=======================| | \ : : 0| | | \ N| | | | | \_____ |=======================| | | | : : | 00h / N| | _v_____ |=======================| *1. Big-endian. Binary value with high byte first. *2. Size of blocks in memo file (SET BLOCKSIZE). Default is 512 bytes. *3. Record type Value Description 00h Picture. This normally indicates that file is produced on a MacIntosh, since pictures on the DOS/Windows platform are "objects". 01h Memo 02h Object */ QByteArray memoData; QString dbtFileName = dbfFileName; unsigned char a,b,c,d; quint32 tipMemo; quint32 lengthMemo; quint32 memoBlockLength; int k = dbtFileName.length(); dbtFileName.truncate(k-3); if (dbfFileName.endsWith(".dbf")) dbtFileName += "fpt"; if (dbfFileName.endsWith(".DBF")) dbtFileName += "FPT"; QFile file; file.setFileName(dbtFileName); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), tr("FPT open error")); return; } file.seek(0); memoData = file.read(8); a = memoData.at(7); b = memoData.at(6); c = memoData.at(5); d = memoData.at(4); memoBlockLength = a + (b << 8) + (c << 16) + (d << 24); file.seek(i*memoBlockLength); memoData = file.read(8); a = memoData.at(3); b = memoData.at(2); c = memoData.at(1); d = memoData.at(0); tipMemo = a + (b << 8) + (c << 16) + (d << 24); a = memoData.at(7); b = memoData.at(6); c = memoData.at(5); d = memoData.at(4); lengthMemo = a + (b << 8) + (c << 16) + (d << 24); file.seek(i*memoBlockLength+8); memoData = file.read(lengthMemo); QString memoText = QString(memoData); QDbfDialog *dialog = new QDbfDialog(tr("Memo data"), this); QSettings settings; dialog->resize(settings.value("dbfeditor/memoedsize", QSize(880,560)).toSize()); QVBoxLayout *mainLayout = new QVBoxLayout; QLabel *label = new QLabel(tr("The text from the memo file"), dialog); QPlainTextEdit *t = new QPlainTextEdit(memoText,dialog); t->setReadOnly(true); label->setBuddy(t); QFont font=t->font(); #ifdef UNIX font.setFamily("Monospace"); #else font.setFamily("Lucida Console"); #endif font.setItalic(false); t->setFont(font); QPushButton *closeButton = new QPushButton(tr("Close"), dialog); QHBoxLayout *buttonLayout = new QHBoxLayout; buttonLayout->addStretch(1); buttonLayout->addWidget(closeButton); mainLayout->addWidget(label); mainLayout->addWidget(t); //mainLayout->addStretch(1); mainLayout->addLayout(buttonLayout); connect(closeButton, SIGNAL(clicked()), dialog, SLOT(accept())); dialog->setLayout(mainLayout); dialog->exec(); settings.setValue("dbfeditor/memoedsize", dialog->size()); delete dialog; } void QDbfEditor::readDbt4File(int i) { /* dBASE IV _______________________ 0 | Number of next | ^ 1 | available block | | 2 | for appending data | Header 3 | (binary) | | |-----------------------| | 4 | ( Reserved ) | | | Size of blocks *1| | | | | 7 | | | |-----------------------| | 8 | DBF file name | | | without extention | | : : | 15 | | | |-----------------------| | 16 | Reserved (00h) | | |-----------------------| | 17 | ( Reserved ) | | 18 | | | 19 | | | |-----------------------| | 20 | Block length in bytes | | 21 | *4| | |-----------------------| | 22 | ( Reserved ) | | | | | | (i.e. garbage) | | : : | : : | 511| | | |=======================| _v_____ 1| | ^ Used block | | ^ __ |=======================| | | | / 0| ( Reserved ) | : : | / 1| | : : | / 2| FFh FFh 08h 00h | | | | / 3| | 511| | | / |-----------------------| |=======================| _|_____/ 4| Length of memo field | 1| | | 5| | : : | 6| | : : | 7| | | | | |-----------------------| 511| | _|_____ 8| Memo data *2| |=======================| | \ : : | | | \ N| | | | | \_____ |=======================| | | | | | 512 Bytes | | text blocks : : | : : | Unused block : : | __ |=======================| : : | / 0| Pointer to next free | : : | / 1| block | : : | / 2| | | | | / 3| | 511| | | / |-----------------------| |=======================| _|_____/ 4| Pointer to next used | 1| | | 5| block | : : | 6| | : : | 7| | | | | |-----------------------| 511| | _|_____ 8| ( Reserved ) | |=======================| | \ : : 1| | | \ N| | | | | \_____ |=======================| | | | : : | | | | |-----------------------| _|_____ | Field terminator (1Ah)| | ^ |-----------------------| | |Terminating field | Field terminator (1Ah)| | |within the block *3 |-----------------------| _|__v__ : ( Unused ) : | 511| : | |=======================| _v_____ | | ^ | | | | | 512 Bytes | | text blocks : : | : : | | | | | | _v_____ |=======================| *1. Size of blocks in memo file (SET BLOCKSIZE). Default is 512 bytes (FoxBase, dBASE IV ??) . *2. End of text mark is 0Dh 0Ah and line breaks are 8Dh 0Ah *3. Field terminator Is reported to use only one field terminator (1Ah) - (FoxPro, Fox??). *4. dBASE III files are marked as lenght = 1. */ QByteArray memoData; QString dbtFileName = dbfFileName; unsigned char a,b; //quint32 tipMemo; quint32 lengthMemo; //quint32 memoBlockLength; quint16 lengthInBlocks; int k = dbtFileName.length(); dbtFileName.truncate(k-3); dbtFileName += "dbt"; QFile file; file.setFileName(dbtFileName); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), tr("DBT open error")); return; } file.seek(0); memoData = file.read(512); a = memoData.at(21); b = memoData.at(20); lengthInBlocks = a + (b << 8); //file.seek(i*512*lengthInBlocks); file.seek(i*512); memoData = file.read(8); a = memoData.at(4); lengthMemo = a; //file.seek(i*512*lengthInBlocks+8); file.seek(i*512+8); memoData = file.read(lengthMemo-8); QString memoText = QString(memoData); QDbfDialog *dialog = new QDbfDialog(tr("Memo data"), this); QSettings settings; dialog->resize(settings.value("dbfeditor/memoedsize", QSize(880,560)).toSize()); QVBoxLayout *mainLayout = new QVBoxLayout; QLabel *label = new QLabel(tr("The text from the memo file"), dialog); QPlainTextEdit *t = new QPlainTextEdit(memoText,dialog); t->setReadOnly(true); label->setBuddy(t); QFont font=t->font(); #ifdef UNIX font.setFamily("Monospace"); #else font.setFamily("Lucida Console"); #endif font.setItalic(false); t->setFont(font); QPushButton *closeButton = new QPushButton(tr("Close"), dialog); QHBoxLayout *buttonLayout = new QHBoxLayout; buttonLayout->addStretch(1); buttonLayout->addWidget(closeButton); mainLayout->addWidget(label); mainLayout->addWidget(t); //mainLayout->addStretch(1); mainLayout->addLayout(buttonLayout); connect(closeButton, SIGNAL(clicked()), dialog, SLOT(accept())); dialog->setLayout(mainLayout); dialog->exec(); settings.setValue("dbfeditor/memoedsize", dialog->size()); delete dialog; } void QDbfEditor::helpDbf() { QDbfDialog *dialog = new QDbfDialog(tr("qtDbf documentation"), this); QSettings settings; dialog->resize(settings.value("dbfeditor/helpsize", QSize(860,540)).toSize()); QString dbfLocal = settings.value("dbflocal", "en").toString(); QVBoxLayout *mainLayout = new QVBoxLayout; QString dbfDirPath; #if (defined Q_OS_UNIX) || (defined Q_OS_OS2) if (QFile::exists("/usr/local/share/qtdbf")) { dbfDirPath = "/usr/local/share/qtdbf"; } else { if (QFile::exists("/usr/share/qtdbf")) { dbfDirPath = "/usr/share/qtdbf"; } else { dbfDirPath = qApp->applicationDirPath(); } } #else dbfDirPath = qApp->applicationDirPath(); #endif dbfDirPath += "/help/qtdbf_"; dbfDirPath += dbfLocal; dbfDirPath += ".html"; QFile f(dbfDirPath); QTextEdit *t = new QTextEdit(this); t->setReadOnly(true); if (f.open(QIODevice::ReadOnly)) { QByteArray data = f.readAll(); QTextCodec *codec = Qt::codecForHtml(data); QString str = codec->toUnicode(data); t->setHtml(str); } else { t->setText(tr("Help file missing").append("\n").append(f.errorString())); } QPushButton *aboutButton = new QPushButton(tr("About"), dialog); QPushButton *aboutQtButton = new QPushButton(tr("About Qt"), dialog); QPushButton *closeButton = new QPushButton(tr("Close"), dialog); QHBoxLayout *buttonLayout = new QHBoxLayout; buttonLayout->addWidget(aboutButton); buttonLayout->addWidget(aboutQtButton); buttonLayout->addStretch(1); buttonLayout->addWidget(closeButton); mainLayout->addWidget(t); mainLayout->addLayout(buttonLayout); connect(aboutButton, SIGNAL(clicked()), this, SLOT(about())); connect(aboutQtButton, SIGNAL(clicked()), qApp, SLOT(aboutQt())); connect(closeButton, SIGNAL(clicked()), dialog, SLOT(accept())); dialog->setLayout(mainLayout); dialog->exec(); settings.setValue("dbfeditor/helpsize", dialog->size()); delete dialog; } void QDbfEditor::configApp() { QDetaliiTabDialog *tabDialog = new QDetaliiTabDialog(strTableName); tabDialog->exec(); delete tabDialog; } void QDbfEditor::about() { QString explic; explic = tr("<b align='center'>qtDbf</b> <p>- an open source, multiplatform DBF viewer and editor written in Qt and using SQLite.</p>"); QMessageBox::about(this,"qtDbf 1.0", explic); } void QDbfEditor::sortDbf(const QModelIndex& index) { int current = view->currentIndex().row(); int c = index.column(); QString query; order = fieldsCollection.at(c-1)->fieldName; query = "SELECT * FROM "; query += tableName; if (where != "") query += " WHERE " + where; if (order != "") query += " ORDER BY " + order; model->setQuery(query, QSqlDatabase::database("dbfEditor")); if (model->lastError().isValid()) { QMessageBox::critical(this, tr("Error"), model->lastError().text()); return; } refresh(current); } void QDbfEditor::calculator() { QCalculatorDialog *d = new QCalculatorDialog(tr("Calculator"), this); d->exec(); delete d; } void QDbfEditor::setToolButtonIconSize(int i) { QSize size = QSize(i,i); editButton->setIconSize(size); openButton->setIconSize(size); insertButton->setIconSize(size); deleteButton->setIconSize(size); saveButton->setIconSize(size); configButton->setIconSize(size); fillButton->setIconSize(size); calcButton->setIconSize(size); helpButton->setIconSize(size); quitButton->setIconSize(size); filterButton->setIconSize(size); agregatButton->setIconSize(size); } QDbfEditor::~QDbfEditor() { } void QDbfEditor::agregat() { int c = view->currentIndex().column(); DialogAgregat *dlg = new DialogAgregat(fieldsCollection,c-1,this); if (dlg->exec() == QDialog::Accepted) { QString query = "SELECT "+dlg->getFieldPart()+" FROM "; query += tableName; if (where != "") query += " WHERE " + where; dlg->deleteLater(); QSqlQuery getData(QSqlDatabase::database("dbfEditor")); getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } if (getData.next()) { QString val = getData.value(0).toString(); QMessageBox msgBox(QMessageBox::Information, tr("Result"), val, QMessageBox::Save | QMessageBox::Close, this); msgBox.setButtonText(QMessageBox::Save, tr("Copy to Clipboard")); if (msgBox.exec()==QMessageBox::Save) { QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(val); } } } }
33.908076
139
0.475373
xiaohaijin
1c09fa25e31e9f9eb1cf698f769c434748b626f3
24,246
hpp
C++
src/pbdcex.core.hpp
jj4jj/pbdcex
5b0d2bbdaebf94cceee47350819dae93a88a4cc8
[ "MIT" ]
5
2015-12-24T19:03:41.000Z
2016-09-01T02:32:58.000Z
src/pbdcex.core.hpp
jj4jj/pbdcex
5b0d2bbdaebf94cceee47350819dae93a88a4cc8
[ "MIT" ]
null
null
null
src/pbdcex.core.hpp
jj4jj/pbdcex
5b0d2bbdaebf94cceee47350819dae93a88a4cc8
[ "MIT" ]
2
2019-08-21T19:58:00.000Z
2021-12-22T23:05:16.000Z
#ifndef __PBDCEX_CORE_EX_HPP_XX__ #define __PBDCEX_CORE_EX_HPP_XX__ #pragma once #include <cstdio> #include <cstdarg> #include <cstdint> #include <cstring> #include <cassert> #include <string> #include <algorithm> namespace pbdcex { namespace util { static inline uint64_t FNV_1A_Hash64(const unsigned char * data, size_t zdata){ uint64_t hashv = 14695981039346656037ULL; if (zdata > 0){ for (size_t i = 0; i < zdata; ++i) { // fold in another byte hashv ^= (uint64_t)data[i]; hashv *= 1099511628211ULL; } } else { for (size_t i = 0; data[i] != 0 ; ++i) { // fold in another byte hashv ^= (uint64_t)data[i]; hashv *= 1099511628211ULL; } } hashv ^= hashv >> 32; return (hashv); } static inline size_t FNV_1A_Hash32(const unsigned char * data, size_t zdata){ uint32_t hashv = 2166136261U; if (zdata > 0){ for (size_t i = 0; i < zdata; ++i) { // fold in another byte hashv ^= (uint32_t)data[i]; hashv *= 16777619U; } } else { for (size_t i = 0; data[i] != 0; ++i) { // fold in another byte hashv ^= (uint32_t)data[i]; hashv *= 16777619U; } } return (hashv); } static inline bool _is_prime(size_t n){ for (size_t i = 2; i < n / 2; ++i){ if (n % i == 0){ return false; } } return true; } static inline size_t _next_prime_bigger(size_t n){ ++n; while (true){ if (util::_is_prime(n)){ return n; } ++n; } } static inline size_t _next_prime_smaller(size_t n){ --n; while (true){ if (util::_is_prime(n)){ return n; } --n; } } template<class T> struct Hash { size_t operator ()(const T & td) const { return td.hash(); } }; template<> struct Hash<int8_t> { size_t operator ()(const int8_t & td) const { return td; } }; template<> struct Hash<uint8_t> { size_t operator ()(const uint8_t & td) const { return td; } }; template<> struct Hash<int16_t> { size_t operator ()(const int16_t & td) const { return td; } }; template<> struct Hash<uint16_t> { size_t operator ()(const uint16_t & td) const { return td; } }; template<> struct Hash<int32_t> { size_t operator ()(const int32_t & td) const { return td; } }; template<> struct Hash<uint32_t> { size_t operator ()(const uint32_t & td) const { return td; } }; template<> struct Hash<int64_t> { size_t operator ()(const int64_t & td) const { return td; } }; template<> struct Hash<uint64_t> { size_t operator ()(const uint64_t & td) const { return td; } }; template<> struct Hash<float> { size_t operator ()(const float & td) const { return (size_t)td; } }; template<> struct Hash<double> { size_t operator ()(const double & td) const { return (size_t)td; } }; } inline size_t hash_code_merge_multi_value(size_t vs[], size_t n){ //64bytes optimal todo return util::FNV_1A_Hash64((unsigned char*)&vs[0], n*sizeof(size_t)); } template<class T, class P> struct serializable_t { int dumps(::std::string & str) const { P pm; reinterpret_cast<const T*>(this)->convto(pm); if (!pm.SerializeToString(&str)) { return -1; } return 0; } int loads(const ::std::string & str){ P pm; if (!pm.ParseFromString(str)){ return -1; } int ret = reinterpret_cast<T*>(this)->check_convfrom(pm); if (ret){ return ret; } reinterpret_cast<T*>(this)->convfrom(pm); return 0; } int loads(const char * buff, int ibuff){ P pm; if (!pm.ParseFromArray(buff, ibuff)){ return -1; } int ret = reinterpret_cast<T*>(this)->check_convfrom(pm); if (ret){ return ret; } reinterpret_cast<T*>(this)->convfrom(pm); return 0; } const char * debugs(::std::string & str) const { P pm; reinterpret_cast<const T*>(this)->convto(pm); str = pm.ShortDebugString(); return str.c_str(); }; }; template<size_t lmax> struct string_t { char data[lmax]; ///////////////////////////////////////////////////////////// size_t hash() const { //fnv return util::FNV_1A_Hash64((unsigned char *)data, 0); } static string_t & assign(string_t & str, const char * cs){ str.assign(cs); return str; } void construct(){ this->data[0] = 0; } size_t format(const char * fmt, ...){ va_list ap; va_start(ap, fmt); size_t n=vsnprintf(data, lmax-1, fmt, ap); data[lmax-1]=0; va_end(ap); return n; } int assign(const char * s){ if (!s){ return 0;} size_t l = strlen(s); if (l > lmax){ l = lmax - 1; } memcpy(data, s, l); data[l]=0; return l; } int assign(const ::std::string & s){ return this->assign(s.data()); } string_t & operator = (const char * s) { this->assign(s); return *this; } string_t & operator = (const ::std::string & str) { this->assign(str); return *this; } int clone(char * s, int len) const { if (!s){ return 0; } int xlen = this->length(); if (xlen > len){ xlen = len - 1; } memcpy(s, data, xlen); data[xlen] = 0; return xlen; } operator char * (){ return data; } size_t length() const { return strlen(data); } bool operator == (const string_t & rhs) const { return compare(rhs) == 0; } bool operator < (const string_t & rhs) const { return compare(rhs) < 0; } bool operator > (const string_t & rhs) const { return compare(rhs) > 0; } int compare(const string_t & rhs) const { return strcmp(data, rhs.data); } }; template<size_t lmax, class LengthT = unsigned int> struct bytes_t { unsigned char data[lmax]; LengthT length; ////////////////////////////////////////////////////// size_t hash() const { //fnv return util::FNV_1A_Hash64(data, length); } void construct(){ this->data[0] = 0; this->length = 0; } LengthT assign(const char * s, int len){ LengthT l = len < (int)length ? len : length; memcpy(data, s, l); return l; } LengthT assign(const ::std::string & s){ return this->assign(s.data(), s.length()); } LengthT clone(char * s, int len) const { LengthT l = len < (int)length ? len : length; memcpy(s, data, l); return l; } bool operator == (const bytes_t & rhs) const { return compare(rhs) == 0; } bool operator < (const bytes_t & rhs) const { return compare(rhs) < 0; } bool operator > (const bytes_t & rhs) const { return compare(rhs) > 0; } int compare(const bytes_t & rhs) const { if (length < rhs.length){ return memcmp(data, rhs.data, length); } else { return memcmp(data, rhs.data, rhs.length); } } }; template<class T, size_t cmax, class LengthT=uint32_t> struct array_t { T list[cmax]; LengthT count; ///////////////////////////////// size_t hash() const { //five element if (this->count == 0U){ return 13131313U; } size_t hvs[5] = { 0 }; size_t hvl = this->count; size_t gap = 1; auto hf = util::Hash<T>(); if (this->count > 5U){ hvl = 5; gap = this->count / 5U; } for (LengthT i = 0; i < this->count; i += gap) { hvs[i] = hf(this->list[i]); } return util::FNV_1A_Hash64((unsigned char *)hvs, hvl*sizeof(size_t)); } void construct(){ count = 0; } size_t capacity() const { return cmax; } bool full() const { return this->count >= cmax; } bool empty() const { return this->count == 0; } void clear() { this->count = 0; } bool operator == (const array_t & rhs) const { return compare(rhs) == 0; } bool operator < (const array_t & rhs) const { return compare(rhs) < 0; } bool operator > (const array_t & rhs) const { return compare(rhs) > 0; } int compare(const array_t & rhs) const { if (count < rhs.count){ for (LengthT i = 0; i < count; ++i){ if (list[i] < rhs.list[i]){ return -1; } else if (!(list[i] == rhs.list[i])){ return 1; } } } else { for (LengthT i = 0; i < rhs.count; ++i){ if (list[i] < rhs.list[i]){ return -1; } else if (!(list[i] == rhs.list[i])){ return 1; } } } return (int)(count - rhs.count); } //linear list/////////////////////////////////////// int lfind(const T & tk) const { for (LengthT i = 0; i < count && i < cmax; ++i){ if (list[i] == tk){ return i; } } return -1; } int lappend(const T & td, bool shift_overflow = false){ if (count >= cmax && !shift_overflow){ return -1; } if (count < cmax){ list[count] = td; ++count; return 0; } else { if (cmax > 0){ memmove(list, list + 1, (cmax - 1)*sizeof(T)); list[cmax - 1] = td; } } return 0; } int lremove(int idx, bool swap_remove = false){ if (idx < 0 || (LengthT)idx >= count){ return -1; } if (swap_remove){ list[idx] = list[cmax - 1]; //list[cmax - 1].construct(); } else { memmove(list + idx, list + idx + 1, (count - idx - 1)*sizeof(T)); } --count; return 0; } int linsert(int idx, const T & td, bool overflow_shift = false){ if (count >= cmax && !overflow_shift){ return -1; } if ((LengthT)idx >= count){ idx = count; } else if (idx < 0){ idx = 0; } if ((LengthT)idx == count){ return lappend(td, overflow_shift); } //--overlay------idx------>-----idx+1------------------------------ assert(count <= cmax); if (count == cmax){ memmove(list + idx + 1, list + idx, (cmax - 1 - idx)*sizeof(T)); list[idx] = td; } else { memmove(list + idx + 1, list + idx, (count - idx)*sizeof(T)); list[idx] = td; ++count; } return 0; } void lsort(array_t & out) const { memcpy(&out, this, sizeof(*this)); ::std::sort(out.list, out.list + out.count); } ////////////////////////////////////////////////////////// /////////////////////binary-seaching////////////////////// int bfind(const T & tk) const { LengthT idx1st = lower_bound(tk); if (idx1st < count && list[idx1st] == tk){ return idx1st; } return -1; } int binsert(const T & td, bool overflow_shift = false, bool uniq = false) { LengthT idx = lower_bound(td); if (uniq && idx < count && list[idx] == td) { return -1; } return linsert(idx, td, overflow_shift); } int bremove(const T & tk){ int idx = bfind(tk); if (idx < 0){ return -1;} return lremove(idx, false); } LengthT lower_bound(const T & tk) const { const T * p = ::std::lower_bound(list, list + count, tk); return (p - list); } LengthT upper_bound(const T & tk) const { const T * p = ::std::upper_bound(list, list + count, tk); return (p - list); } T & operator [](size_t idx){ assert(idx < count); return list[idx]; } const T & operator [](size_t idx) const { assert(idx < count); return list[idx]; } }; template<class T, size_t cmax> struct mmpool_t { typedef uint64_t mmpool_bit_block_t; //typedef unsigned long long mmpool_bit_block_t; #define mmpool_bit_block_byte_sz (sizeof(mmpool_bit_block_t)) #define mmpool_bit_block_bit_sz (8*mmpool_bit_block_byte_sz) #define mmpool_bit_block_count ((cmax+mmpool_bit_block_bit_sz-1)/mmpool_bit_block_bit_sz) typedef array_t<T, mmpool_bit_block_count*mmpool_bit_block_bit_sz> allocator_t; allocator_t allocator_; mmpool_bit_block_t bmp_[mmpool_bit_block_count]; size_t used_; ///////////////////////////////////////////////////////////////////////////////////////// void construct(){ memset(this, 0, sizeof(*this)); allocator_.count = cmax; used_ = 0; } const allocator_t & allocator() { return allocator_; } size_t alloc(){ if (used() >= capacity()){ return 0; //full } //1.find first 0 set 1 size_t x,i; for (i = 0, x = 0; i < mmpool_bit_block_count; ++i){ if((x = __builtin_ffsll(~(bmp_[i])))){ break; } } if(x != 0){ bmp_[i] |= (1ULL<<(x-1));//set 1 size_t id=i*mmpool_bit_block_bit_sz+x; ++used_; new (&(allocator_.list[id - 1]))T(); return id; } else { return 0; } } size_t id(const T * p) const { assert(p >= allocator_.list && p < allocator_.list + cmax); return 1 + (p - allocator_.list); } T * ptr(size_t id) { if(id > 0 && id <= capacity() && isbusy(id)){ return &(allocator_.list[id-1]); } else { return NULL; } } bool isbusy(size_t id){ assert(id > 0); size_t idx=id-1; return bmp_[idx/mmpool_bit_block_bit_sz]&(1ULL<<(idx%mmpool_bit_block_bit_sz)); } size_t capacity() const { return cmax; } bool empty() const { return used() == 0; } size_t used() const { return used_; } size_t next(size_t it) const { if (used_ == 0){ return 0; } bool head = true; //(it+1)-1 = idx uint32_t pos_bit_ffs = 0; for (size_t idx = it / mmpool_bit_block_bit_sz, pos_bit_offset = it % mmpool_bit_block_bit_sz; idx < sizeof(bmp_) / sizeof(bmp_[0]); ++idx) { if (!head) { pos_bit_offset = 0; } else { head = false; } if (bmp_[idx] != 0ULL) { pos_bit_ffs = __builtin_ffsll(bmp_[idx] >> pos_bit_offset); if (pos_bit_ffs > 0) { return idx*mmpool_bit_block_bit_sz + pos_bit_offset + pos_bit_ffs; } } } return 0; } void free(size_t id){ assert(id > 0); size_t idx = id - 1; if(isbusy(id)){ //set 0 bmp_[idx / mmpool_bit_block_bit_sz] &= (~(1ULL << (idx%mmpool_bit_block_bit_sz))); --used_; allocator_.list[idx].~T(); } } }; //multi layer hash table implementation //---------- //------------------ //---------------------------- //collision strategy : //1.create a link list in multiple layer //2.in last max layer linear probe solving template<class T, size_t cmax, size_t layer = 3, class hcfT = util::Hash<T>> struct hashtable_t { struct hashmap_entry_t { size_t id; size_t next; size_t hco; }; struct { size_t offset; size_t count; } hash_layer_segment[layer]; #define hash_entry_index_size (layer*cmax*150/100) typedef mmpool_t<T, cmax> pool_t; typedef array_t<hashmap_entry_t, hash_entry_index_size+8> index_t; index_t index_; pool_t mmpool_; size_t stat_probe_insert; size_t stat_insert; size_t stat_probe_read; size_t stat_hit_read; //////////////////////////////////////////////////////////// void construct(){ memset(&index_, 0, sizeof(index_)); index_.count = hash_entry_index_size; mmpool_.construct(); stat_probe_insert = stat_insert = stat_hit_read = stat_probe_read = 1;//for div 0 error //bigger and bigger but max is limit hash_layer_segment[0].offset = 1; size_t hash_layer_max_size = util::_next_prime_bigger(cmax); hash_layer_segment[layer - 1].count = hash_layer_max_size; for (int i = layer - 2 ; i >= 0; --i){ hash_layer_segment[i].count = util::_next_prime_smaller(hash_layer_segment[i + 1].count); } for (size_t i = 1; i < layer; ++i){ hash_layer_segment[i].offset = hash_layer_segment[i - 1].offset + hash_layer_segment[i - 1].count; } assert(hash_entry_index_size >= hash_layer_segment[layer - 1].count + hash_layer_segment[layer - 1].offset); } const pool_t & mmpool() const {return mmpool_;} int load(int rate = 100) const { return mmpool_.used() * rate / index_.capacity(); } int factor(){ return cmax * 100 / index_.capacity(); } int hit(int rate = 100) const { return stat_hit_read * rate / stat_probe_read; } int collision() const { return stat_probe_insert / stat_insert; } const char * layers(::std::string & str) const { for (int i = 0; i < layer; ++i){ str.append("[" + ::std::to_string(this->hash_layer_segment[i].offset) + "," + ::std::to_string(this->hash_layer_segment[i].count) + ")"); } return str.c_str(); } const char * stat(::std::string & str){ str += "mbytes size:" + ::std::to_string(sizeof(*this)) + " mused:" + ::std::to_string(this->mmpool().used()) +"/"+::std::to_string(cmax) + " musage:" + ::std::to_string(this->mmpool().used() / cmax) + " iload:" + ::std::to_string(this->load()) + " ihit:" + ::std::to_string(this->hit()) + " ifactor:" + ::std::to_string(this->factor()) + " icollision:" + ::std::to_string(this->collision()) + " ilayers:" + ::std::to_string(layer); return this->layers(str); } bool empty() const { return mmpool_.empty(); } bool full() const { return mmpool_.used() >= cmax; } size_t next_slot(size_t hc, size_t ref){ assert(ref > 0); assert(index_.list[ref].next == 0); size_t find_slot = 0; if (ref < hash_layer_segment[layer - 1].offset){ for (size_t i = 0; i < layer - 1; ++i){ ++stat_probe_insert; find_slot = hash_layer_segment[i].offset + hc % hash_layer_segment[i].count; if (0 == index_.list[find_slot].id){ return find_slot; } } } //next one idle find_slot = ref; while (true){ ++stat_probe_insert; find_slot = hash_layer_segment[layer - 1].offset + (find_slot + 1) % hash_layer_segment[layer - 1].count; if (0 == index_.list[find_slot].id){ return find_slot; } } assert(false); return 0; } T * insert(const T & k){ if (full()){ return NULL; //full } //need to optimalization size_t hco = hcfT()(k); size_t idx = 1 + hco % hash_layer_segment[0].count; T * pv = NULL; while(idx && index_.list[idx].id){//find collision queue available ++stat_probe_insert; pv = mmpool_.ptr(index_.list[idx].id); if (index_.list[idx].hco == hco && *pv == k){ return NULL; } if(index_.list[idx].next == 0){ break; } idx = index_.list[idx].next; } if(idx > 0){ //valid idx if(index_.list[idx].id > 0){ //link list tail assert(index_.list[idx].next == 0); size_t npos = next_slot(hco, idx); assert(npos > 0 && index_.list[npos].id == 0); size_t hid = mmpool_.alloc(); if(hid == 0){ return NULL; } //#list append collision queue index_.list[idx].next = npos; index_.list[npos].id = hid; index_.list[npos].hco = hco; index_.list[npos].next = 0; ++stat_insert; pv = mmpool_.ptr(hid); *pv = k; return pv; } else { //head pos or in layer link list node size_t hid = mmpool_.alloc(); if(hid == 0){ return NULL; } hashmap_entry_t & he = index_.list[idx]; he.id = hid; he.hco = hco; ++stat_insert; pv = mmpool_.ptr(hid); *pv = k; return pv; } } return NULL; } int remove(const T & k){ //need to optimalization size_t hco = hcfT()(k); size_t idx = 1 + hco % hash_layer_segment[0].count; size_t pidx = 0; size_t ltidx = hash_layer_segment[layer - 1].offset + hco % hash_layer_segment[layer - 1].count; while(idx){ if(index_.list[idx].id){ T * p = mmpool_.ptr(index_.list[idx].id); if (index_.list[idx].hco == hco && *p == k){ mmpool_.free(index_.list[idx].id); if (idx < hash_layer_segment[layer - 1].offset || idx == ltidx){ //middle layer index_.list[idx].id = 0; //just erase it (no change list) index_.list[idx].hco = 0; //just erase it (no change list) return 0; } assert(pidx > 0); index_.list[idx].id = 0; index_.list[idx].hco = 0; index_.list[pidx].next = index_.list[idx].next; index_.list[idx].next = 0; return 0; } } pidx = idx; idx = index_.list[idx].next; } return -1; } T * find(const T & k){ //need to optimalization size_t hco = hcfT()(k); size_t idx = 1 + hco % hash_layer_segment[0].count; while(idx){ ++stat_probe_read; if (index_.list[idx].id){ T * pv = mmpool_.ptr(index_.list[idx].id); if (index_.list[idx].hco == hco && *pv == k){ ++stat_hit_read; return pv; } } idx = index_.list[idx].next; } return NULL; } }; }; #endif
30.23192
117
0.471542
jj4jj
1c0f8cdf4689a866f0b5c92700272cdaa0d66e4e
5,951
cpp
C++
OnlineSubsystemB3atZUtils/Source/OnlineSubsystemB3atZUtils/Private/B3atZOnlineBeacon.cpp
philippbb/OnlineSubsytemB3atZPlugin
17ad7c220fddd24bc36860ad9bbc20b3a98bb357
[ "MIT" ]
10
2017-07-22T13:04:45.000Z
2021-12-22T10:02:32.000Z
OnlineSubsystemB3atZUtils/Source/OnlineSubsystemB3atZUtils/Private/B3atZOnlineBeacon.cpp
philippbb/OnlineSubsytemB3atZPlugin
17ad7c220fddd24bc36860ad9bbc20b3a98bb357
[ "MIT" ]
null
null
null
OnlineSubsystemB3atZUtils/Source/OnlineSubsystemB3atZUtils/Private/B3atZOnlineBeacon.cpp
philippbb/OnlineSubsytemB3atZPlugin
17ad7c220fddd24bc36860ad9bbc20b3a98bb357
[ "MIT" ]
3
2017-05-06T20:31:43.000Z
2020-07-01T01:45:37.000Z
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved // Plugin written by Philipp Buerki. Copyright 2017. All Rights reserved.. #include "../OnlineSubsystemB3atZUtils/Public/B3atZOnlineBeacon.h" #include "Engine/NetConnection.h" #include "EngineGlobals.h" #include "Engine/Engine.h" DEFINE_LOG_CATEGORY(LogBeacon); AB3atZOnlineBeacon::AB3atZOnlineBeacon(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer), NetDriver(nullptr), BeaconState(EBeaconState::DenyRequests) { NetDriverName = FName(TEXT("BeaconDriver")); } bool AB3atZOnlineBeacon::InitBase() { UE_LOG(LogTemp, Warning, TEXT("B3atZOnlineBeacon InitBase")); NetDriver = GEngine->CreateNetDriver(GetWorld(), NAME_BeaconNetDriver); if (NetDriver != nullptr) { UE_LOG(LogTemp, Warning, TEXT("B3atZOnlineBeacon InitBase CreatedNetDriver is valid")); HandleNetworkFailureDelegateHandle = GEngine->OnNetworkFailure().AddUObject(this, &AB3atZOnlineBeacon::HandleNetworkFailure); SetNetDriverName(NetDriver->NetDriverName); return true; } return false; } void AB3atZOnlineBeacon::EndPlay(const EEndPlayReason::Type EndPlayReason) { if (NetDriver) { GEngine->DestroyNamedNetDriver(GetWorld(), NetDriverName); NetDriver = nullptr; } Super::EndPlay(EndPlayReason); } bool AB3atZOnlineBeacon::HasNetOwner() const { // Beacons are their own net owners return true; } void AB3atZOnlineBeacon::DestroyBeacon() { UE_LOG(LogBeacon, Verbose, TEXT("Destroying beacon %s, netdriver %s"), *GetName(), NetDriver ? *NetDriver->GetDescription() : TEXT("NULL")); GEngine->OnNetworkFailure().Remove(HandleNetworkFailureDelegateHandle); if (NetDriver) { GEngine->DestroyNamedNetDriver(GetWorld(), NetDriverName); NetDriver = nullptr; } Destroy(); } void AB3atZOnlineBeacon::HandleNetworkFailure(UWorld *World, UNetDriver *InNetDriver, ENetworkFailure::Type FailureType, const FString& ErrorString) { if (InNetDriver && InNetDriver->NetDriverName == NetDriverName) { UE_LOG(LogBeacon, Verbose, TEXT("NetworkFailure %s: %s"), *GetName(), ENetworkFailure::ToString(FailureType)); OnFailure(); } } void AB3atZOnlineBeacon::OnFailure() { GEngine->OnNetworkFailure().Remove(HandleNetworkFailureDelegateHandle); if (NetDriver) { GEngine->DestroyNamedNetDriver(GetWorld(), NetDriverName); NetDriver = nullptr; } } void AB3atZOnlineBeacon::OnActorChannelOpen(FInBunch& Bunch, UNetConnection* Connection) { Connection->OwningActor = this; Super::OnActorChannelOpen(Bunch, Connection); } bool AB3atZOnlineBeacon::IsRelevancyOwnerFor(const AActor* ReplicatedActor, const AActor* ActorOwner, const AActor* ConnectionActor) const { bool bRelevantOwner = (ConnectionActor == ReplicatedActor); return bRelevantOwner; } bool AB3atZOnlineBeacon::IsNetRelevantFor(const AActor* RealViewer, const AActor* ViewTarget, const FVector& SrcLocation) const { // Only replicate to the owner or to connections of the same beacon type (possible that multiple UNetConnections come from the same client) bool bIsOwner = GetNetConnection() == ViewTarget->GetNetConnection(); bool bSameBeaconType = GetClass() == RealViewer->GetClass(); return bOnlyRelevantToOwner ? bIsOwner : bSameBeaconType; } EAcceptConnection::Type AB3atZOnlineBeacon::NotifyAcceptingConnection() { check(NetDriver); if(NetDriver->ServerConnection) { // We are a client and we don't welcome incoming connections. UE_LOG(LogNet, Log, TEXT("NotifyAcceptingConnection: Client refused")); return EAcceptConnection::Reject; } else if(BeaconState == EBeaconState::DenyRequests) { // Server is down UE_LOG(LogNet, Log, TEXT("NotifyAcceptingConnection: Server %s refused"), *GetName()); return EAcceptConnection::Reject; } else //if(BeaconState == EBeaconState::AllowRequests) { // Server is up and running. UE_LOG(LogNet, Log, TEXT("B3atZOnlineBeacon NotifyAcceptingConnection: Server %s accept"), *GetName()); return EAcceptConnection::Accept; } } void AB3atZOnlineBeacon::NotifyAcceptedConnection(UNetConnection* Connection) { check(NetDriver != nullptr); check(NetDriver->ServerConnection == nullptr); UE_LOG(LogNet, Log, TEXT("NotifyAcceptedConnection: Name: %s, TimeStamp: %s, %s"), *GetName(), FPlatformTime::StrTimestamp(), *Connection->Describe()); } bool AB3atZOnlineBeacon::NotifyAcceptingChannel(UChannel* Channel) { check(Channel); check(Channel->Connection); check(Channel->Connection->Driver); UNetDriver* Driver = Channel->Connection->Driver; check(NetDriver == Driver); if (Driver->ServerConnection) { // We are a client and the server has just opened up a new channel. UE_LOG(LogNet, Log, TEXT("NotifyAcceptingChannel %i/%i client %s"), Channel->ChIndex, (int32)Channel->ChType, *GetName()); if (Channel->ChType == CHTYPE_Actor) { // Actor channel. UE_LOG(LogNet, Log, TEXT("Client accepting actor channel")); return 1; } else if (Channel->ChType == CHTYPE_Voice) { // Accept server requests to open a voice channel, allowing for custom voip implementations // which utilize multiple server controlled voice channels. UE_LOG(LogNet, Log, TEXT("Client accepting voice channel")); return 1; } else { // Unwanted channel type. UE_LOG(LogNet, Log, TEXT("Client refusing unwanted channel of type %i"), (uint8)Channel->ChType); return 0; } } else { // We are the server. if (Channel->ChIndex == 0 && Channel->ChType == CHTYPE_Control) { // The client has opened initial channel. UE_LOG(LogNet, Log, TEXT("NotifyAcceptingChannel Control %i server %s: Accepted"), Channel->ChIndex, *GetFullName()); return 1; } else { // Client can't open any other kinds of channels. UE_LOG(LogNet, Log, TEXT("NotifyAcceptingChannel %i %i server %s: Refused"), (uint8)Channel->ChType, Channel->ChIndex, *GetFullName()); return 0; } } } void AB3atZOnlineBeacon::NotifyControlMessage(UNetConnection* Connection, uint8 MessageType, FInBunch& Bunch) { }
31.321053
152
0.750294
philippbb
1c11aa81d8d5c87a5eba9e1c34588fa89aa6edaa
7,208
cpp
C++
src/tests/unit/cpu/shape_inference_test/interpolate_shape_inference.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
1
2019-09-22T01:05:07.000Z
2019-09-22T01:05:07.000Z
src/tests/unit/cpu/shape_inference_test/interpolate_shape_inference.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
58
2020-11-06T12:13:45.000Z
2022-03-28T13:20:11.000Z
src/tests/unit/cpu/shape_inference_test/interpolate_shape_inference.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
2
2019-09-20T01:33:37.000Z
2019-09-20T08:42:11.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include <interpolate_shape_inference.hpp> #include <openvino/op/constant.hpp> #include <openvino/op/interpolate.hpp> #include <openvino/op/parameter.hpp> #include <utils/shape_inference/shape_inference.hpp> #include <utils/shape_inference/static_shape.hpp> using namespace ov; using InterpolateMode = op::v4::Interpolate::InterpolateMode; using CoordinateTransformMode = op::v4::Interpolate::CoordinateTransformMode; using Nearest_mode = op::v4::Interpolate::NearestMode; using ShapeCalcMode = op::v4::Interpolate::ShapeCalcMode; static std::shared_ptr<op::v4::Interpolate> build_InterpolateV4() { op::v4::Interpolate::InterpolateAttrs attrs; attrs.mode = InterpolateMode::NEAREST; attrs.shape_calculation_mode = ShapeCalcMode::SCALES; attrs.coordinate_transformation_mode = CoordinateTransformMode::HALF_PIXEL; attrs.nearest_mode = Nearest_mode::ROUND_PREFER_FLOOR; attrs.antialias = false; attrs.pads_begin = {0, 0, 0, 0}; attrs.pads_end = {0, 0, 0, 0}; attrs.cube_coeff = -0.75; auto input_data = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1}); auto sizes = std::make_shared<op::v0::Parameter>(element::i32, PartialShape::dynamic()); auto scales = std::make_shared<op::v0::Parameter>(element::f32, PartialShape::dynamic()); auto axes = std::make_shared<op::v0::Parameter>(element::i32, PartialShape::dynamic()); auto interpolate = std::make_shared<op::v4::Interpolate>(input_data, sizes, scales, axes, attrs); return interpolate; } static std::shared_ptr<op::v4::Interpolate> build_InterpolateV4ConstantInput() { op::v4::Interpolate::InterpolateAttrs attrs; attrs.mode = InterpolateMode::NEAREST; attrs.shape_calculation_mode = ShapeCalcMode::SCALES; attrs.coordinate_transformation_mode = CoordinateTransformMode::HALF_PIXEL; attrs.nearest_mode = Nearest_mode::ROUND_PREFER_FLOOR; attrs.antialias = false; attrs.pads_begin = {0, 0, 0, 0}; attrs.pads_end = {0, 0, 0, 0}; attrs.cube_coeff = -0.75; auto input_data = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1}); auto sizes = std::make_shared<ov::op::v0::Constant>(element::i32, Shape{2}, std::vector<int32_t>{24, 160}); auto scales = std::make_shared<ov::op::v0::Constant>(element::f32, Shape{2}, std::vector<float>{2.0, 0.5}); auto axes = std::make_shared<ov::op::v0::Constant>(element::i32, Shape{2}, std::vector<int32_t>{2, 3}); auto interpolate = std::make_shared<op::v4::Interpolate>(input_data, sizes, scales, axes, attrs); return interpolate; } static std::shared_ptr<op::v0::Interpolate> build_InterpolateV0() { ov::op::v0::Interpolate::Attributes attrs; attrs.axes = {2, 3}; attrs.mode = "nearest"; attrs.align_corners = true; attrs.antialias = false; attrs.pads_begin = {0, 0, 0, 0}; attrs.pads_end = {0, 0, 0, 0}; auto input_data = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1}); auto sizes = std::make_shared<op::v0::Parameter>(element::i32, PartialShape::dynamic()); auto interpolate_v0 = std::make_shared<op::v0::Interpolate>(input_data, sizes, attrs); return interpolate_v0; } TEST(StaticShapeInferenceTest, InterpolateV4Test) { auto interpolate = build_InterpolateV4(); int32_t sizes_val[] = {24, 160}; float scales_val[] = {2.0, 0.5}; int32_t axes_val[] = {2, 3}; std::map<size_t, std::shared_ptr<ngraph::runtime::HostTensor>> constant_data; constant_data[1] = std::make_shared<ngraph::runtime::HostTensor>(ngraph::element::Type_t::i32, Shape{2}, sizes_val); constant_data[2] = std::make_shared<ngraph::runtime::HostTensor>(element::f32, Shape{2}, scales_val); constant_data[3] = std::make_shared<ngraph::runtime::HostTensor>(element::i32, Shape{2}, axes_val); std::vector<StaticShape> static_input_shapes = {StaticShape{1, 2, 48, 80}, StaticShape{2}, StaticShape{2}, StaticShape{2}}, static_output_shapes = {StaticShape{}}; shape_inference(interpolate.get(), static_input_shapes, static_output_shapes, constant_data); ASSERT_EQ(static_output_shapes[0], StaticShape({1, 2, 96, 40})); } TEST(StaticShapeInferenceTest, InterpolateV4ConstantInputTest) { auto interpolate = build_InterpolateV4ConstantInput(); std::vector<StaticShape> static_input_shapes = {StaticShape{1, 2, 50, 80}, StaticShape{2}, StaticShape{2}, StaticShape{2}}, static_output_shapes = {StaticShape{}}; shape_inference(interpolate.get(), static_input_shapes, static_output_shapes); ASSERT_EQ(static_output_shapes[0], StaticShape({1, 2, 100, 40})); } TEST(StaticShapeInferenceTest, InterpolateV4MissingConstantTest) { auto interpolate = build_InterpolateV4(); int32_t sizes_val[] = {24, 160}; float scales_val[] = {2.0, 0.5}; std::map<size_t, std::shared_ptr<ngraph::runtime::HostTensor>> constant_data; constant_data[1] = std::make_shared<ngraph::runtime::HostTensor>(ngraph::element::Type_t::i32, Shape{2}, sizes_val); constant_data[2] = std::make_shared<ngraph::runtime::HostTensor>(element::f32, Shape{2}, scales_val); std::vector<StaticShape> static_input_shapes = {StaticShape{1, 2, 48, 80}, StaticShape{2}, StaticShape{2}, StaticShape{2}}, static_output_shapes = {StaticShape{}}; EXPECT_THROW(shape_inference(interpolate.get(), static_input_shapes, static_output_shapes, constant_data), NodeValidationFailure); } TEST(StaticShapeInferenceTest, InterpolateV0Test) { auto interpolate = build_InterpolateV0(); int32_t sizes_val[] = {15, 30}; std::map<size_t, std::shared_ptr<ngraph::runtime::HostTensor>> constant_data; constant_data[1] = std::make_shared<ngraph::runtime::HostTensor>(ngraph::element::Type_t::i32, Shape{2}, sizes_val); std::vector<StaticShape> static_input_shapes = {StaticShape{2, 2, 33, 65}, StaticShape{2}}, static_output_shapes = {StaticShape{}}; shape_inference(interpolate.get(), static_input_shapes, static_output_shapes, constant_data); ASSERT_EQ(static_output_shapes[0], StaticShape({2, 2, 15, 30})); } TEST(StaticShapeInferenceTest, InterpolateV0MissingConstantTest) { auto interpolate = build_InterpolateV0(); std::vector<StaticShape> static_input_shapes = {StaticShape{2, 2, 33, 65}, StaticShape{2}}, static_output_shapes = {StaticShape{}}; EXPECT_THROW(shape_inference(interpolate.get(), static_input_shapes, static_output_shapes), NodeValidationFailure); }
48.375839
120
0.66232
pazamelin
1c1246b06c41ea08f0c0a3bb12e4b5c2f55d9dea
1,107
cpp
C++
Online Judges/LightOJ/1047 - Neighbor House.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
Online Judges/LightOJ/1047 - Neighbor House.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
Online Judges/LightOJ/1047 - Neighbor House.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
#include<iostream> #include<bits/stdc++.h> using namespace std; //Macros #define read(a) scanf("%d",&a) #define CLEAR(a,b) memset(a,b,sizeof(a)) #define VI(a) vector<a> #define lld long long int #define ulld unsigned long long int #define PI acos(-1.0) #define Gamma 0.5772156649015328606065120900824024310421 int arr[22][3]; int dp[22][3]; int n; int cal(int i,int j) { if(i==n) return 0; if(i>=n|| j<0 || j>2) return INT_MAX; if(dp[i][j]!=-1) return dp[i][j]; for(int k=0;k<3;k++) { dp[i][k]= arr[i][k]+min(min( cal(i+1,k+1) , cal(i+1,k-1) ), min( cal(i+1,k+2) , cal(i+1,k-2) )); } return dp[i][j]; } int main() { int test; read(test); for(int Case = 1;Case<=test;Case++) { CLEAR(dp,-1); read(n); for(int i=0;i<n;i++) { for(int j=0;j<3;j++) { scanf("%d",&arr[i][j]); } } int ret = cal(0,0); for(int i=0;i<3;i++) ret = min(ret,dp[0][i]); printf("Case %d: %d\n",Case,ret); } return 0; }
17.030769
104
0.483288
akazad13
1c135917bc74b3aae19c1068d8fe38e7acb51550
4,730
cpp
C++
dnn/src/naive/elemwise_multi_type/opr_impl_1.cpp
TaoweiZhang/MegEngine
bd3c4a05274f69dacca6097d8cbadbb34c7cc2e4
[ "Apache-2.0" ]
1
2022-03-21T03:13:45.000Z
2022-03-21T03:13:45.000Z
dnn/src/naive/elemwise_multi_type/opr_impl_1.cpp
TaoweiZhang/MegEngine
bd3c4a05274f69dacca6097d8cbadbb34c7cc2e4
[ "Apache-2.0" ]
null
null
null
dnn/src/naive/elemwise_multi_type/opr_impl_1.cpp
TaoweiZhang/MegEngine
bd3c4a05274f69dacca6097d8cbadbb34c7cc2e4
[ "Apache-2.0" ]
null
null
null
/** * \file dnn/src/naive/elemwise_multi_type/opr_impl_1.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include "./opr_impl.h" #include "megdnn/tensor_iter.h" #include "src/common/elemwise/kern_defs.cuh" #include "src/common/elemwise_multi_type/kern_defs.cuh" #include "src/naive/handle.h" using namespace megdnn; using namespace naive; void ElemwiseMultiTypeImpl::on_fuse_mul_add3_int16x32x32x32( const ElemwiseOpParamN<3>& param, const TensorND& dst) { auto size = param.size; auto src0 = param[0]; auto src1 = param[1]; auto src2 = param[2]; auto work = [src0, src1, src2, size, dst]() { auto i0 = tensor_iter_valonly<dt_int16>(src0).begin(); auto i1 = tensor_iter_valonly<dt_int32>(src1).begin(); auto i2 = tensor_iter_valonly<dt_int32>(src2).begin(); auto dst_ptr = dst.ptr<dt_int32>(); for (size_t i = 0; i < size; ++i) { dst_ptr[i] = (*i0) * (*i1) + (*i2); ++i0; ++i1; ++i2; } }; MEGDNN_DISPATCH_CPU_KERN_OPR(work()); } void ElemwiseMultiTypeImpl::on_fuse_mul_add3_int16xf32xf32xf32( const ElemwiseOpParamN<3>& param, const TensorND& dst) { auto size = param.size; auto src0 = param[0]; auto src1 = param[1]; auto src2 = param[2]; auto work = [src0, src1, src2, size, dst]() { auto i0 = tensor_iter_valonly<dt_int16>(src0).begin(); auto i1 = tensor_iter_valonly<dt_float32>(src1).begin(); auto i2 = tensor_iter_valonly<dt_float32>(src2).begin(); auto dst_ptr = dst.ptr<dt_float32>(); for (size_t i = 0; i < size; ++i) { dst_ptr[i] = (*i0) * (*i1) + (*i2); ++i0; ++i1; ++i2; } }; MEGDNN_DISPATCH_CPU_KERN_OPR(work()); } void ElemwiseMultiTypeImpl::on_fuse_mul_add3_uint8xf32xf32xf32( const ElemwiseOpParamN<3>& param, const TensorND& dst) { auto size = param.size; auto src0 = param[0]; auto src1 = param[1]; auto src2 = param[2]; auto work = [src0, src1, src2, size, dst]() { auto i0 = tensor_iter_valonly<dt_uint8>(src0).begin(); auto i1 = tensor_iter_valonly<dt_float32>(src1).begin(); auto i2 = tensor_iter_valonly<dt_float32>(src2).begin(); auto dst_ptr = dst.ptr<dt_float32>(); for (size_t i = 0; i < size; ++i) { dst_ptr[i] = (*i0) * (*i1) + (*i2); ++i0; ++i1; ++i2; } }; MEGDNN_DISPATCH_CPU_KERN_OPR(work()); } void ElemwiseMultiTypeImpl::on_mul_int16xf32xf32( const ElemwiseOpParamN<2>& param, const TensorND& dst) { auto size = param.size; auto src0 = param[0]; auto src1 = param[1]; auto work = [src0, src1, size, dst]() { auto i0 = tensor_iter_valonly<dt_int16>(src0).begin(); auto i1 = tensor_iter_valonly<dt_float32>(src1).begin(); auto dst_ptr = dst.ptr<dt_float32>(); for (size_t i = 0; i < size; ++i) { dst_ptr[i] = (*i0) * (*i1); ++i0; ++i1; } }; MEGDNN_DISPATCH_CPU_KERN_OPR(work()); } void ElemwiseMultiTypeImpl::on_fuse_mul_add3_iXxf32xf32xi8( const ElemwiseOpParamN<3>& param, const TensorND& dst) { switch (param[0].layout.dtype.enumv()) { #define cb(t) \ case DTypeTrait<t>::enumv: \ return dispatch_fma3_iXxf32xf32xi8<DTypeTrait<t>::ctype>(param, dst); MEGDNN_FOREACH_COMPUTING_DTYPE_INT(cb) #undef cb default: megdnn_throw("unsupported src dtype"); } } template <typename ctype> void ElemwiseMultiTypeImpl::dispatch_fma3_iXxf32xf32xi8( const ElemwiseOpParamN<3>& param, const TensorND& dst) { auto size = param.size; auto src0 = param[0]; auto src1 = param[1]; auto src2 = param[2]; auto work = [src0, src1, src2, size, dst]() { elemwise_multi_type::Fma3iXxf32xf32xiYOp<ctype, dt_int8> op; auto i0 = tensor_iter_valonly<ctype>(src0).begin(); auto i1 = tensor_iter_valonly<dt_float32>(src1).begin(); auto i2 = tensor_iter_valonly<dt_float32>(src2).begin(); auto dst_ptr = dst.ptr<dt_int8>(); for (size_t i = 0; i < size; ++i) { dst_ptr[i] = op(*i0, *i1, *i2); ++i0; ++i1; ++i2; } }; MEGDNN_DISPATCH_CPU_KERN_OPR(work()); } // vim: syntax=cpp.doxygen
34.028777
89
0.604017
TaoweiZhang
1c16dc3bb20e37ed22e6079c11a2e75d1e557c8f
1,361
cpp
C++
client/LocalConn.cpp
lzs123/CProxy
08266997317b0ba89ddc93dac46b0faf5fd12592
[ "MIT" ]
7
2022-02-07T08:26:55.000Z
2022-03-23T02:55:44.000Z
client/LocalConn.cpp
lzs123/CProxy
08266997317b0ba89ddc93dac46b0faf5fd12592
[ "MIT" ]
null
null
null
client/LocalConn.cpp
lzs123/CProxy
08266997317b0ba89ddc93dac46b0faf5fd12592
[ "MIT" ]
null
null
null
#include <fcntl.h> #include <string.h> #include "LocalConn.h" #include "Tunnel.h" #include "lib/Util.h" void LocalConn::handleRead() { try{ int bs = splice(fd_, NULL, pipe_fds_[1], NULL, 2048, SPLICE_F_MOVE | SPLICE_F_NONBLOCK); if (bs < 0) { SPDLOG_CRITICAL("proxy_id: {} local_fd: {} -> pipe_fd: {} splice err: {} ", proxy_id_, fd_, pipe_fds_[1], strerror(errno)); return; } // 当proxyConn调用shutdownFromRemote后,shutdown(local_fd, 1)后会往local_fd中添加EPOLLIN事件,所以可能会重复满足bs=0,需要添加closing_判断。避免多次进入循环 // https://mp.weixin.qq.com/s?__biz=MzUxNDUwOTc0Nw==&mid=2247484253&idx=1&sn=e42ed5e1af8382eb6dffa7550470cdf3 if (bs == 0 && !closing_) { tun_->shutdownFromLocal(proxy_id_, getTranCount()); closing_ = true; return; } bs = splice(pipe_fds_[0], NULL, peer_conn_fd_, NULL, bs, SPLICE_F_MOVE | SPLICE_F_NONBLOCK); if (bs < 0) { SPDLOG_CRITICAL("proxy_id {} local_fd: {} pipe_fd: {} -> proxy_conn_fd: {} splice err: {}", proxy_id_, fd_, pipe_fds_[0], peer_conn_fd_, strerror(errno)); return; } incrTranCount(bs); } catch (const std::exception& e) { SPDLOG_CRITICAL("read local_conn except: {}", e.what()); } } void LocalConn::postHandle() { if (closing_) { return; } channel_->setEvents(EPOLLET | EPOLLIN | EPOLLRDHUP); loop_->updatePoller(channel_); }
35.815789
162
0.659809
lzs123
1c1daf85142e4d3caa7fc315f2ddee90e9f4dda5
490
cpp
C++
dawn/test/unit-test/dawn/Optimizer/samples/KCacheTest02b.cpp
BenWeber42/dawn
727835e027b8270d667452b857fa4e0af57b2c2e
[ "MIT" ]
20
2017-09-28T14:23:54.000Z
2021-08-23T09:58:26.000Z
dawn/test/unit-test/dawn/Optimizer/samples/KCacheTest02b.cpp
BenWeber42/dawn
727835e027b8270d667452b857fa4e0af57b2c2e
[ "MIT" ]
1,018
2017-10-09T13:55:47.000Z
2022-03-14T13:16:38.000Z
dawn/test/unit-test/dawn/Optimizer/samples/KCacheTest02b.cpp
eddie-c-davis/dawn
4dabcfc72e422f125e6a18fe08d0212d588adf98
[ "MIT" ]
20
2017-09-21T10:35:24.000Z
2021-01-18T09:24:58.000Z
#include "gtclang_dsl_defs/gtclang_dsl.hpp" using namespace gtclang::dsl; stencil Test { storage a, b, c; var tmp; Do { // MS0 vertical_region(k_start, k_start) { tmp = a; } vertical_region(k_start + 1, k_end) { b = tmp(k - 1); } // MS1 vertical_region(k_end, k_end) { tmp = (b(k - 1) + b) * tmp; } vertical_region(k_end - 1, k_start) { tmp = 2 * b; c = tmp(k + 1); } } };
19.6
43
0.483673
BenWeber42
1c2019fcd1b8894f0a0a76c6cff42181449ee6bc
129,465
cpp
C++
bwchart/bwchart/DlgStats.cpp
udonyang/scr-benchmark
ed81d74a9348b6813750007d45f236aaf5cf4ea4
[ "MIT" ]
null
null
null
bwchart/bwchart/DlgStats.cpp
udonyang/scr-benchmark
ed81d74a9348b6813750007d45f236aaf5cf4ea4
[ "MIT" ]
null
null
null
bwchart/bwchart/DlgStats.cpp
udonyang/scr-benchmark
ed81d74a9348b6813750007d45f236aaf5cf4ea4
[ "MIT" ]
null
null
null
// DlgStats.cpp : implementation file // #include "stdafx.h" #include "bwchart.h" #include "DlgStats.h" #include "regparam.h" #include "bwrepapi.h" #include "DlgHelp.h" #include "DlgMap.h" #include "Dlgbwchart.h" #include "gradient.h" #include "hsvrgb.h" #include "overlaywnd.h" #include "ExportCoachDlg.h" #include "bezier.h" #include <math.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define MAXPLAYERONVIEW 6 #define HSCROLL_DIVIDER 2 #define TIMERSPEED 8 //----------------------------------------------------------------------------------------------------------------- // constants for chart painting int hleft=30; const int haxisleft = 2; const int vplayer=30; const int hplayer=52; const int hright=8; const int vtop=24; const int vbottom=12; const int evtWidth=4; const int evtHeight=8; const int layerHeight=14; const COLORREF clrCursor = RGB(200,50,50); const COLORREF clrMineral = RGB(50,50,150); const COLORREF clrGrid = RGB(64,64,64); const COLORREF clrLayer1 = RGB(32,32,32); const COLORREF clrLayer2 = RGB(16,16,16); const COLORREF clrLayerTxt1 = RGB(0,0,0); const COLORREF clrLayerTxt2 = RGB(64,64,64); const COLORREF clrAction = RGB(255,206,70); const COLORREF clrBOLine[3] = {RGB(30,30,120),RGB(80,30,30),RGB(30,80,30)}; const COLORREF clrBOName[3] = {RGB(100,150,190), RGB(200,50,90), RGB(50,200,90) }; #define clrPlayer OPTIONSCHART->GetColor(DlgOptionsChart::CLR_PLAYERS) #define clrUnitName OPTIONSCHART->GetColor(DlgOptionsChart::CLR_OTHER) #define clrRatio OPTIONSCHART->GetColor(DlgOptionsChart::CLR_OTHER) #define clrTime OPTIONSCHART->GetColor(DlgOptionsChart::CLR_OTHER) static bool firstPoint=true; static int lastMaxX=0; static int lastHotPointX=0; static const char *lastHotPoint=0; static CString strDrop; static CString strExpand; static CString strLeave; static CString strMinGas; static CString strSupplyUnit; static CString strMinimapPing; // dividers for splines static int gSplineCount[DlgStats::__MAXCHART]= { //APM 200, //RESOURCES, 200, //UNITS 200, //ACTIONS 0, //BUILDINGS 0, //UPGRADES 0, //APMDIST 0, //BUILDORDER 0, //HOTKEYS 0, //MAPCOVERAGE 100, //MIX_APMHOTKEYS 0 }; //----------------------------------------------------------------------------------------------------------------- BEGIN_MESSAGE_MAP(DlgStats, CDialog) //{{AFX_MSG_MAP(DlgStats) ON_WM_PAINT() ON_BN_CLICKED(IDC_GETEVENTS, OnGetevents) ON_WM_SIZE() ON_NOTIFY(LVN_ITEMCHANGED, IDC_LISTEVENTS, OnItemchangedListevents) ON_WM_LBUTTONDOWN() ON_CBN_SELCHANGE(IDC_ZOOM, OnSelchangeZoom) ON_WM_HSCROLL() ON_NOTIFY(NM_DBLCLK, IDC_PLSTATS, OnDblclkPlstats) ON_BN_CLICKED(IDC_GAZ, OnUpdateChart) ON_WM_DESTROY() ON_CBN_SELCHANGE(IDC_CHARTTYPE, OnSelchangeCharttype) ON_BN_CLICKED(IDC_DHELP, OnHelp) ON_BN_CLICKED(IDC_TESTREPLAYS, OnTestreplays) ON_BN_CLICKED(IDC_ADDEVENT, OnAddevent) ON_NOTIFY(NM_RCLICK, IDC_PLSTATS, OnRclickPlstats) ON_BN_CLICKED(IDC_SEEMAP, OnSeemap) ON_BN_CLICKED(IDC_ANIMATE, OnAnimate) ON_WM_TIMER() ON_BN_CLICKED(IDC_PAUSE, OnPause) ON_BN_CLICKED(IDC_SPEEDMINUS, OnSpeedminus) ON_BN_CLICKED(IDC_SPEEDPLUS, OnSpeedplus) ON_NOTIFY(LVN_GETDISPINFO, IDC_LISTEVENTS, OnGetdispinfoListevents) ON_WM_LBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_SETCURSOR() ON_WM_RBUTTONDOWN() ON_NOTIFY(NM_RCLICK, IDC_LISTEVENTS, OnRclickListevents) ON_BN_CLICKED(IDC_FLT_SELECT, OnFilterChange) ON_BN_CLICKED(IDC_NEXT_SUSPECT, OnNextSuspect) ON_BN_CLICKED(IDC_MINERALS, OnUpdateChart) ON_BN_CLICKED(IDC_SUPPLY, OnUpdateChart) ON_BN_CLICKED(IDC_ACTIONS, OnUpdateChart) ON_BN_CLICKED(IDC_UNITS, OnUpdateChart) ON_BN_CLICKED(IDC_USESECONDS, OnUpdateChart) ON_BN_CLICKED(IDC_SPEED, OnUpdateChart) ON_BN_CLICKED(IDC_SINGLECHART, OnUpdateChart) ON_BN_CLICKED(IDC_UNITSONBO, OnUpdateChart) ON_BN_CLICKED(IDC_HOTPOINTS, OnUpdateChart) ON_BN_CLICKED(IDC_UPM, OnUpdateChart) ON_BN_CLICKED(IDC_BPM, OnUpdateChart) ON_BN_CLICKED(IDC_PERCENTAGE, OnUpdateChart) ON_BN_CLICKED(IDC_HKSELECT, OnUpdateChart) ON_BN_CLICKED(IDC_FLT_BUILD, OnFilterChange) ON_BN_CLICKED(IDC_FLT_TRAIN, OnFilterChange) ON_BN_CLICKED(IDC_FLT_SUSPECT, OnFilterChange) ON_BN_CLICKED(IDC_FLT_HACK, OnFilterChange) ON_BN_CLICKED(IDC_FLT_OTHERS, OnFilterChange) ON_BN_CLICKED(IDC_FLT_CHAT, OnFilterChange) ON_BN_CLICKED(IDC_SORTDIST, OnUpdateChart) ON_CBN_SELCHANGE(IDC_APMSTYLE, OnSelchangeApmstyle) //}}AFX_MSG_MAP ON_COMMAND(ID__REMOVEPLAYER,OnRemovePlayer) ON_COMMAND(ID__ENABLEDISABLE,OnEnableDisable) ON_COMMAND(ID__WATCHREPLAY_BW116,OnWatchReplay116) ON_COMMAND(ID__WATCHREPLAY_BW115,OnWatchReplay115) ON_COMMAND(ID__WATCHREPLAY_BW114,OnWatchReplay114) ON_COMMAND(ID__WATCHREPLAY_BW113,OnWatchReplay113) ON_COMMAND(ID__WATCHREPLAY_BW112,OnWatchReplay112) ON_COMMAND(ID__WATCHREPLAY_BW111,OnWatchReplay111) ON_COMMAND(ID__WATCHREPLAY_BW110,OnWatchReplay110) ON_COMMAND(ID__WATCHREPLAY_BW109,OnWatchReplay109) ON_COMMAND(ID__WATCHREPLAYINBW_SC,OnWatchReplaySC) ON_COMMAND(ID__WATCHREPLAYINBW_AUTO,OnWatchReplay) ON_COMMAND(ID_FF_EXPORT_TOTEXTFILE,OnExportToText) ON_COMMAND(ID__EXPORTTO_BWCOACH,OnExportToBWCoach) // ON_COMMAND(ID_FF_EXPORTTO_HTMLFILE,OnExportToHtml) END_MESSAGE_MAP() //----------------------------------------------------------------------------------------------------------------- void DlgStats::_Parameters(bool bLoad) { int defval[__MAXCHART]; int defvalUnits[__MAXCHART]; int defvalApm[__MAXCHART]; memset(defval,0,sizeof(defval)); memset(defvalUnits,0,sizeof(defvalUnits)); memset(defvalApm,0,sizeof(defval)); defvalUnits[MAPCOVERAGE]=1; defvalApm[MAPCOVERAGE]=2; defvalApm[APM]=2; PINT("main",seeMinerals,TRUE); PINT("main",seeGaz,TRUE); PINT("main",seeSupply,FALSE); PINT("main",seeActions,FALSE); PINTARRAY("main",singleChart,__MAXCHART,defval); PINTARRAY("main",seeUnits,__MAXCHART,defvalUnits); PINTARRAY("main",apmStyle,__MAXCHART,defvalApm); PINT("main",useSeconds,FALSE); PINT("main",seeSpeed,FALSE); PINT("main",seeUPM,FALSE); PINT("main",seeBPM,FALSE); PINT("main",chartType,0); PINT("main",seeUnitsOnBO,TRUE); PINT("main",seeHotPoints,TRUE); PINT("main",seePercent,TRUE); PINT("main",animationSpeed,2); PINT("main",hlist,120); PINT("main",wlist,0); PINT("main",viewHKselect,FALSE); PINT("filter",fltSelect,TRUE); PINT("filter",fltTrain,TRUE); PINT("filter",fltBuild,TRUE); PINT("filter",fltSuspect,TRUE); PINT("filter",fltHack,TRUE); PINT("filter",fltOthers,TRUE); PINT("filter",fltChat,TRUE); PINT("main",sortDist,FALSE); } //----------------------------------------------------------------------------------------------------------------- /* static void _GetRemoteItemText(HANDLE hProcess, HWND hlv, LV_ITEM* plvi, int item, int subitem, char *itemText) { // Initialize a local LV_ITEM structure LV_ITEM lvi; lvi.mask = LVIF_TEXT; lvi.iItem = item; lvi.iSubItem = subitem; // NOTE: The text data immediately follows the LV_ITEM structure // in the memory block allocated in the remote process. lvi.pszText = (LPTSTR) (plvi + 1); lvi.cchTextMax = 100; // Write the local LV_ITEM structure to the remote memory block if(!WriteProcessMemory(hProcess, plvi, &lvi, sizeof(lvi), NULL)) { ::MessageBox(0,__TEXT("Cant write into SuperView's memory"), "bwchart", MB_OK | MB_ICONWARNING); return; } // Tell the ListView control to fill the remote LV_ITEM structure ListView_GetItem(hlv, plvi); // Read the remote text string into our buffer if(!ReadProcessMemory(hProcess, plvi + 1, itemText, 256, NULL)) { ::MessageBox(0,__TEXT("Cant read into SuperView's memory"), "bwchart", MB_OK | MB_ICONWARNING); return; } } //----------------------------------------------------------------------------------------------------------------- typedef LPVOID (__stdcall * PFNVIRTALLEX)(HANDLE, LPVOID, SIZE_T, DWORD,DWORD); static HANDLE ghFileMapping=0; static PVOID _AllocSharedMemory(HANDLE hProcess, int size) { OSVERSIONINFO osvi = { sizeof(osvi) }; GetVersionEx( &osvi ); if ( osvi.dwPlatformId == VER_PLATFORM_WIN32_NT ) { // We're on NT, so use VirtualAllocEx to allocate memory in the other // process address space. Alas, we can't just call VirtualAllocEx // since it's not defined in the Windows 95 KERNEL32.DLL. return VirtualAllocEx(hProcess, NULL, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); } else if ( osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ) { // In Windows 9X, create a small memory mapped file. On this // platform, memory mapped files are above 2GB, and thus are // accessible by all processes. ghFileMapping = CreateFileMapping( INVALID_HANDLE_VALUE, 0, PAGE_READWRITE | SEC_COMMIT, 0, size, 0 ); if ( ghFileMapping ) { LPVOID pStubMemory = MapViewOfFile( ghFileMapping, FILE_MAP_WRITE, 0, 0, size ); return pStubMemory; } else { CloseHandle( ghFileMapping ); ghFileMapping=0; } } return 0; } //----------------------------------------------------------------------------------------------------------------- static void _FreeSharedMemory(HANDLE hProcess, PVOID padr) { OSVERSIONINFO osvi = { sizeof(osvi) }; GetVersionEx( &osvi ); if ( osvi.dwPlatformId == VER_PLATFORM_WIN32_NT ) { // We're on NT, so use VirtualFreeEx VirtualFreeEx(hProcess, padr, 0, MEM_RELEASE); } else if ( osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ) { // In Windows 9X, create a small memory mapped file. On this // platform, memory mapped files are above 2GB, and thus are // accessible by all processes. UnmapViewOfFile(padr); CloseHandle( ghFileMapping ); } } //----------------------------------------------------------------------------------------------------------------- #define CMPUNIT(val,rval) if(_stricmp(itemParam,val)==0) {strcpy(itemParam,rval); return;} #define CMPBUILD(val,rval) if(_stricmp(lastp,val)==0) {strcpy(lastp,rval); return;} // adjust values static void _AdjustAction(char *itemType, char *itemParam) { if(_stricmp(itemType,"Train")==0) { CMPUNIT("46","Scout"); CMPUNIT("47","Arbiter"); CMPUNIT("3C","Corsair"); CMPUNIT("45","Shuttle"); CMPUNIT("53","Reaver"); CMPUNIT("01","Ghost"); CMPUNIT("0C","Battlecruiser"); CMPUNIT("Vulture","Goliath"); CMPUNIT("Goliath","Vulture"); CMPUNIT("0E","Nuke"); return; } else if(_stricmp(itemType,"2A")==0) {strcpy(itemType,"Train"); strcpy(itemParam,"Archon"); return;} else if(_stricmp(itemType,"5A")==0) {strcpy(itemType,"Train"); strcpy(itemParam,"Dark Archon"); return;} else if(_stricmp(itemType,"Build")==0) { // extract building name char *lastp=strrchr(itemParam,','); if(lastp!=0) lastp++; else lastp=itemParam; while(*lastp==' ') lastp++; CMPBUILD("AA","Arbiter Tribunal"); CMPBUILD("AB","Robotics Support Bay"); CMPBUILD("AC","Shield Battery"); CMPBUILD("75","Covert Ops"); CMPBUILD("76","Physics Lab"); CMPBUILD("6C","Nuclear Silo"); CMPBUILD("Acadamy","Academy"); return; } else if(_stricmp(itemType,"Research")==0 || _stricmp(itemType,"Upgrade")==0) { CMPUNIT("27","Gravitic Booster"); CMPUNIT("22","Zealot Speed"); CMPUNIT("15","Recall"); CMPUNIT("0E","Protoss Air Attack"); CMPUNIT("23","Scarab Damage"); CMPUNIT("26","Sensor Array"); CMPUNIT("16","Statis Field"); CMPUNIT("14","Hallucination"); CMPUNIT("0F","Plasma Shield"); CMPUNIT("24","Reaver Capacity"); CMPUNIT("2C","Khaydarin Core"); CMPUNIT("28","Khaydarin Amulet"); CMPUNIT("29","Apial Sensors"); CMPUNIT("25","Gravitic Drive"); CMPUNIT("1B","Mind Control"); CMPUNIT("2A","Gravitic Thrusters"); CMPUNIT("1F","Maelstrom"); CMPUNIT("31","Argus Talisman"); CMPUNIT("19","Disruption Web"); CMPUNIT("2F","Argus Jewel"); CMPUNIT("01","Lockdown"); CMPUNIT("02","EMP Shockwave"); CMPUNIT("09","Cloaking Field"); CMPUNIT("11","Vulture Speed"); CMPUNIT("0A","Personal Cloaking"); CMPUNIT("08","Yamato Gun"); CMPUNIT("17","Colossus Reactor"); CMPUNIT("18","Restoration"); CMPUNIT("1E","Optical Flare"); CMPUNIT("33","Medic Energy"); return; } } //----------------------------------------------------------------------------------------------------------------- bool DlgStats::_GetListViewContent(HWND hlv) { // Get the count of items in the ListView control int nCount = ListView_GetItemCount(hlv); // Open a handle to the remote process's kernel object DWORD dwProcessId; GetWindowThreadProcessId(hlv, &dwProcessId); HANDLE hProcess = OpenProcess( PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, dwProcessId); if (hProcess == NULL) { MessageBox(__TEXT("Could not communicate with SuperView"), "bwchart", MB_OK | MB_ICONWARNING); return false; } // Allocate memory in the remote process's address space LV_ITEM* plvi = (LV_ITEM*) //VirtualAllocEx(hProcess, NULL, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); _AllocSharedMemory(hProcess, 4096); if (plvi == NULL) { DWORD dw=GetLastError(); CString msg; msg.Format("Could not allocate virtual memory %lu",dw); MessageBox("Sorry, but BWchart cannot work under Windows 95/98", "bwchart", MB_OK | MB_ICONWARNING); return false; } // Get each ListView item's text data for (int nIndex = 0; nIndex < nCount; nIndex++) { // read elapsed time char itemTime[256]; _GetRemoteItemText(hProcess, hlv, plvi, nIndex, 0, itemTime); int nPos = m_listEvents.InsertItem(nIndex,itemTime, 0); m_listEvents.SetItemData(nPos,(DWORD)_atoi64(itemTime)); // read player name char itemPlayer[256]; _GetRemoteItemText(hProcess, hlv, plvi, nIndex, 1, itemPlayer); m_listEvents.SetItemText(nPos,1,itemPlayer); // read event type char itemType[256]; _GetRemoteItemText(hProcess, hlv, plvi, nIndex, 2, itemType); // read event parameters char itemParam[256]; _GetRemoteItemText(hProcess, hlv, plvi, nIndex, 3, itemParam); // adjust values _AdjustAction(itemType,itemParam); // update list view m_listEvents.SetItemText(nPos,2,itemType); m_listEvents.SetItemText(nPos,3,itemParam); // record event //m_replay.AddEvent(atoi(itemTime),itemPlayer,itemType,itemParam); } // Free the memory in the remote process's address space _FreeSharedMemory(hProcess, plvi); //VirtualFreeEx(hProcess, plvi, 0, MEM_RELEASE); // Cleanup and put our results on the clipboard CloseHandle(hProcess); return true; } //----------------------------------------------------------------------------------------------------------------- BOOL CALLBACK EnumChildProc( HWND hwnd, // handle to child window LPARAM lParam // application-defined value ) { char classname[128]; GetClassName(hwnd,classname,sizeof(classname)); if(_stricmp(classname,"SysListView32")==0) { HWND hlv = ::GetNextWindow(hwnd, GW_HWNDNEXT); if(hlv==0) return FALSE; hlv = ::GetNextWindow(hlv, GW_HWNDNEXT); if(hlv==0) return FALSE; *((HWND*)lParam) = hlv; return FALSE; } return TRUE; } */ //----------------------------------------------------------------------------------------------------------------- bool DlgStats::_GetReplayFileName(CString& path) { static char BASED_CODE szFilter[] = "Replay (*.rep)|*.rep|All Files (*.*)|*.*||"; // find initial path CString initialPath; initialPath = AfxGetApp()->GetProfileString("MAIN","LASTADDREPLAY"); if(initialPath.IsEmpty()) DlgOptions::_GetStarcraftPath(initialPath); // stop animation if any StopAnimation(); // open dialog CFileDialog dlg(TRUE,"rep","",0,szFilter,this); dlg.m_ofn.lpstrInitialDir = initialPath; if(dlg.DoModal()==IDOK) { CWaitCursor wait; path = dlg.GetPathName(); AfxGetApp()->WriteProfileString("MAIN","LASTADDREPLAY",path); return true; } return false; } ///////////////////////////////////////////////////////////////////////////// // DlgStats dialog DlgStats::DlgStats(CWnd* pParent /*=NULL*/) : CDialog(DlgStats::IDD, pParent) { //{{AFX_DATA_INIT(DlgStats) m_zoom = 0; m_seeMinerals = TRUE; m_seeGaz = TRUE; m_seeSupply = FALSE; m_seeActions = FALSE; m_useSeconds = FALSE; m_seeSpeed = FALSE; m_chartType = -1; m_seeUnitsOnBO = FALSE; m_exactTime = _T(""); m_seeBPM = FALSE; m_seeUPM = FALSE; m_seeHotPoints = FALSE; m_seePercent = FALSE; m_viewHKselect = FALSE; m_fltSelect = FALSE; m_fltSuspect = FALSE; m_fltHack = FALSE; m_fltTrain = FALSE; m_fltBuild = FALSE; m_fltOthers = FALSE; m_fltChat = FALSE; m_suspectInfo = _T(""); m_sortDist = FALSE; //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_timeBegin = 0; m_timeEnd = 0; m_lockListView=false; m_selectedPlayer=0; m_selectedAction=-1; m_maxPlayerOnBoard=0; m_selectedPlayerList=0; m_bIsAnimating=false; m_animationSpeed=2; m_prevAnimationSpeed=0; m_timer=0; m_mixedCount=0; m_MixedPlayerIdx=0; // map title m_rectMapName.SetRectEmpty(); // resize m_resizing=NONE; m_hlist=120; m_wlist=0; // load parameters _Parameters(true); if(m_hlist<60) m_hlist=60; // scroller increments m_lineDev.cx = 5; m_lineDev.cy = 0; m_pageDev.cx = 50; m_pageDev.cy = 0; // create all fonts _CreateFonts(); // create map m_dlgmap = new DlgMap(0,m_pLabelBoldFont,m_pLayerFont,this); // create overlay m_over = new OverlayWnd(this); // init time m_exactTime = _MkTime(0,0,true); } DlgStats::~DlgStats() { // delete overlay m_over->DestroyWindow(); delete m_over; //delete map delete m_dlgmap; // delete fonts _DestroyFonts(); } void DlgStats::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(DlgStats) DDX_Check(pDX, IDC_SINGLECHART, m_singleChart[m_chartType]); DDX_Check(pDX, IDC_UNITS, m_seeUnits[m_chartType]); DDX_CBIndex(pDX, IDC_APMSTYLE, m_apmStyle[m_chartType]); DDX_CBIndex(pDX, IDC_CHARTTYPE, m_chartType); DDX_Control(pDX, IDC_PROGRESS1, m_progress); DDX_Control(pDX, IDC_GAMEDURATION, m_gamed); DDX_Control(pDX, IDC_DBLCLICK, m_dlbclick); DDX_Control(pDX, IDC_PLSTATS, m_plStats); DDX_Control(pDX, IDC_SCROLLBAR2, m_scrollerV); DDX_Control(pDX, IDC_SCROLLBAR1, m_scroller); DDX_Control(pDX, IDC_LISTEVENTS, m_listEvents); DDX_CBIndex(pDX, IDC_ZOOM, m_zoom); DDX_Check(pDX, IDC_MINERALS, m_seeMinerals); DDX_Check(pDX, IDC_GAZ, m_seeGaz); DDX_Check(pDX, IDC_SUPPLY, m_seeSupply); DDX_Check(pDX, IDC_ACTIONS, m_seeActions); DDX_Check(pDX, IDC_USESECONDS, m_useSeconds); DDX_Check(pDX, IDC_SPEED, m_seeSpeed); DDX_Check(pDX, IDC_UNITSONBO, m_seeUnitsOnBO); DDX_Text(pDX, IDC_EXACTTIME, m_exactTime); DDX_Check(pDX, IDC_BPM, m_seeBPM); DDX_Check(pDX, IDC_UPM, m_seeUPM); DDX_Check(pDX, IDC_HOTPOINTS, m_seeHotPoints); DDX_Check(pDX, IDC_PERCENTAGE, m_seePercent); DDX_Check(pDX, IDC_HKSELECT, m_viewHKselect); DDX_Check(pDX, IDC_FLT_SELECT, m_fltSelect); DDX_Check(pDX, IDC_FLT_CHAT, m_fltChat); DDX_Check(pDX, IDC_FLT_SUSPECT, m_fltSuspect); DDX_Check(pDX, IDC_FLT_HACK, m_fltHack); DDX_Check(pDX, IDC_FLT_TRAIN, m_fltTrain); DDX_Check(pDX, IDC_FLT_BUILD, m_fltBuild); DDX_Check(pDX, IDC_FLT_OTHERS, m_fltOthers); DDX_Text(pDX, IDC_SUSPECT_INFO, m_suspectInfo); DDX_Check(pDX, IDC_SORTDIST, m_sortDist); //}}AFX_DATA_MAP } //------------------------------------------------------------------------------------------------------------ void DlgStats::_CreateFonts() { // get system language LANGID lng = GetSystemDefaultLangID(); //if(lng==0x412) // korea //if(lng==0x0804) //chinese // retrieve a standard VARIABLE FONT from system HFONT hFont = (HFONT)GetStockObject( ANSI_VAR_FONT); CFont *pRefFont = CFont::FromHandle(hFont); LOGFONT LFont; // get font description memset(&LFont,0,sizeof(LOGFONT)); pRefFont->GetLogFont(&LFont); // create our label Font LFont.lfHeight = 18; LFont.lfWidth = 0; LFont.lfQuality|=ANTIALIASED_QUALITY; strcpy(LFont.lfFaceName,"Arial"); m_pLabelFont = new CFont(); m_pLabelFont->CreateFontIndirect(&LFont); // create our bold label Font LFont.lfWeight=700; m_pLabelBoldFont = new CFont(); m_pLabelBoldFont->CreateFontIndirect(&LFont); // create our layer Font pRefFont->GetLogFont(&LFont); LFont.lfHeight = 14; LFont.lfWidth = 0; LFont.lfQuality|=ANTIALIASED_QUALITY; strcpy(LFont.lfFaceName,"Arial"); m_pLayerFont = new CFont(); m_pLayerFont->CreateFontIndirect(&LFont); // create our small label Font LFont.lfHeight = 10; LFont.lfWidth = 0; LFont.lfQuality&=~ANTIALIASED_QUALITY; strcpy(LFont.lfFaceName,"Small Fonts"); m_pSmallFont = new CFont(); m_pSmallFont->CreateFontIndirect(&LFont); // create image list m_pImageList = new CImageList(); } //------------------------------------------------------------------------------------------------------------ void DlgStats::_DestroyFonts() { delete m_pLabelBoldFont; delete m_pLabelFont; delete m_pSmallFont; delete m_pLayerFont; delete m_pImageList; } //------------------------------------------------------------------------------------------------------------ // prepare list view void DlgStats::_PrepareListView() { UINT evCol[]={IDS_COL_TIME,IDS_COL_PLAYER,IDS_COL_ACTION,IDS_COL_PARAMETERS,0,IDS_COL_UNITSID}; int evWidth[]={50,115,80,180,20,180}; UINT stCol[]={IDS_COL_PLAYER,IDS_COL_ACTIONS,IDS_COL_APM,IDS_COL_NULL,IDS_COL_VAPM,IDS_COL_MINERAL,IDS_COL_GAS, IDS_COL_SUPPLY,IDS_COL_UNITS,IDS_COL_APMPM,IDS_COL_APMMAX,IDS_COL_APMMIN,IDS_COL_BASE,IDS_COL_MICRO,IDS_COL_MACRO}; int stWidth[]={115,50,40,35,45,50,50,50,50,50,60,60,40,40,45}; // Allow the header controls item to be movable by the user. // and set full row selection m_listEvents.SetExtendedStyle(m_listEvents.GetExtendedStyle()|LVS_EX_HEADERDRAGDROP+LVS_EX_FULLROWSELECT); CString colTitle; for(int i=0;i<sizeof(evCol)/sizeof(evCol[0]);i++) { if(evCol[i]!=0) colTitle.LoadString(evCol[i]); else colTitle=""; m_listEvents.InsertColumn(i, colTitle,LVCFMT_LEFT,evWidth[i],i); } // Set the background color COLORREF clrBack = RGB(255,255,255); m_listEvents.SetBkColor(clrBack); m_listEvents.SetTextBkColor(clrBack); m_listEvents.SetTextColor(RGB(10,10,10)); m_listEvents.SubclassHeaderControl(); // player stats m_plStats.SetExtendedStyle(m_plStats.GetExtendedStyle()|LVS_EX_HEADERDRAGDROP+LVS_EX_FULLROWSELECT); for(int i=0;i<sizeof(stCol)/sizeof(stCol[0]);i++) { if(stCol[i]!=0) colTitle.LoadString(stCol[i]); else colTitle=""; m_plStats.InsertColumn(i, colTitle,LVCFMT_LEFT,stWidth[i],i); } DlgBrowser::LoadColumns(&m_plStats,"plstats"); // Set the background color m_plStats.SetBkColor(clrBack); m_plStats.SetTextBkColor(clrBack); m_plStats.SetTextColor(RGB(10,10,10)); // create, initialize, and hook up image list m_pImageList->Create(16, 16, ILC_COLOR4, 2, 2); m_pImageList->SetBkColor(clrBack); // add icons CWinApp *pApp = AfxGetApp(); m_pImageList->Add(pApp->LoadIcon(IDI_ICON_DISABLE)); m_pImageList->Add(pApp->LoadIcon(IDI_ICON_OK)); m_plStats.SetImageList(m_pImageList, LVSIL_SMALL); } //------------------------------------------------------------------------------------------------------------ void DlgStats::UpdateBkgBitmap() { // re-init all pens for drawing all the charts _InitAllDrawingTools(); // load background bitmap if any Invalidate(); } //------------------------------------------------------------------------------------------------------------ BOOL DlgStats::OnInitDialog() { CDialog::OnInitDialog(); // init chart type CComboBox *charttype = (CComboBox *)GetDlgItem(IDC_CHARTTYPE); CString msg; msg.LoadString(IDS_CT_APM); charttype->AddString(msg); msg.LoadString(IDS_CT_RESOURCES); charttype->AddString(msg); msg.LoadString(IDS_CT_UNITDIST); charttype->AddString(msg); msg.LoadString(IDS_CT_ACTIONDIST); charttype->AddString(msg); msg.LoadString(IDS_CT_BUILDDIST); charttype->AddString(msg); msg.LoadString(IDS_CT_UPGRADES); charttype->AddString(msg); msg.LoadString(IDS_CT_APMDIST); charttype->AddString(msg); msg.LoadString(IDS_CT_BO); charttype->AddString(msg); msg.LoadString(IDS_CT_HOTKEYS); charttype->AddString(msg); msg.LoadString(IDS_CT_MAPCOVERGAGE); charttype->AddString(msg); msg.LoadString(IDS_CT_MIX_APMHOTKEYS); charttype->AddString(msg); charttype->SetCurSel(m_chartType); // prepare list view _PrepareListView(); // resize CRect rect; GetClientRect(&rect); _Resize(rect.Width(),rect.Height()); // update screen OnSelchangeCharttype(); // create map window m_dlgmap->Create(DlgMap::IDD,(CWnd*)this); // load some strings strDrop.LoadString(IDS_DROP); strExpand.LoadString(IDS_EXPAND); strLeave.LoadString(IDS_LEAVE); strMinGas.LoadString(IDS_MINGAS); strSupplyUnit.LoadString(IDS_SUPPLYUNIT); strMinimapPing.LoadString(IDS_MINIMAPPING); #ifndef NDEBUG GetDlgItem(IDC_TESTREPLAYS)->ShowWindow(SW_SHOW); #endif return TRUE; // return TRUE unless you set the focus to a control } //----------------------------------------------------------------------------------------------------------------- // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void DlgStats::OnPaint() { CPaintDC dc(this); // device context for painting if (!IsIconic()) { // fill chart background OPTIONSCHART->PaintBackground(&dc,m_boardRect); // draw tracking rect for vertical resizing CRect resizeRect; _GetResizeRect(resizeRect); resizeRect.DeflateRect(resizeRect.Width()/3,1); CRect resizeRect2(resizeRect); resizeRect2.right = resizeRect2.left+10; dc.Draw3dRect(&resizeRect2,RGB(220,220,220),RGB(180,180,180)); resizeRect2=resizeRect; resizeRect2.left = resizeRect2.right-10; dc.Draw3dRect(&resizeRect2,RGB(220,220,220),RGB(180,180,180)); // draw tracking rect for horizontal resizing _GetHorizResizeRect(resizeRect); resizeRect.DeflateRect(2,resizeRect.Height()/3); resizeRect2=resizeRect; resizeRect2.bottom = resizeRect2.top+10; dc.Draw3dRect(&resizeRect2,RGB(220,220,220),RGB(180,180,180)); resizeRect2=resizeRect; resizeRect2.top = resizeRect2.bottom-10; dc.Draw3dRect(&resizeRect2,RGB(220,220,220),RGB(180,180,180)); // paint charts if(m_replay.IsDone()) _PaintCharts(&dc); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_GetCursorRect(CRect& rect, unsigned long time, int width) { // only repaint around the time cursor rect = m_boardRect; rect.left += m_dataAreaX; float finc = (float)(rect.Width()-hleft-hright)/(float)(m_timeEnd - m_timeBegin); float fx=(float)(rect.left+hleft) + finc * (time-m_timeBegin); rect.right = width+(int)fx; rect.left = -width+(int)fx;; } //----------------------------------------------------------------------------------------------------------------- // bUserControl = true when the cursor is changed by the user // void DlgStats::_SetTimeCursor(unsigned long value, bool bUpdateListView, bool bUserControl) { // repaint current cursor zone CRect rect; _GetCursorRect(rect, m_timeCursor, 2); InvalidateRect(rect,FALSE); // update cursor m_timeCursor = value; _GetCursorRect(rect, m_timeCursor, 2); if(m_zoom>0 && (m_timeCursor<m_timeBegin || m_timeCursor>m_timeEnd)) { // the time window has changed, we must repaint everything _AdjustWindow(); rect = m_boardRect; } // update scroller m_scroller.SetScrollPos(value/HSCROLL_DIVIDER); // if we are animating if(m_bIsAnimating) { // if the animation timer is the one who changed the cursor if(!bUserControl) { // only repaint around the time cursor int width = 16 + m_animationSpeed; _GetCursorRect(rect, m_timeCursor, width); } else { // the user has changed the cursor during the animation // we must repaint everything rect = m_boardRect; } } // update map if(bUserControl) m_dlgmap->ResetTime(m_timeCursor); // repaint view InvalidateRect(rect,FALSE); // update list of events if(bUpdateListView) { // select corresponding line in list view unsigned long idx = _GetEventFromTime(m_timeCursor); m_lockListView=true; m_listEvents.SetItemState(idx,LVIS_SELECTED|LVIS_FOCUSED,LVIS_SELECTED|LVIS_FOCUSED); m_listEvents.EnsureVisible(idx,FALSE); m_lockListView=false; } // update exact time m_exactTime = _MkTime(m_replay.QueryFile()->QueryHeader(),value,true); UpdateData(FALSE); } //----------------------------------------------------------------------------------------------------------------- // display player stats void DlgStats::_DisplayPlayerStats() { m_plStats.DeleteAllItems(); // for each player for(int i=0; i<m_replay.GetPlayerCount(); i++) { // get event list ReplayEvtList *list = m_replay.GetEvtList(i); // insert player stats CString str; int nPos = m_plStats.InsertItem(i,list->PlayerName(), list->IsEnabled()?1:0); str.Format("%d",list->GetEventCount()); m_plStats.SetItemText(nPos,1,str); str.Format("%d",list->GetActionPerMinute()); m_plStats.SetItemText(nPos,2,str); str.Format("%d",list->GetDiscardedActions()); m_plStats.SetItemText(nPos,3,str); str.Format("%d",list->GetValidActionPerMinute()); m_plStats.SetItemText(nPos,4,str); str.Format("%d",list->ResourceMax().Minerals()); m_plStats.SetItemText(nPos,5,str); str.Format("%d",list->ResourceMax().Gaz()); m_plStats.SetItemText(nPos,6,str); str.Format("%d",(int)list->ResourceMax().Supply()); m_plStats.SetItemText(nPos,7,str); str.Format("%d",list->ResourceMax().Units()); m_plStats.SetItemText(nPos,8,str); str.Format("%d",list->GetStandardAPMDev(-1,-1)); m_plStats.SetItemText(nPos,9,str); str.Format("%d",list->ResourceMax().LegalAPM()); m_plStats.SetItemText(nPos,10,str); str.Format("%d",list->GetMiniAPM()); m_plStats.SetItemText(nPos,11,str); str.Format("%d",list->GetStartingLocation()); m_plStats.SetItemText(nPos,12,str); str.Format("%d",list->GetMicroAPM()); m_plStats.SetItemText(nPos,13,str); str.Format("%d",list->GetMacroAPM()); m_plStats.SetItemText(nPos,14,str); m_plStats.SetItemData(nPos,(DWORD)list); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::LoadReplay(const char *reppath, bool bClear) { CWaitCursor wait; // stop animation if any StopAnimation(); // clear list views if(bClear) m_listEvents.DeleteAllItems(); // update map m_dlgmap->UpdateReplay(0); // load replay if(m_replay.Load(reppath,true,&m_listEvents,bClear)!=0) { CString msg; msg.Format(IDS_CORRUPTEDBIS,reppath); MessageBox(msg,0,MB_OK|MB_ICONEXCLAMATION); return; } AfxGetApp()->WriteProfileString("MAIN","LASTREPLAY",reppath); SetDlgItemText(IDC_REPLAYFILE,reppath); // udpate suspect events counts CString chktitle; int suspectCount = m_replay.GetSuspectCount(); chktitle.Format(IDS_SUSPICIOUS,suspectCount); GetDlgItem(IDC_FLT_SUSPECT)->SetWindowText(chktitle); GetDlgItem(IDC_FLT_SUSPECT)->EnableWindow(suspectCount==0?FALSE:TRUE); // udpate hack events counts int hackCount = m_replay.GetHackCount(); chktitle.Format(IDS_HACK,hackCount); GetDlgItem(IDC_FLT_HACK)->SetWindowText(chktitle); GetDlgItem(IDC_FLT_HACK)->EnableWindow(hackCount==0?FALSE:TRUE); // update "next" button GetDlgItem(IDC_NEXT_SUSPECT)->EnableWindow((suspectCount+hackCount)==0?FALSE:TRUE); // display player stats _DisplayPlayerStats(); // init view m_maxPlayerOnBoard = m_replay.GetPlayerCount(); m_timeBegin = 0; m_timeCursor = 0; m_timeEnd = (m_chartType==BUILDORDER) ? m_replay.GetLastBuildOrderTime() : m_replay.GetEndTime(); m_scroller.SetScrollRange(0,m_timeEnd/HSCROLL_DIVIDER); // init all pens for drawing all the charts _InitAllDrawingTools(); // display game duration and game date CTime cdate; CString str; time_t date = m_replay.QueryFile()->QueryHeader()->getCreationDate(); if(localtime(&date)!=0) cdate = CTime(date); else cdate = CTime(1971,1,1,0,0,0); str.Format(IDS_MKDURATION,_MkTime(m_replay.QueryFile()->QueryHeader(),m_replay.GetEndTime(),true), (const char*)cdate.Format("%d %b %y")); SetDlgItemText(IDC_GAMEDURATION,str); // update map m_dlgmap->UpdateReplay(&m_replay); GetDlgItem(IDC_SEEMAP)->EnableWindow(m_replay.GetMapAnim()==0 ? FALSE :TRUE); if(m_replay.GetMapAnim()==0) m_dlgmap->ShowWindow(SW_HIDE); // init action filter _UpdateActionFilter(true); // update apm with current style m_replay.UpdateAPM(m_apmStyle[APM], m_apmStyle[MAPCOVERAGE]); //repaint Invalidate(FALSE); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnGetevents() { // get path CString path; if(!_GetReplayFileName(path)) return; // load replay LoadReplay(path,true); } //----------------------------------------------------------------------------------------------------------------- #define CHANGEPOS(id,x,y)\ {CWnd *wnd = GetDlgItem(id);\ if(wnd && ::IsWindow(wnd->GetSafeHwnd()))\ wnd->SetWindowPos(0,x,y,0,0,SWP_NOZORDER|SWP_NOSIZE);} #define CHANGEPOSSIZE(id,x,y,w,h)\ {CWnd *wnd = GetDlgItem(id);\ if(wnd && ::IsWindow(wnd->GetSafeHwnd()))\ wnd->SetWindowPos(0,x,y,w,h,SWP_NOZORDER);} void DlgStats::_Resize(int cx, int cy) { if(!::IsWindow(m_scroller)) return; // if window was reduced a lot, make sure event list width & height is not too big if(m_wlist==0) m_wlist=min(460,(80*cx/100)); if(m_wlist>(90*cx/100)) m_wlist = 90*cx/100; if(m_hlist>(70*cy/100)) m_hlist = 70*cy/100; int hlist=m_hlist; int wlist=m_wlist; // find position of lowest control on the top CRect rectCtrl; GetDlgItem(IDC_SPEED)->GetWindowRect(&rectCtrl); ScreenToClient(&rectCtrl); int top=rectCtrl.top+rectCtrl.Height()+8; int left=10; int right=16; int wlist2=cx - wlist - right-left-2; m_boardRect.SetRect(left,top,max(16,cx-left-right),max(top+16,cy-32-hlist)); // scrollers if(::IsWindow(m_scroller)) m_scroller.SetWindowPos(0,left,m_boardRect.bottom,m_boardRect.Width()-218,17,SWP_NOZORDER); if(::IsWindow(m_scrollerV)) m_scrollerV.SetWindowPos(0,m_boardRect.right,top,17,m_boardRect.Height(),SWP_NOZORDER); // event list if(::IsWindow(m_listEvents)) m_listEvents.SetWindowPos(0,m_boardRect.left,cy-hlist-8+20,wlist,hlist-40,SWP_NOZORDER); // cursor time CHANGEPOS(IDC_EXACTTIME,m_boardRect.Width()-200,m_boardRect.bottom+2); // filter check boxes CHANGEPOS(IDC_FLT_SELECT,8+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_BUILD,70+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_TRAIN,146+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_OTHERS,222+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_SUSPECT,280+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_HACK,380+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_CHAT,480+m_boardRect.left,cy-hlist-8); CHANGEPOSSIZE(IDC_SUSPECT_INFO,8+m_boardRect.left,cy-22,wlist-70,12); CHANGEPOS(IDC_NEXT_SUSPECT,m_boardRect.left+wlist-58,cy-24); // player list if(::IsWindow(m_plStats)) m_plStats.SetWindowPos(0,m_boardRect.left+wlist+8,cy-hlist-8,wlist2,hlist-20,SWP_NOZORDER); // little help text if(::IsWindow(m_dlbclick)) m_dlbclick.SetWindowPos(0,m_boardRect.left+wlist+8,cy-20,0,0,SWP_NOZORDER|SWP_NOSIZE); // buttons CHANGEPOS(IDC_DHELP,m_boardRect.right-36,cy-22); CHANGEPOSSIZE(IDC_ANIMATE,m_boardRect.Width()-79,m_boardRect.bottom,49,17); CHANGEPOSSIZE(IDC_SEEMAP,m_boardRect.Width()-148,m_boardRect.bottom,69,17); CHANGEPOSSIZE(IDC_SPEEDPLUS,m_boardRect.Width()-30,m_boardRect.bottom,19,17); CHANGEPOSSIZE(IDC_SPEEDMINUS,m_boardRect.Width()-11,m_boardRect.bottom,19,17); CHANGEPOSSIZE(IDC_PAUSE,m_boardRect.Width()+8,m_boardRect.bottom,19,17); Invalidate(TRUE); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); if(cx!=0 && cy!=0) _Resize(cx, cy); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintOneEvent(CDC *pDC, const CRect* pRect, const ReplayEvt *evt) { COLORREF m_color = evt->GetColor(); COLORREF oldColor = pDC->GetBkColor(); switch(m_shape) { case SQUARE: pDC->FillSolidRect(pRect,m_color); break; case RECTANGLE: pDC->Draw3dRect(pRect,m_color,m_color); break; case FLAG: case FLAGEMPTY: { CRect rect = *pRect; rect.bottom = rect.top+rect.Height()/2; rect.right = rect.left + (3*rect.Width())/4; if(m_shape==FLAG) pDC->FillSolidRect(&rect,m_color); else pDC->Draw3dRect(&rect,m_color,m_color); rect = *pRect; rect.right = rect.left+1; pDC->FillSolidRect(&rect,m_color); } break; case TEALEFT: case TEARIGHT: { CRect rect = *pRect; if(m_shape==TEALEFT) rect.right = rect.left+1; rect.left = rect.right-1; pDC->FillSolidRect(&rect,m_color); rect.right = pRect->right; rect.left = pRect->left; rect.top=pRect->top+pRect->Height()/2; rect.bottom = rect.top+1; pDC->FillSolidRect(&rect,m_color); } break; case TEATOP: case TEABOTTOM: { CRect rect = *pRect; if(m_shape==TEATOP) rect.bottom = rect.top+1; rect.top = rect.bottom-1; pDC->FillSolidRect(&rect,m_color); rect.top = pRect->top; rect.bottom = pRect->bottom; rect.left=pRect->left+pRect->Width()/2; rect.right = rect.left+1; pDC->FillSolidRect(&rect,m_color); } break; case ROUNDRECT: CPen pen(PS_SOLID,1,m_color); CBrush brush(m_color); CPen *oldPen = pDC->SelectObject(&pen); CBrush *oldBrush = pDC->SelectObject(&brush); pDC->RoundRect(pRect,CPoint(4,4)); pDC->SelectObject(oldBrush); pDC->SelectObject(oldPen); break; } pDC->SetBkColor(oldColor); } //----------------------------------------------------------------------------------------------------------------- DrawingTools* DlgStats::_GetDrawingTools(int player) { if(player>=0) return &m_dtools[player+1]; return &m_dtools[0]; } //----------------------------------------------------------------------------------------------------------------- // init all pens for drawing all the charts void DlgStats::_InitAllDrawingTools() { // init drawing tools for multiple frame mode _InitDrawingTools(-1,m_maxPlayerOnBoard,1); // init drawing tools for all players on one frame mode for(int i=0;i<m_maxPlayerOnBoard;i++) _InitDrawingTools(i,m_maxPlayerOnBoard,2); } //----------------------------------------------------------------------------------------------------------------- // init all pens for drawing the charts of one player void DlgStats::_InitDrawingTools(int player, int maxplayer, int /*lineWidth*/) { // clear tools DrawingTools *tools = _GetDrawingTools(player); tools->Clear(); // create pen for minerals for(int i=0; i<DrawingTools::maxcurve;i++) { int lineSize = ReplayResource::GetLineSize(i); tools->m_clr[i] = ReplayResource::GetColor(i,player,maxplayer); tools->m_penMineral[i] = new CPen(PS_SOLID,lineSize,tools->m_clr[i]); tools->m_penMineralS[i] = new CPen(PS_SOLID,1,tools->m_clr[i]); tools->m_penMineralDark[i] = new CPen(PS_SOLID,1,CHsvRgb::Darker(tools->m_clr[i],0.70)); } } //----------------------------------------------------------------------------------------------------------------- // draw a little text to show a hot point void DlgStats::_PaintHotPoint(CDC *pDC, int x, int y, const ReplayEvt *evt, COLORREF clr) { const char *hotpoint=0; const IStarcraftAction *action = evt->GetAction(); int off=8; //if event is a hack if(evt->IsHack()) { // make color lighter COLORREF clrt = RGB(255,0,0); // draw a little triangle there int off=3; CPen clr(PS_SOLID,1,clrt); CPen clr2(PS_SOLID,1,RGB(160,0,0)); CPen *old=(CPen*)pDC->SelectObject(&clr); for(int k=0;k<3;k++) { pDC->MoveTo(x-k,y-off-k); pDC->LineTo(x+k+1,y-off-k); } pDC->SelectObject(&clr2); for(int k=3;k<5;k++) { pDC->MoveTo(x-k,y-off-k); pDC->LineTo(x+k+1,y-off-k); } pDC->SelectObject(old); } // Expand? if(action->GetID()==BWrepGameData::CMD_BUILD) { int buildID = evt->UnitIdx(); if(buildID == BWrepGameData::OBJ_COMMANDCENTER || buildID == BWrepGameData::OBJ_HATCHERY || buildID == BWrepGameData::OBJ_NEXUS) hotpoint = strExpand; if(buildID == BWrepGameData::OBJ_COMMANDCENTER) { // make sure it's not just a "land" const BWrepActionBuild::Params *p = (const BWrepActionBuild::Params *)action->GetParamStruct(); if(p->m_buildingtype!=BWrepGameData::BTYP_BUILD) hotpoint=0; } } // Leave game? else if(action->GetID()==BWrepGameData::CMD_LEAVEGAME) { hotpoint = strLeave; } // Drop? else if(action->GetID()==BWrepGameData::CMD_UNLOAD || action->GetID()==BWrepGameData::CMD_UNLOADALL || (action->GetID()==BWrepGameData::CMD_ATTACK && evt->Type().m_subcmd==BWrepGameData::ATT_UNLOAD)) { hotpoint = strDrop; } // Minimap ping? else if(action->GetID()==BWrepGameData::CMD_MINIMAPPING) { hotpoint = strMinimapPing; } // no hot point? if(hotpoint==0) return; // previous hotpoint too close? if((x-lastHotPointX)<32 && lastHotPoint==hotpoint) return; // make color lighter clr = CHsvRgb::Darker(clr,1.5); // get text size int w = pDC->GetTextExtent(hotpoint).cx; CRect rectTxt(x-w/2-off,y-off,x+w/2-off,y-10-off); // draw text pDC->SetTextColor(clr); int omode = pDC->SetBkMode(TRANSPARENT); pDC->DrawText(hotpoint,&rectTxt,DT_SINGLELINE|DT_CENTER|DT_VCENTER); pDC->SetBkMode(omode); // draw joining line pDC->MoveTo(x-off,y-off); pDC->LineTo(x,y); lastHotPointX = x; lastHotPoint = hotpoint; } //----------------------------------------------------------------------------------------------------------------- // draw a local maximum void DlgStats::_DrawLocalMax(CDC *pDC, int rx, int ry, const COLORREF clr, int& lastMaxX, int maxval) { // if it's not too close to previous Max if(rx>lastMaxX+32) { // draw a little triangle there lastMaxX = rx; for(int k=0;k<5;k++) { pDC->MoveTo(rx-k,ry-3-k); pDC->LineTo(rx+k+1,ry-3-k); } // draw max value CRect rectTxt(rx-16,ry-20,rx+16,ry-10); CString strMax; strMax.Format("%d",maxval); CFont *oldFont=pDC->SelectObject(m_pSmallFont); COLORREF oldClr=pDC->SetTextColor(clr); int omode = pDC->SetBkMode(TRANSPARENT); pDC->DrawText(strMax,rectTxt,DT_CENTER|DT_SINGLELINE); pDC->SetBkMode(omode); pDC->SetTextColor(oldClr); pDC->SelectObject(oldFont); } } //----------------------------------------------------------------------------------------------------------------- static const double BWPI = 3.1415926535897932384626433832795; static double _CosineInterpolate(double y1,double y2,double mu) { double mu2 = (1-cos(mu*BWPI))/2; return(y1*(1-mu2)+y2*mu2); } //----------------------------------------------------------------------------------------------------------------- class CKnotArray { public: //ctor CKnotArray(int knotcount) : m_knotcount(knotcount) { m_knots = new CPoint*[ReplayResource::__CLR_MAX]; for(int i=0;i<ReplayResource::__CLR_MAX;i++) m_knots[i] = new CPoint[knotcount]; memset(m_isUsed,0,sizeof(m_isUsed)); } //dtor ~CKnotArray() { for(int i=0;i<ReplayResource::__CLR_MAX;i++) delete[]m_knots[i]; delete[]m_knots; } // access CPoint *GetKnots(int curveidx) const {return m_knots[curveidx];} int GetKnotCount() const {return m_knotcount;} bool IsUsed(int i) const {return m_isUsed[i];} void SetIsUsed(int i) {m_isUsed[i]=true;} private: CPoint **m_knots; int m_knotcount; bool m_isUsed[ReplayResource::__CLR_MAX]; }; //----------------------------------------------------------------------------------------------------------------- // draw resource lines for one resource slot void DlgStats::_PaintResources2(CDC *pDC, int ybottom, int cx, DrawingTools *tools, ReplayResource *res, unsigned long time, CKnotArray& knot, int knotidx) { static int rx[DrawingTools::maxcurve],ry[DrawingTools::maxcurve]; static int orx[DrawingTools::maxcurve],ory[DrawingTools::maxcurve]; // save all current points for(int j=0; j<ReplayResource::MaxValue(); j++) { orx[j] = rx[j]; ory[j] = ry[j]; } // for each resource type for(int j=0; j<ReplayResource::MaxValue(); j++) { if(j==0 && (!m_seeMinerals || m_chartType!=RESOURCES)) continue; if(j==1 && (!m_seeGaz || m_chartType!=RESOURCES)) continue; if(j==2 && (!m_seeSupply || m_chartType!=RESOURCES)) continue; if(j==3 && (!m_seeUnits[m_chartType] || m_chartType!=RESOURCES)) continue; if(j==4 && (m_chartType!=APM)) continue; if(j==5 && (!m_seeBPM || m_chartType!=APM)) continue; if(j==6 && (!m_seeUPM || m_chartType!=APM)) continue; if(j==7 && (m_chartType!=APM)) continue; // micro if(j==8) continue; if(j==9 && m_chartType!=MAPCOVERAGE) continue; if(j==10 && (!m_seeUnits[m_chartType] || m_chartType!=MAPCOVERAGE)) continue; // we had a previous point, move beginning of line on it CPoint firstpt(rx[j],ry[j]); if(!firstPoint) pDC->MoveTo(rx[j],ry[j]); // compute position rx[j] = cx; ry[j] = ybottom - (int)((float)(res->Value(j))*m_fvinc[j]); // use splines? bool nodraw=false; if(j<4 || j==9 || j==10 || (j==4 && !m_seeSpeed)) {knot.GetKnots(j)[knotidx]=CPoint(cx,ry[j]); knot.SetIsUsed(j); nodraw=true;} // if upm or bpm if(j==5 || j==6) { // paint upm / bpm bar int w = max(4,(int)m_finc); pDC->FillSolidRect(cx-w/2,ry[j],w,ybottom-ry[j],tools->m_clr[j]); } else { // paint segment for resource line if(!firstPoint) pDC->SelectObject(tools->m_penMineral[j]); if(!nodraw) { if(!firstPoint && j!=7) { // if segment is long enough, and not a straight line if(cx-firstpt.x>8 && firstpt.y!=ry[j]) { // interpolate it for(int x=firstpt.x;x<=cx;x++) { double mu = (double)(x-firstpt.x)/(double)(cx-firstpt.x); double y = _CosineInterpolate(firstpt.y,ry[j],mu); pDC->LineTo(x,(int)y); } } else pDC->LineTo(rx[j],ry[j]); } } // is it a max for APM? if(j==4 && OPTIONSCHART->m_maxapm && res->Value(j) == m_list->ResourceMax().LegalAPM() && time>=MINAPMVALIDTIMEFORMAX) _DrawLocalMax(pDC, rx[j], ry[j], tools->m_clr[j], lastMaxX, m_list->ResourceMax().LegalAPM()); // is it a max for MAP coverage? if(j==10 && OPTIONSCHART->m_maxapm && res->Value(j) == m_list->ResourceMax().MovingMapCoverage()) _DrawLocalMax(pDC, rx[j], ry[j], tools->m_clr[j], lastMaxX, m_list->ResourceMax().MovingMapCoverage()); } } // compute position rx[4] = cx; ry[4] = ybottom - (int)((float)(res->Value(4))*m_fvinc[4]); // if macro is on if(m_chartType==APM && m_seeSpeed && !firstPoint) { // paint surface POINT pt[4]; pt[0].x = orx[4]; pt[1].x = rx[4]; pt[2].x = rx[7]; pt[3].x = orx[7]; pt[0].y = ory[4]; pt[1].y = ry[4]; pt[2].y = ry[7]; pt[3].y = ory[7]; CBrush bkgpoly(tools->m_clr[4]); CBrush *oldb = pDC->SelectObject(&bkgpoly); pDC->SelectObject(tools->m_penMineral[4]); pDC->Polygon(pt, 4); pDC->SelectObject(oldb); // draw up and bottom lines in darker color for antialiasing //CPen penred(PS_SOLID,2,RGB(235,0,0)); //CPen pengreen(PS_SOLID,2,RGB(0,0,235)); pDC->SelectObject(tools->m_penMineralDark[4]); //pDC->SelectObject(&penred); pDC->MoveTo(pt[0].x,pt[0].y); pDC->LineTo(pt[1].x,pt[1].y); //pDC->SelectObject(&pengreen); pDC->MoveTo(pt[2].x,pt[2].y); pDC->LineTo(pt[3].x,pt[3].y); } firstPoint=false; } //----------------------------------------------------------------------------------------------------------------- // paint a spline curve void DlgStats::_PaintSpline(CDC *pDC, const CKnotArray& knots, int curveidx) { // compute control points CPoint* firstControlPoints=0; CPoint* secondControlPoints=0; BezierSpline::GetCurveControlPoints(knots.GetKnots(curveidx), knots.GetKnotCount(), firstControlPoints, secondControlPoints); // allocate point array for call to PolyBezier int ptcount = 3*(knots.GetKnotCount()-1)+1; POINT* pts = new POINT[ptcount]; for(int i=0;i<knots.GetKnotCount()-1;i++) { int step = i*3; pts[step]=knots.GetKnots(curveidx)[i]; pts[step+1]=firstControlPoints[i]; pts[step+2]=secondControlPoints[i]; } pts[ptcount-1]=knots.GetKnots(curveidx)[knots.GetKnotCount()-1]; // draw curve pDC->PolyBezier(pts,ptcount); // delete arrays delete[]pts; delete[]firstControlPoints; delete[]secondControlPoints; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintEvents(CDC *pDC, int chartType, const CRect& rect, const ReplayResource& resmax, int player) { // any event to draw? if(m_list->GetEventCount()==0) return; // compute all ratios depending on the max of every resource float rheight = (float)(rect.Height()-vtop-vbottom); m_fvinc[0] = m_fvinc[1] = rheight/(float)(max(resmax.Minerals(),resmax.Gaz())); m_fvinc[2] = m_fvinc[3] = rheight/(float)(max(resmax.Supply(),resmax.Units())); m_fvinc[4] = rheight/(float)resmax.APM(); m_fvinc[5] = rheight/((float)resmax.BPM()*4.0f); m_fvinc[6] = rheight/((float)resmax.UPM()*2.0f); m_fvinc[7] = rheight/(float)resmax.APM(); m_fvinc[8] = rheight/(float)(resmax.MacroAPM()*4); m_fvinc[9] = m_fvinc[10] = rheight/(float)(max(resmax.MapCoverage(),resmax.MovingMapCoverage())); m_finc = (float)(rect.Width()-hleft-hright)/(float)(m_timeEnd - m_timeBegin); // get drawing tools DrawingTools *tools = _GetDrawingTools(player); CPen *oldPen = (CPen*)pDC->SelectObject(tools->m_penMineral[0]); int oldMode = pDC->GetBkMode(); COLORREF oldclr = pDC->GetBkColor(); CFont *oldfont = pDC->SelectObject(m_pSmallFont); // where do we start painting? unsigned long timeBegin = m_timeBegin; //unsigned long timeBegin = m_bIsAnimating ? m_timeCursor : m_timeBegin; //if(m_timeCursor<500) timeBegin = 0; else timeBegin-=500; // reset last max data lastMaxX = 0; lastHotPointX = 0; lastHotPoint = 0; // for all resource slots firstPoint=true; int slotBegin = m_list->Time2Slot(m_timeBegin); int slotEnd = m_list->Time2Slot(m_timeEnd); // m_list->GetSlotCount() int slotCount = slotEnd-slotBegin; int divider = max(1,slotCount/gSplineCount[chartType]); int knotcount = slotCount==0 ? 0 : (slotCount/divider); CKnotArray *knots = knotcount==0 ? 0 : new CKnotArray(knotcount); for(int slot = slotBegin; slot<slotEnd; slot++) { // get resource object ReplayResource *res = m_list->GetResourceFromIdx(slot); unsigned long tick = m_list->Slot2Time(slot); // compute event position on X float fx=(float)(rect.left+hleft) + m_finc * (tick-m_timeBegin); int cx = (int)fx; // draw resource lines int knotslot = min(knotcount-1,(slot-slotBegin)/divider); _PaintResources2(pDC, rect.bottom - vbottom, cx, tools, res, tick, *knots, knotslot); } if(knots!=0) { // paint splines for(int i=0;i<ReplayResource::MaxValue();i++) if(knots->IsUsed(i)) { pDC->SelectObject(tools->m_penMineral[i]); _PaintSpline(pDC,*knots,i); } delete knots; } if(m_chartType==RESOURCES && (m_seeActions || (m_seeMinerals && m_seeHotPoints))) { // for each event in the current window, paint hot points int layer=0; unsigned long eventMax = (unsigned long)m_list->GetEventCount(); CRect rectEvt; firstPoint=true; lastMaxX = 0; lastHotPointX = 0; lastHotPoint = 0; for(unsigned long idx = m_list->GetEventFromTime(timeBegin);;idx++) { // get event description if(idx>=eventMax) break; const ReplayEvt *evt = m_list->GetEvent(idx); if(evt->Time()>m_timeEnd) break; // during animation, we only paint until cursor if(m_bIsAnimating && evt->Time()>m_timeCursor) break; // compute event position on X float fx=(float)(rect.left+hleft) + m_finc * (evt->Time()-m_timeBegin); int cx = (int)fx; // if we paint actions if(m_seeActions) { // compute event rect rectEvt.left=cx-evtWidth/2; rectEvt.right=cx+evtWidth/2; layer = m_replay.GetTypeIdx(evt); rectEvt.bottom=rect.bottom-vbottom-layer*layerHeight-(layerHeight-evtHeight)/2; rectEvt.top=rectEvt.bottom-evtHeight-(layerHeight-evtHeight)/2+1; if(rectEvt.top>rect.top) _PaintOneEvent(pDC,&rectEvt,evt); } // draw hot point (if any) firstPoint=false; if(m_seeMinerals && m_seeHotPoints && !evt->IsDiscarded()) { int y = rect.bottom-vbottom - (int)((float)(evt->Resources().Value(0))*m_fvinc[0]); pDC->SelectObject(tools->m_penMineralS[0]); _PaintHotPoint(pDC, cx, y, evt, tools->m_clr[0]); } } } else if(m_chartType==APM) { // for each event in the current window, paint hot points unsigned long eventMax = (unsigned long)m_list->GetEventCount(); CRect rectEvt; for(unsigned long idx = m_list->GetEventFromTime(timeBegin);;idx++) { // get event description if(idx>=eventMax) break; const ReplayEvt *evt = m_list->GetEvent(idx); if(evt->Time()>m_timeEnd) break; if(evt->ActionID()!=BWrepGameData::CMD_MESSAGE) continue; // during animation, we only paint until cursor if(m_bIsAnimating && evt->Time()>m_timeCursor) break; // compute event position on X float fx=(float)(rect.left+hleft) + m_finc * (evt->Time()-m_timeBegin); int cx = (int)fx; // if we paint actions if(m_seeHotPoints) { // compute event rect rectEvt.left=cx-evtWidth/2; rectEvt.right=cx+evtWidth/2; int layer = 0; rectEvt.bottom=rect.bottom-vbottom-layer*layerHeight-(layerHeight-evtHeight)/2; rectEvt.top=rectEvt.bottom-evtHeight-(layerHeight-evtHeight)/2+1; if(rectEvt.top>rect.top) _PaintOneEvent(pDC,&rectEvt,evt); } } } else if(m_chartType==MAPCOVERAGE) { } // restore every gdi stuff pDC->SelectObject(oldPen); pDC->SetBkMode(oldMode); pDC->SetBkColor(oldclr); pDC->SelectObject(oldfont); } //----------------------------------------------------------------------------------------------------------------- // compute vertical increment for grid and axis float DlgStats::_ComputeGridInc(unsigned long& tminc, unsigned long& maxres, const CRect& rect, const ReplayResource& resmax, int chartType, bool useGivenMax) const { if(!useGivenMax) { // compute max value switch(chartType) { case APM : maxres = resmax.APM(); break; case MAPCOVERAGE : maxres = max(resmax.MapCoverage(),resmax.MovingMapCoverage()); break; default: maxres = max(resmax.Minerals(),resmax.Gaz()); } } // compute vertical pixel per value float fvinc = (float)(rect.Height()-vbottom-vtop)/(float)(maxres); // compute grid increment tminc=((maxres/10)/1000)*1000; if(tminc==0) tminc=tminc=((maxres/10)/100)*100; if(tminc==0) tminc=((maxres/10)/10)*10; if(tminc==0) tminc=5; if(maxres<15) tminc=1; return fvinc; } void DlgStats::_PaintGrid(CDC *pDC, const CRect& rect, const ReplayResource& resmax) { if(!OPTIONSCHART->m_bggrid) return; // create pen for axis CPen *penGrid = new CPen(PS_DOT,1,clrGrid); CPen *oldPen = pDC->SelectObject(penGrid); int oldmode = pDC->SetBkMode(TRANSPARENT); // draw horizontal lines of grid unsigned long maxres = 0; unsigned long tminc; float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax,m_chartType); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { // draw grid float fy=(float)(rect.bottom-vbottom) - fvinc * tr; pDC->MoveTo(rect.left+hleft+1,(int)fy); pDC->LineTo(rect.right-hright,(int)fy); } // restore every gdi stuff pDC->SetBkMode(oldmode); pDC->SelectObject(oldPen); delete penGrid; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintActionsName(CDC *pDC, const CRect& rect) { if(!m_seeActions || m_chartType!=RESOURCES) return; // draw layers CString strNum; CRect rectTxt; CFont *oldFont = pDC->SelectObject(m_pLayerFont); // compute first layer rect CRect rectLayer=rect; rectLayer.top = rectLayer.bottom-layerHeight; rectLayer.OffsetRect(hleft,-vbottom); rectLayer.right-=hleft+hright; COLORREF bkc = pDC->GetBkColor(); // for each layer for(int k=0; k<m_replay.GetTypeCount();k++) { // fill layer rect COLORREF clrLayer = (k%2)==0 ? clrLayer1 : clrLayer2; pDC->FillSolidRect(&rectLayer,clrLayer); // draw layer action name clrLayer = (k%2)==0 ? clrLayerTxt1 : clrLayerTxt2; rectTxt = rectLayer; rectTxt.left+=28; rectTxt.right = rectTxt.left+128; pDC->SetTextColor(clrLayer); pDC->DrawText(m_replay.GetTypeStr(k),rectTxt,DT_LEFT|DT_SINGLELINE); //next layer rectLayer.OffsetRect(0,-layerHeight); if(rectLayer.bottom-layerHeight < rect.top) break; } // restore bkcolor pDC->SetBkColor(bkc); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintAxis(CDC *pDC, const CRect& rect, const ReplayResource& resmax, int mask, unsigned long timeBegin, unsigned long timeEnd) { // create pen for axis CPen *penTime = new CPen(PS_SOLID,1,clrTime); CPen *penAction = new CPen(PS_SOLID,1,clrAction); CPen *oldPen = (CPen*)pDC->SelectObject(penTime); int oldmode = pDC->SetBkMode(TRANSPARENT); // draw X axis values CString strNum; CRect rectTxt; float finc = timeEnd>timeBegin ? (float)(rect.Width()-hleft-hright)/(float)(timeEnd - timeBegin) : 0.0f; unsigned long tminc = 10; unsigned long maxres; while(timeEnd>timeBegin && (int)(tminc*finc)<50) tminc*=2; COLORREF oldClr = pDC->SetTextColor(clrTime); CFont *oldFont=pDC->SelectObject(m_pSmallFont); if(mask&MSK_XLINE && timeEnd>timeBegin) { for(unsigned long tm=timeBegin; tm<timeEnd; tm+=tminc) { float fx=(float)(rect.left+hleft) + finc * (tm-timeBegin); strNum = _MkTime(m_replay.QueryFile()->QueryHeader(),tm, m_useSeconds?true:false); int cx = (int)fx; // draw time rectTxt.SetRect(cx,rect.bottom-vbottom+2,cx+128,rect.bottom); pDC->DrawText(strNum,rectTxt,DT_LEFT|DT_SINGLELINE); // draw line pDC->MoveTo(cx,rect.bottom-vbottom-1); pDC->LineTo(cx,rect.bottom-vbottom+2); } } if((m_seeMinerals || m_seeGaz) && m_chartType==RESOURCES) { // draw left Y axis values (minerals and gas) int xpos = rect.left+hleft; float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType); if(mask&MSK_YLEFTLINE) { for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(xpos-1,cy); pDC->LineTo(xpos+2,cy); // draw time rectTxt.SetRect(rect.left+haxisleft,cy-8,rect.left+hleft-3,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw left Y axis title rectTxt.SetRect(rect.left+haxisleft,rect.top,rect.left+hleft+16,rect.top+16); pDC->DrawText(strMinGas,rectTxt,DT_LEFT|DT_SINGLELINE|DT_VCENTER); } } if((m_seeSupply || m_seeUnits[m_chartType]) && m_chartType==RESOURCES) { // draw right Y axis values (supply & units) if(mask&MSK_YRIGHTLINE) { maxres = resmax.Supply(); float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType,true); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(rect.right-hright-1,cy); pDC->LineTo(rect.right-hright+2,cy); // draw time rectTxt.SetRect(rect.right-hright-4-64,cy-8,rect.right-hright-4,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw right Y axis title rectTxt.SetRect(rect.right-hright-64,rect.top,rect.right-hright-4,rect.top+16); pDC->DrawText(strSupplyUnit,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } } if(m_chartType==APM) { pDC->SelectObject(penAction); pDC->SetTextColor(clrAction); // draw actions/minute Y axis values int xpos = rect.left+hleft; float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(xpos-1,cy); pDC->LineTo(xpos+2,cy); // draw time rectTxt.SetRect(rect.left+haxisleft,cy-8,rect.left+hleft-3,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw actions/minute Y axis title rectTxt.SetRect(rect.left+haxisleft,rect.top,rect.left+hleft-3,rect.top+16); pDC->DrawText("APM",rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); // draw right Y axis values (supply & units) if(mask&MSK_YRIGHTLINE) { fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(rect.right-hright-1,cy); pDC->LineTo(rect.right-hright+2,cy); // draw time rectTxt.SetRect(rect.right-hright-4-64,cy-8,rect.right-hright-4,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw right Y axis title rectTxt.SetRect(rect.right-hright-64,rect.top,rect.right-hright-4,rect.top+16); pDC->DrawText("APM",rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } } else if(m_chartType==MAPCOVERAGE) { pDC->SelectObject(penAction); pDC->SetTextColor(clrAction); // draw coverage Y axis values int xpos = rect.left+hleft; float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(xpos-1,cy); pDC->LineTo(xpos+2,cy); // draw time rectTxt.SetRect(rect.left+haxisleft,cy-8,rect.left+hleft-3,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw building map coverage Y axis title rectTxt.SetRect(rect.left+haxisleft,rect.top,rect.left+hleft-3,rect.top+16); pDC->DrawText("%Map",rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); if(m_seeUnits[m_chartType]) { // draw right Y axis values (unit map coverage) if(mask&MSK_YRIGHTLINE) { maxres = resmax.MovingMapCoverage(); float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType,true); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(rect.right-hright-1,cy); pDC->LineTo(rect.right-hright+2,cy); // draw time rectTxt.SetRect(rect.right-hright-4-64,cy-8,rect.right-hright-4,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw right Y axis title rectTxt.SetRect(rect.right-hright-64,rect.top,rect.right-hright-4,rect.top+16); pDC->DrawText("%Map",rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } } } // restore every gdi stuff pDC->SetBkMode(oldmode); pDC->SelectObject(oldPen); pDC->SetTextColor(oldClr); pDC->SelectObject(oldFont); delete penTime; delete penAction; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintAxisLines(CDC *pDC, const CRect& rect, int mask) { // create pen for axis CPen *penTime = new CPen(PS_SOLID,1,clrTime); CPen *oldPen = (CPen*)pDC->SelectObject(penTime); // draw X axis time line if(mask&MSK_XLINE) { pDC->MoveTo(rect.left+hleft,rect.bottom-vbottom); pDC->LineTo(rect.right-hright,rect.bottom-vbottom); } // draw left Y axis time line if(mask&MSK_YLEFTLINE) { pDC->MoveTo(rect.left+hleft,rect.bottom-vbottom); pDC->LineTo(rect.left+hleft,rect.top+vtop); } // draw right Y axis time line if(mask&MSK_YRIGHTLINE) { pDC->MoveTo(rect.right-hright,rect.bottom-vbottom); pDC->LineTo(rect.right-hright,rect.top+vtop); } // restore every gdi stuff pDC->SelectObject(oldPen); delete penTime; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintBackgroundLayer(CDC *pDC, const CRect& rect, const ReplayResource& resmax) { // draw horizontal lines of grid _PaintGrid(pDC, rect, resmax); // draw layers _PaintActionsName(pDC, rect); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintForegroundLayer(CDC *pDC, const CRect& rect, const ReplayResource& resmax, int mask) { // draw X & Yaxis time line _PaintAxisLines(pDC, rect, mask); // draw X & Y axis values _PaintAxis(pDC, rect, resmax,MSK_ALL,m_timeBegin,m_timeEnd); // draw cursor _PaintCursor(pDC, rect); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintMapName(CDC *pDC, CRect& rect) { if(m_chartType!=RESOURCES && m_chartType!=APM) return; // select font & color CFont *oldFont = pDC->SelectObject(m_pLabelBoldFont); int oldMode = pDC->SetBkMode(TRANSPARENT); // build title CString title(m_replay.MapName()); if(m_replay.RWAHeader()!=0) { CString audioby; audioby.Format(IDS_AUDIOCOMMENT,m_replay.RWAHeader()->author); title+=audioby; } //get title size with current font CSize sz = pDC->GetTextExtent(title); // draw text CRect rectTxt; rectTxt.SetRect(rect.left+hplayer,rect.top,rect.left+hplayer+sz.cx,rect.top+28); pDC->SetTextColor(OPTIONSCHART->GetColor(DlgOptionsChart::CLR_MAP)); pDC->DrawText(title,rectTxt,DT_LEFT|DT_SINGLELINE|DT_VCENTER); m_rectMapName = rectTxt; // restore pDC->SetBkMode(oldMode); pDC->SelectObject(oldFont); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintSentinel(CDC *pDC, CRect& rectTxt) { if(m_chartType!=RESOURCES && m_chartType!=APM) return; CString gamename = m_replay.QueryFile()->QueryHeader()->getGameName(); if(gamename.Left(11)=="BWSentinel ") { // select font & color CFont *oldFont = pDC->SelectObject(m_pSmallFont); int oldMode = pDC->SetBkMode(TRANSPARENT); // draw text pDC->SetTextColor(clrPlayer); pDC->DrawText("(sentinel on)",rectTxt,DT_LEFT|DT_SINGLELINE|DT_VCENTER); // restore pDC->SetBkMode(oldMode); pDC->SelectObject(oldFont); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintPlayerName(CDC *pDC, const CRect& rectpl, ReplayEvtList *list, int playerIdx, int playerPos, COLORREF clr, int offv) { CRect rect(rectpl); rect.OffsetRect(4,0); // select font & color CFont *oldFont = pDC->SelectObject(m_pLabelBoldFont); COLORREF oldClr = pDC->SetTextColor(clr); COLORREF bkClr = pDC->GetBkColor(); int oldMode = pDC->GetBkMode(); // draw player name CString pname; CRect rectTxt; pname.Format("%s (%s)",list->PlayerName(),list->GetRaceStr()); rectTxt.SetRect(rect.left+hplayer,rect.top+offv,rect.left+hplayer+200,rect.top+offv+28); if(playerPos>=0) rectTxt.OffsetRect(0,playerPos*28); if(m_chartType!=RESOURCES && m_chartType!=APM && m_mixedCount==0) rectTxt.OffsetRect(-hplayer+hleft,0); pDC->SetTextColor(clr); pDC->SetBkMode(TRANSPARENT); pDC->DrawText(pname,rectTxt,DT_LEFT|DT_SINGLELINE|DT_VCENTER); CRect rectRatio=rectTxt; // text size int afterText = pDC->GetTextExtent(pname).cx; // draw colors of resource lines if(playerIdx>=0) { rectTxt.top+=22; rectTxt.right=rectTxt.left+12; rectTxt.bottom=rectTxt.top+3; for(int j=0; j<ReplayResource::MaxValue(); j++) { if(j==0 && (!m_seeMinerals || m_chartType!=RESOURCES)) continue; if(j==1 && (!m_seeGaz || m_chartType!=RESOURCES)) continue; if(j==2 && (!m_seeSupply || m_chartType!=RESOURCES)) continue; if(j==3 && (!m_seeUnits[m_chartType] || m_chartType!=RESOURCES)) continue; if(j==4 && (!m_seeSpeed || m_chartType!=APM)) continue; if(j==5 && (!m_seeBPM || m_chartType!=APM)) continue; if(j==6 && (!m_seeUPM || m_chartType!=APM)) continue; if(j==7 || j==8) continue; pDC->FillSolidRect(&rectTxt,_GetDrawingTools(playerIdx)->m_clr[j]); rectTxt.OffsetRect(rectTxt.Width()+3,0); } } // add player info if(m_chartType>=UNITS && m_chartType<=UPGRADES) { // display distribution total pname.Format(IDS_TOTAL,list->GetDistTotal(m_chartType-UNITS)); } else { // display APM stuff //if(m_maxPlayerOnBoard==2) //{ // compute action ratio //ReplayEvtList *list1 = m_replay.GetEvtList(0); //ReplayEvtList *list2 = m_replay.GetEvtList(1); //float ratio = list==list1 ? (float)list1->GetEventCount()/(float)list2->GetEventCount() : (float)list2->GetEventCount()/(float)list1->GetEventCount(); //pname.Format("[%.2f, %d, %d APM]",ratio,list->GetEventCount(),list->GetActionPerMinute()); //} pname.Format("[%d actions APM=%d]",list->GetEventCount(),list->GetActionPerMinute()); } rectRatio.OffsetRect(afterText+8,0); pDC->SelectObject(m_pLayerFont); pDC->SetTextColor(clrRatio); pDC->SetBkColor(RGB(0,0,0)); pDC->SetBkMode(TRANSPARENT); pDC->DrawText(pname,rectRatio,DT_LEFT|DT_SINGLELINE|DT_VCENTER); // restore every gdi stuff pDC->SetBkMode(oldMode); pDC->SelectObject(oldFont); pDC->SetTextColor(oldClr); pDC->SetBkColor(bkClr); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintCursor(CDC *pDC, const CRect& rect) { // compute position float finc = (float)(rect.Width()-hleft-hright)/(float)(m_timeEnd - m_timeBegin); float fxc=(float)(rect.left+hleft) + finc * (m_timeCursor-m_timeBegin); // prepare pen CPen *penCursor = new CPen(PS_DOT,1,clrCursor); CPen *oldPen = pDC->SelectObject(penCursor); int oldmode = pDC->SetBkMode(TRANSPARENT); // draw cursor pDC->MoveTo((int)fxc,rect.top); pDC->LineTo((int)fxc,rect.bottom); // restore every gdi stuff pDC->SetBkMode(oldmode); pDC->SelectObject(oldPen); delete penCursor; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintBO(CDC *pDC, const CRect& rect, const ReplayObjectSequence& bo, int offset) { // draw building names int levelh = (rect.Height()-32-vplayer)/4; for(int i=0;i<bo.GetCount();i++) { float finc = (float)(rect.Width()-hleft-hright)/(float)(m_timeEnd - m_timeBegin); float fxc=(float)(rect.left+hleft) + finc * bo.GetTime(i); int y = rect.top+vplayer+16 + ((i+1)%4)*levelh + offset; pDC->MoveTo((int)fxc,y); pDC->LineTo((int)fxc,rect.bottom-vbottom); // text size CString pname = bo.GetName(i); int wText = pDC->GetTextExtent(pname).cx; CRect rectText; y-=16; rectText.SetRect((int)fxc-wText/2, y, (int)fxc+wText/2, y+16); rectText.InflateRect(1,1); pDC->DrawText(pname,rectText,DT_CENTER|DT_SINGLELINE|DT_VCENTER); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintBuildOrder(CDC *pDC, const CRect& rect) { // select font & color CFont *oldFont = pDC->SelectObject(m_pLayerFont); COLORREF oldClr = pDC->SetTextColor(clrBOName[0]); int oldMode = pDC->GetBkMode(); CPen *penCursor = new CPen(PS_SOLID,1,clrBOLine[0]); CPen *penCursor2 = new CPen(PS_SOLID,1,clrBOLine[1]); CPen *penCursor3 = new CPen(PS_SOLID,1,clrBOLine[2]); // draw X & Y axis values ReplayResource resmax; _PaintAxis(pDC, rect, resmax, MSK_XLINE,m_timeBegin,m_timeEnd); // draw building names CPen *oldPen = pDC->SelectObject(penCursor); pDC->SetBkMode(TRANSPARENT); _PaintBO(pDC, rect, m_list->GetBuildOrder(),0); // draw upgrades pDC->SetTextColor(clrBOName[2]); pDC->SelectObject(penCursor3); _PaintBO(pDC, rect, m_list->GetBuildOrderUpgrade(),10); // draw research pDC->SetTextColor(clrBOName[2]); pDC->SelectObject(penCursor3); _PaintBO(pDC, rect, m_list->GetBuildOrderResearch(),20); // draw units names if(m_seeUnitsOnBO) { pDC->SetTextColor(clrBOName[1]); pDC->SelectObject(penCursor2); _PaintBO(pDC, rect, m_list->GetBuildOrderUnits(),30); } // paint foreground layer (axis lines + cursor) _PaintForegroundLayer(pDC, rect, resmax, MSK_XLINE); // restore every gdi stuff pDC->SelectObject(oldPen); pDC->SelectObject(oldFont); pDC->SetTextColor(oldClr); pDC->SetBkMode(oldMode); delete penCursor3; delete penCursor2; delete penCursor; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_ComputeHotkeySymbolRect(const ReplayEvtList *list, const HotKeyEvent *hkevt, CRect& datarect, CRect& symRect) { // compute symbol position int levelhk = (datarect.Height()-8-vplayer)/10; float finc = (float)(datarect.Width()-hleft-hright)/(float)(m_timeEnd - m_timeBegin); float fxc=(float)(datarect.left+hleft) + finc * (hkevt->m_time - m_timeBegin); int y = datarect.top+vplayer + hkevt->m_slot*levelhk; int wText = 10; symRect.SetRect((int)fxc-wText/2, y, (int)fxc+wText/2, y+levelhk); symRect.InflateRect(2,2); symRect.DeflateRect(0,(levelhk-wText)/2); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintHotKeyEvent(CDC *pDC, CRect& datarect, int offset) { char text[3]; CRect symRect; // draw hotkey events for(int i=0;i<(int)m_list->GetHKEventCount();i++) { // get event const HotKeyEvent *hkevt = m_list->GetHKEvent(i); if(hkevt->m_time < m_timeBegin || hkevt->m_time > m_timeEnd) continue; // view hotkey selection? if(!m_viewHKselect && hkevt->m_type==HotKeyEvent::SELECT) continue; // compute symbol position _ComputeHotkeySymbolRect(m_list, hkevt, datarect, symRect); // text size sprintf(text,"%d", hkevt->m_slot==9?0:hkevt->m_slot+1); // draw text CRect rectText; pDC->SetTextColor(hkevt->m_type!=HotKeyEvent::ASSIGN ? RGB(100,0,100):RGB(0,0,0)); if(hkevt->m_type==HotKeyEvent::ASSIGN) pDC->FillSolidRect(symRect,RGB(100,0,200)); else if(hkevt->m_type==HotKeyEvent::ADD) pDC->Draw3dRect(symRect,RGB(100,0,200),RGB(100,0,200)); pDC->DrawText(text,symRect,DT_CENTER|DT_SINGLELINE|DT_VCENTER); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintHotKeys(CDC *pDC, const CRect& rectc) { // select font & color CFont *oldFont = pDC->SelectObject(m_pLayerFont); int oldMode = pDC->GetBkMode(); int oldbkClr = pDC->GetBkColor(); // height of a key strip int levelhk = (rectc.Height()-8-vplayer)/10; // offset rect CRect rect(rectc); rect.left += m_dataAreaX; // draw X & Y axis values ReplayResource resmax; _PaintAxis(pDC, rect, resmax, MSK_XLINE,m_timeBegin,m_timeEnd); // draw hotkey numbers pDC->SetBkMode(TRANSPARENT); int oldclr = pDC->SetTextColor(RGB(0,0,0)); COLORREF clrkey=RGB(255,255,0); COLORREF clrkeydark=CHsvRgb::Darker(clrkey,0.50); for(int i=0;i<10;i++) { // compute symbol position int y = rect.top+vplayer + i*levelhk; // text size CString hkslot; hkslot.Format("%d",i==9?0:i+1); // compute key rect CRect rectText; int wkey = min (24,levelhk-4); int hkey = (85*levelhk)/100; int delta = (levelhk-hkey)/2; rectText.SetRect(rect.left+6-m_dataAreaX,y+delta,0,y+hkey+delta); rectText.right = rectText.left + wkey; while(rectText.Width()<4) rectText.InflateRect(1,1); // fill key rect COLORREF clr = m_list->IsHotKeyUsed(i) ? clrkey : clrkeydark; //pDC->FillSolidRect(rectText,clr); Gradient::Fill(pDC,rectText,clr,CHsvRgb::Darker(clr,0.70)); pDC->Draw3dRect(rectText,clr,CHsvRgb::Darker(clr,0.80)); // draw text pDC->DrawText(hkslot,rectText,DT_CENTER|DT_SINGLELINE|DT_VCENTER); } // draw hotkey events _PaintHotKeyEvent(pDC, rect,0); // paint foreground layer (axis lines + cursor) _PaintForegroundLayer(pDC, rect, resmax, MSK_XLINE); // restore rect rect.left -= m_dataAreaX; // restore every gdi stuff pDC->SetBkMode(oldMode); pDC->SetTextColor(oldclr); pDC->SetBkColor(oldbkClr); } //----------------------------------------------------------------------------------------------------------------- static int _gType; static ReplayEvtList* _gList; static int _gCompareElements( const void *arg1, const void *arg2 ) { int i1 = *((int*)arg1); int i2 = *((int*)arg2); return _gList->GetDistCount(_gType,i2)-_gList->GetDistCount(_gType,i1); } void DlgStats::_PaintDistribution(CDC *pDC, const CRect& rect, int type) { //empty distribution? if(m_list->GetDistTotal(type)==0) return; // select font & color CFont *oldFont = pDC->SelectObject(m_pLabelFont); COLORREF oldClr = pDC->SetTextColor(clrUnitName); COLORREF bkClr = pDC->GetBkColor(); // compute number of non null elements in the distribution int elemcount=m_list->GetDistNonNullCount(type); int dvalmax = m_seePercent ? 50 : m_replay.GetDistPeak(type); // skip elements with 0.0% count if(m_seePercent) { for(int i=0; i<m_list->GetDistMax(type); i++) { int dval = (100*m_list->GetDistCount(type,i))/m_list->GetDistTotal(type); if(dval>dvalmax) dvalmax=dval; if(m_list->GetDistCount(type,i)>0 && dval==0) elemcount--; } } // compute bar height CRect barRect = rect; barRect.top+=32; barRect.DeflateRect(hleft,0); int barHeight = elemcount==0 ? 0 : min(40,barRect.Height()/elemcount); // select adequate font pDC->SelectObject((barHeight<18) ? ((barHeight<10) ? m_pSmallFont : m_pLayerFont) : m_pLabelFont); int barStart = 150; //(barHeight<18) ? ((barHeight<10) ? 80 : 110) : 150; // create array of pointer to distribution elements int *elemIdx = new int[m_list->GetDistMax(type)]; int j=0; for(int i=0; i<m_list->GetDistMax(type); i++) { // skip elements with 0 count if(m_list->GetDistCount(type,i)==0) continue; // skip elements with 0.0% count if(m_seePercent && (100*m_list->GetDistCount(type,i))/m_list->GetDistTotal(type)==0) continue; elemIdx[j]=i; j++; } // sort array if(m_sortDist) { _gType=type; _gList=m_list; qsort(elemIdx,j,sizeof(int),_gCompareElements); } // for each element CString val; barRect.bottom = barRect.top + barHeight; int barSpacing = (15*barHeight)/100; //for(int i=0; i<m_list->GetDistMax(type); i++) for(int k=0; k<j; k++) { int i=elemIdx[k]; /* // skip elements with 0 count if(m_list->GetDistCount(type,i)==0) continue; // skip elements with 0.0% count if(m_seePercent && (100*m_list->GetDistCount(type,i))/m_list->GetDistTotal(type)==0) continue; */ // display element name //pDC->SetBkColor(RGB(0,0,0)); pDC->SetBkMode(TRANSPARENT); pDC->SetTextColor(clrUnitName); pDC->DrawText(m_list->GetDistName(type,i),barRect,DT_LEFT|DT_SINGLELINE|DT_VCENTER); // what value int dval = m_seePercent ? (100*m_list->GetDistCount(type,i))/m_list->GetDistTotal(type) : m_list->GetDistCount(type,i); // draw bar int barWidth = dval*(barRect.Width() - (barStart+42))/dvalmax; CRect zbar=barRect; zbar.DeflateRect(barStart,barSpacing,0,barSpacing); zbar.right =zbar.left+barWidth; COLORREF clr = m_list->GetDistColor(type,i); Gradient::Fill(pDC,&zbar,clr,CHsvRgb::Darker(clr,0.6),GRADIENT_FILL_RECT_V); //pDC->FillSolidRect(&zbar,clr); // draw value if(m_seePercent) { /* if(dval==0) { double fval = (100.0*m_list->GetDistCount(type,i))/m_list->GetDistTotal(type); val.Format("%.1f%%",fval); } else */ val.Format("%d%%",dval); } else val.Format("%d",dval); pDC->SetTextColor(clrUnitName); int oldMode=pDC->SetBkMode(TRANSPARENT); zbar.left=zbar.right+4; zbar.right+=42; pDC->DrawText(val,zbar,DT_LEFT|DT_SINGLELINE|DT_VCENTER); pDC->SetBkMode(oldMode); // next element barRect.OffsetRect(0,barHeight); } delete[]elemIdx; // restore every gdi stuff pDC->SelectObject(oldFont); pDC->SetTextColor(oldClr); pDC->SetBkColor(bkClr); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_GetDataRectForPlayer(int plidx, CRect& rect, int pcount) { assert(pcount>0); rect = m_boardRect; rect.bottom = rect.top+rect.Height()/pcount; rect.OffsetRect(0,rect.Height()*plidx); } //----------------------------------------------------------------------------------------------------------------- // paint one chart for one player void DlgStats::_PaintChart(CDC *pDC, int chartType, const CRect& rect, int minMargin) { //what kind of chart do we paint? hleft = max(minMargin,6); if(chartType==BUILDORDER) { // build order _PaintBuildOrder(pDC,rect); } else if(chartType==HOTKEYS) { // build hotkeys _PaintHotKeys(pDC,rect); } else if(chartType!=RESOURCES && chartType!=MAPCOVERAGE && chartType!=APM) { // any distribution _PaintDistribution(pDC,rect,chartType-2); } else { hleft = max(minMargin,30); // paint background layer _PaintBackgroundLayer(pDC, rect, m_list->ResourceMax()); // draw selected events & resources _PaintEvents(pDC, chartType, rect, m_list->ResourceMax()); // paint foreground layer _PaintForegroundLayer(pDC, rect, m_list->ResourceMax()); } // draw player name _PaintPlayerName(pDC, rect, m_list, -1, -1, clrPlayer); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintMultipleCharts(CDC *pDC) { m_rectMapName.SetRectEmpty(); // for each player on board CRect rect; m_shape = SQUARE; for(int i=0,j=0; i<m_replay.GetPlayerCount() && j<m_maxPlayerOnBoard; i++) { // get event list for that player m_list = m_replay.GetEvtList(i); if(!m_list->IsEnabled()) continue; // get rect for the player's charts _GetDataRectForPlayer(j, rect, m_maxPlayerOnBoard); // paint one chart for one player _PaintChart(pDC, m_chartType, rect); // offset shape for next player m_shape=(eSHAPE)((int)m_shape+1); j++; } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintMixedCharts(CDC *pDC, int playerIdx, int *chartType, int count) { m_rectMapName.SetRectEmpty(); // for required chart CRect rect; m_shape = SQUARE; m_mixedCount=count; m_MixedPlayerIdx=playerIdx; for(int i=0; i<count; i++) { // get event list for that player m_list = m_replay.GetEvtList(playerIdx); // get rect for the chart _GetDataRectForPlayer(i, rect, count); // paint one chart int ctype = m_chartType; m_chartType = chartType[i]; _PaintChart(pDC, chartType[i], rect, 35); m_mixedRect[i]=rect; m_mixedChartType[i]=m_chartType; m_chartType=ctype; } } //----------------------------------------------------------------------------------------------------------------- // get index of first enabled player int DlgStats::_GetFirstEnabledPlayer() const { // for each player on board for(int i=0; i<m_replay.GetPlayerCount(); i++) if(m_replay.GetEvtList(i)->IsEnabled()) return i; return 0; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintSingleChart(CDC *pDC) { CRect rect = m_boardRect; hleft = 30; // paint background layer _PaintBackgroundLayer(pDC, rect, m_replay.ResourceMax()); // for each player on board m_shape = SQUARE; for(int i=0,j=0; j<m_maxPlayerOnBoard; i++) { // get event list for that player m_list = m_replay.GetEvtList(i); if(!m_list->IsEnabled()) continue; // draw selected events & resources _PaintEvents(pDC, m_chartType, rect, m_replay.ResourceMax(),i); m_shape=(eSHAPE)((int)m_shape+1); j++; } // paint foreground layer _PaintForegroundLayer(pDC, rect, m_replay.ResourceMax()); // paint map name _PaintMapName(pDC,rect); int offv = vplayer-8; // draw players name for(int i=0,j=0; j<m_maxPlayerOnBoard; i++) { // get event list for that player ReplayEvtList* list = m_replay.GetEvtList(i); if(!list->IsEnabled()) continue; _PaintPlayerName(pDC, rect, list, i,j, clrPlayer,offv); j++; } // paint sentinel logo if needed rect.SetRect(rect.left+hplayer+220,rect.top,rect.left+hplayer+280,rect.top+28); _PaintSentinel(pDC, rect); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintCheckBoxColor(CDC *pDC) { UINT cid[]={IDC_MINERALS,IDC_GAZ,IDC_SUPPLY,IDC_UNITS}; for(int i=0;i<sizeof(cid)/sizeof(cid[0]);i++) { CRect rect; GetDlgItem(cid[i])->GetWindowRect(&rect); ScreenToClient(&rect); rect.OffsetRect(-8,0); rect.DeflateRect(0,2); rect.right = rect.left+6; rect.top--; pDC->FillSolidRect(&rect,_GetDrawingTools(0)->m_clr[i]); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintCharts(CDC *pDC) { m_maxPlayerOnBoard = min(MAXPLAYERONVIEW,m_replay.GetEnabledPlayerCount()); if(m_maxPlayerOnBoard>0) { if(m_chartType==MIX_APMHOTKEYS) { int ctype[]={APM,HOTKEYS}; _PaintMixedCharts(pDC,_GetFirstEnabledPlayer(),ctype,sizeof(ctype)/sizeof(ctype[0])); } else if(!m_singleChart[m_chartType] || (m_chartType!=RESOURCES && m_chartType!=APM && m_chartType!=MAPCOVERAGE)) _PaintMultipleCharts(pDC); else _PaintSingleChart(pDC); _PaintCheckBoxColor(pDC); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_SelectAction(int idx) { // update selected player char szPlayerName[128]; m_listEvents.GetItemText(idx,1,szPlayerName,sizeof(szPlayerName)); for(int i=0; i<m_replay.GetPlayerCount(); i++) if(_stricmp(m_replay.GetEvtList(i)->PlayerName(),szPlayerName)==0) {m_selectedPlayer = i; break;} // update current cursor pos ReplayEvt *evt = _GetEventFromIdx(idx); _SetTimeCursor(evt->Time(),false); // suspect event? GetDlgItem(IDC_SUSPECT_INFO)->SetWindowText(""); if(evt->IsSuspect()) { CString origin; ReplayEvtList *list = (ReplayEvtList *)evt->GetAction()->GetUserData(0); list->GetSuspectEventOrigin(evt->GetAction(),origin,m_useSeconds?true:false); GetDlgItem(IDC_SUSPECT_INFO)->SetWindowText(origin); } // remember selected action index m_selectedAction = idx; } //--------------------------------------------------------------------------------------- void DlgStats::OnItemchangedListevents(NMHDR* pNMHDR, LRESULT* pResult) { NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR; if(pNMListView->uNewState&(LVIS_SELECTED+LVIS_FOCUSED) && !m_lockListView && (pNMListView->iItem!=-1)) { // update selected player & cursor pos _SelectAction(pNMListView->iItem); } *pResult = 0; } //--------------------------------------------------------------------------------------- inline unsigned long DlgStats::_GetActionCount() { return m_replay.GetEnActionCount();//(unsigned long)m_replay.QueryFile()->QueryActions()->GetActionCount(); } //--------------------------------------------------------------------------------------- ReplayEvt * DlgStats::_GetEventFromIdx(unsigned long idx) { assert(idx<_GetActionCount()); const IStarcraftAction *action = m_replay.GetEnAction(idx); //m_replay.QueryFile()->QueryActions()->GetAction(idx); ReplayEvtList *list = (ReplayEvtList *)action->GetUserData(0); ReplayEvt *evt = list->GetEvent(action->GetUserData(1)); return evt; } //--------------------------------------------------------------------------------------- // cursor = value between 0 and full span time // will find the nearest event unsigned long DlgStats::_GetEventFromTime(unsigned long cursor) { unsigned long eventCount = _GetActionCount(); if(eventCount==0) return 0; unsigned long nSlot = 0; unsigned long low = 0; unsigned long high = eventCount - 1; unsigned long beginTimeTS = 0; unsigned long i; unsigned long eventTime; // for all events in the list while(true) { i= (high+low)/2; ASSERT(high>=low); // are we beyond the arrays boundaries? if(i>=eventCount) {nSlot=0;break;} // get event time ReplayEvt *evt = _GetEventFromIdx(i); eventTime = evt->Time(); // compare times LONGLONG delta = eventTime-beginTimeTS; LONGLONG nCmp = (LONGLONG )cursor - delta; // if event time is the same, return index if(nCmp==0) { nSlot = i; goto Exit; } else if(nCmp<0) { if(high==low) {nSlot = low; break;} high = i-1; if(high<low) {nSlot=low; break;} if(high<0) {nSlot=0; break;} } else { if(high==low) {nSlot = low+1; break;} low = i+1; if(low>high) {nSlot=high; break;} if(low>=eventCount-1) {nSlot=eventCount-1; break;} } } ASSERT(nSlot<eventCount); Exit: // make sure event belong to the right player char szPlayerName[128]; int nSlotBegin=nSlot; for(;nSlot<eventCount;) { // get event time ReplayEvt *evt = _GetEventFromIdx(nSlot); assert(evt!=0); if(evt->Time()>cursor) break; m_listEvents.GetItemText(nSlot,1,szPlayerName,sizeof(szPlayerName)); if(strcmp(m_replay.GetEvtList(m_selectedPlayer)->PlayerName(),szPlayerName)!=0) nSlot++; else break; } if(nSlot>=eventCount) nSlot=nSlotBegin; else { ReplayEvt *evt = _GetEventFromIdx(nSlot); if(evt->Time()>cursor) nSlot=nSlotBegin; } return nSlot; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_AdjustWindow() { unsigned long windowWidth = (unsigned long)((double)m_replay.GetEndTime()/pow(2.0f,m_zoom)); if(m_timeCursor<windowWidth/2) { m_timeBegin = 0; m_timeEnd = windowWidth; } else if(m_timeCursor+windowWidth/2>m_replay.GetEndTime()) { m_timeBegin = m_replay.GetEndTime()-windowWidth; m_timeEnd = m_replay.GetEndTime(); } else { m_timeBegin = m_timeCursor-windowWidth/2; m_timeEnd = m_timeCursor+windowWidth/2; } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnSelchangeZoom() { UpdateData(TRUE); if(m_zoom==0) { m_timeBegin = 0; m_timeEnd = m_replay.GetEndTime(); } else { _AdjustWindow(); } Invalidate(FALSE); } //-------------------------------------------------------------------------------- BOOL DlgStats::_OnScroll(UINT nScrollCode, UINT nPos, BOOL bDoScroll) { // calc new x position int x = m_scroller.GetScrollPos(); int xOrig = x; switch (LOBYTE(nScrollCode)) { case SB_TOP: x = 0; break; case SB_BOTTOM: x = INT_MAX; break; case SB_LINEUP: x -= m_lineDev.cx; break; case SB_LINEDOWN: x += m_lineDev.cx; break; case SB_PAGEUP: x -= m_pageDev.cx; break; case SB_PAGEDOWN: x += m_pageDev.cx; break; case SB_THUMBTRACK: x = nPos; break; } // calc new y position int y = m_scrollerV.GetScrollPos(); int yOrig = y; switch (HIBYTE(nScrollCode)) { case SB_TOP: y = 0; break; case SB_BOTTOM: y = INT_MAX; break; case SB_LINEUP: y -= m_lineDev.cy; break; case SB_LINEDOWN: y += m_lineDev.cy; break; case SB_PAGEUP: y -= m_pageDev.cy; break; case SB_PAGEDOWN: y += m_pageDev.cy; break; case SB_THUMBTRACK: y = nPos; break; } BOOL bResult = _OnScrollBy(CSize(x - xOrig, y - yOrig), bDoScroll); /* if (bResult && bDoScroll) { Invalidate(); UpdateWindow(); } */ return bResult; } //------------------------------------------------------------------------------------------ BOOL DlgStats::_OnScrollBy(CSize sizeScroll, BOOL bDoScroll) { int xOrig, x; int yOrig, y; // don't scroll if there is no valid scroll range (ie. no scroll bar) CScrollBar* pBar; DWORD dwStyle = GetStyle(); pBar = &m_scrollerV; if ((pBar != NULL && !pBar->IsWindowEnabled()) || (pBar == NULL && !(dwStyle & WS_VSCROLL))) { // vertical scroll bar not enabled sizeScroll.cy = 0; } pBar = &m_scroller; if ((pBar != NULL && !pBar->IsWindowEnabled()) || (pBar == NULL && !(dwStyle & WS_HSCROLL))) { // horizontal scroll bar not enabled sizeScroll.cx = 0; } // adjust current x position xOrig = x = m_scroller.GetScrollPos(); //int xMax = GetScrollLimit(SB_HORZ); int xMax, xMin ; m_scroller.GetScrollRange(&xMin,&xMax) ; x += sizeScroll.cx; if (x < xMin) x = xMin; else if (x > xMax) x = xMax; // adjust current y position yOrig = y = m_scrollerV.GetScrollPos(); //int yMax = GetScrollLimit(SB_VERT); int yMax, yMin ; m_scrollerV.GetScrollRange(&yMin,&yMax) ; y += sizeScroll.cy; if (y < 0) y = 0; else if (y > yMax) y = yMax; // did anything change? if (x == xOrig && y == yOrig) return FALSE; if (bDoScroll) { // do scroll and update scroll positions if (x != xOrig) { _SetTimeCursor(x*HSCROLL_DIVIDER); } if (y != yOrig) { m_scrollerV.SetScrollPos(y); //??????????? } } return TRUE; } //--------------------------------------------------------------------------------------- void DlgStats::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { _OnScroll(MAKEWORD(nSBCode, -1), nPos, TRUE); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnUpdateChart() { BOOL oldUseSeconds = m_useSeconds; UpdateData(TRUE); InvalidateRect(&m_boardRect,FALSE); if(oldUseSeconds != m_useSeconds) m_listEvents.Invalidate(); } //------------------------------------------------------------------------------------- void DlgStats::_UpdateActionFilter(bool refresh) { // compute filter int filter=0; if(m_fltSelect) filter+=Replay::FLT_SELECT; if(m_fltBuild) filter+=Replay::FLT_BUILD; if(m_fltTrain) filter+=Replay::FLT_TRAIN; if(m_fltSuspect) filter+=Replay::FLT_SUSPECT; if(m_fltHack) filter+=Replay::FLT_HACK; if(m_fltOthers) filter+=Replay::FLT_OTHERS; if(m_fltChat) filter+=Replay::FLT_CHAT; m_replay.UpdateFilter(filter); // update list view if(refresh) { m_listEvents.SetItemCountEx(m_replay.GetEnActionCount(), LVSICF_NOSCROLL|LVSICF_NOINVALIDATEALL); m_listEvents.Invalidate(); } } //------------------------------------------------------------------------------------- void DlgStats::_ToggleIgnorePlayer() { POSITION pos = m_plStats.GetFirstSelectedItemPosition(); if(pos!=0) { // get selected item int nItem = m_plStats.GetNextSelectedItem(pos); ReplayEvtList *list = (ReplayEvtList *)m_plStats.GetItemData(nItem); if(list!=0) { // enable/disable player m_replay.EnablePlayer(list,list->IsEnabled()?false:true); LVITEM item = {LVIF_IMAGE ,nItem,0,0,0,0,0,list->IsEnabled()?1:0,0,0}; m_plStats.SetItem(&item); // update list view int nItem=-1; m_listEvents.SetItemCountEx(m_replay.GetEnActionCount(), LVSICF_NOSCROLL|LVSICF_NOINVALIDATEALL); m_listEvents.Invalidate(); /* POSITION pos = m_listEvents.GetFirstSelectedItemPosition(); if (pos != NULL) nItem = pList->GetNextSelectedItem(pos); //if(nItem>=m_replay.GetEnActionCount()) m_listEvents.SnItem=m_replay.GetEnActionCount()-1; */ //repaint InvalidateRect(m_boardRect,TRUE); // update map m_dlgmap->UpdateReplay(&m_replay); } } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnEnableDisable() { _ToggleIgnorePlayer(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnDblclkPlstats(NMHDR* pNMHDR, LRESULT* pResult) { _ToggleIgnorePlayer(); *pResult = 0; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnDestroy() { // if we are on pause, unpause if(m_prevAnimationSpeed!=0) OnPause(); // save parameters _Parameters(false); DlgBrowser::SaveColumns(&m_plStats,"plstats"); CDialog::OnDestroy(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnSelchangeCharttype() { static bool gbTimeWndHasChanged = false; OnUpdateChart(); // update shared "single chart" checkbox CButton *btn = (CButton *)GetDlgItem(IDC_SINGLECHART); btn->SetCheck(m_singleChart[m_chartType]); btn->EnableWindow((m_chartType==RESOURCES || m_chartType==APM || m_chartType==MAPCOVERAGE)?TRUE:FALSE); // update shared "see units" checkbox btn = (CButton *)GetDlgItem(IDC_UNITS); btn->SetCheck(m_seeUnits[m_chartType]); btn->EnableWindow((m_chartType==RESOURCES || m_chartType==MAPCOVERAGE)?TRUE:FALSE); // update shared "apm style" combo box CComboBox *cbx = (CComboBox *)GetDlgItem(IDC_APMSTYLE); cbx->SetCurSel(m_apmStyle[m_chartType]); cbx->EnableWindow((m_chartType==APM || m_chartType==MAPCOVERAGE)?TRUE:FALSE); m_dataAreaX = 0; m_mixedCount=0; m_MixedPlayerIdx=0; // shall we restore the full timeline? if(gbTimeWndHasChanged) { m_timeBegin = 0; m_timeEnd = m_replay.GetEndTime(); gbTimeWndHasChanged = false; m_zoom=0; UpdateData(FALSE); } switch(m_chartType) { case MAPCOVERAGE: { // disable useless options UINT disable[]={IDC_ANIMATE,IDC_PERCENTAGE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY, IDC_SORTDIST, IDC_SPEED,IDC_BPM,IDC_UPM,IDC_ACTIONS,IDC_HOTPOINTS,IDC_UNITSONBO,IDC_HKSELECT}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); // enable useful options UINT enable[]={IDC_USESECONDS,IDC_ZOOM,IDC_UNITS,IDC_APMSTYLE}; for(int i=0;i<sizeof(enable)/sizeof(enable[0]);i++) GetDlgItem(enable[i])->EnableWindow(TRUE); } break; case MIX_APMHOTKEYS: { m_dataAreaX = 0; // disable useless options UINT disable[]={IDC_PERCENTAGE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY, IDC_SORTDIST,IDC_UNITS, IDC_ACTIONS,IDC_HOTPOINTS,IDC_UNITSONBO,IDC_APMSTYLE}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); // enable useful options UINT enable[]={IDC_USESECONDS,IDC_ZOOM,IDC_HKSELECT,IDC_ANIMATE,IDC_SPEED,IDC_BPM,IDC_UPM,IDC_APMSTYLE}; for(int i=0;i<sizeof(enable)/sizeof(enable[0]);i++) GetDlgItem(enable[i])->EnableWindow(TRUE); } break; case HOTKEYS: { m_dataAreaX = 32; // disable useless options UINT disable[]={IDC_ANIMATE,IDC_PERCENTAGE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY, IDC_SORTDIST, IDC_SPEED,IDC_BPM,IDC_UPM,IDC_UNITS,IDC_ACTIONS,IDC_HOTPOINTS,IDC_UNITSONBO,IDC_APMSTYLE}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); // enable useful options UINT enable[]={IDC_USESECONDS,IDC_ZOOM,IDC_HKSELECT}; for(int i=0;i<sizeof(enable)/sizeof(enable[0]);i++) GetDlgItem(enable[i])->EnableWindow(TRUE); } break; case BUILDORDER: { // build order m_timeBegin = 0; m_timeEnd = m_replay.GetLastBuildOrderTime(); gbTimeWndHasChanged = true; // enable useful options GetDlgItem(IDC_UNITSONBO)->EnableWindow(TRUE); GetDlgItem(IDC_USESECONDS)->EnableWindow(TRUE); // disable useless options UINT disable[]={IDC_ZOOM,IDC_ANIMATE,IDC_PERCENTAGE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY, IDC_SORTDIST, IDC_SPEED,IDC_BPM,IDC_UPM,IDC_UNITS,IDC_ACTIONS,IDC_HOTPOINTS,IDC_HKSELECT,IDC_APMSTYLE}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); } break; case RESOURCES: { // disable useless options UINT disable[]={IDC_SPEED,IDC_BPM,IDC_UPM, IDC_HKSELECT,IDC_APMSTYLE,IDC_SORTDIST,IDC_PERCENTAGE,IDC_UNITSONBO}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); // enable useful options UINT enable[]={IDC_ZOOM,IDC_ANIMATE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY, IDC_UNITS,IDC_USESECONDS,IDC_ACTIONS,IDC_HOTPOINTS}; for(int i=0;i<sizeof(enable)/sizeof(enable[0]);i++) GetDlgItem(enable[i])->EnableWindow(TRUE); } break; case APM: { // disable useless options UINT disable[]={IDC_MINERALS,IDC_GAZ,IDC_SUPPLY,IDC_UNITS,IDC_ACTIONS, IDC_HKSELECT,IDC_SORTDIST,IDC_PERCENTAGE,IDC_UNITSONBO}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); // enable useful options UINT enable[]={IDC_ZOOM,IDC_ANIMATE,IDC_SPEED,IDC_BPM,IDC_UPM,IDC_USESECONDS,IDC_APMSTYLE}; for(int i=0;i<sizeof(enable)/sizeof(enable[0]);i++) GetDlgItem(enable[i])->EnableWindow(TRUE); } break; default: { // any distribution GetDlgItem(IDC_PERCENTAGE)->EnableWindow(TRUE); GetDlgItem(IDC_SORTDIST)->EnableWindow(TRUE); // disable useless options UINT disable[]={IDC_ZOOM,IDC_ANIMATE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY,IDC_UNITSONBO, IDC_SPEED,IDC_BPM,IDC_UPM,IDC_UNITS,IDC_ACTIONS,IDC_HOTPOINTS,IDC_HKSELECT,IDC_APMSTYLE}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); } break; } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnHelp() { DlgHelp dlg; dlg.DoModal(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_BrowseReplays(const char *dir, int& count, int &idx, bool bCount) { CFileFind finder; char mask[255]; strcpy(mask,dir); if(mask[strlen(mask)-1]!='\\') strcat(mask,"\\"); strcat(mask,"*.*"); // load all replays BOOL bWorking = finder.FindFile(mask); while (bWorking) { // find next package bWorking = finder.FindNextFile(); //dir? if(finder.IsDirectory()) { // . & .. if(finder.IsDots()) continue; // recurse char subdir[255]; strcpy(subdir,dir); if(subdir[strlen(subdir)-1]!='\\') strcat(subdir,"\\"); strcat(subdir,finder.GetFileName()); _BrowseReplays(subdir, count, idx, bCount); continue; } // rep file? CString ext; ext=finder.GetFileName().Right(4); if(ext.CompareNoCase(".rep")!=0) continue; if(bCount) { count++; } else { // load it if(m_replay.Load(finder.GetFilePath(),false,0,true)!=0) { CString msg; msg.Format(IDS_CANTLOAD,(const char*)finder.GetFilePath()); MessageBox(msg); } idx++; // update progress bar m_progress.SetPos((100*idx)/count); } } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnTestreplays() { m_progress.ShowWindow(SW_SHOW); // count available replays int count=0; int idx=0; _BrowseReplays("e:\\program files\\starcraft\\maps\\", count, idx, true); // laod them _BrowseReplays("e:\\program files\\starcraft\\maps\\", count, idx, false); m_replay.Clear(); m_progress.ShowWindow(SW_HIDE); } //----------------------------------------------------------------------------------------------------------------- static bool gbAscendingAction=true; int CALLBACK CompareAction(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) { int diff=0; const ReplayEvt *evt1 = (const ReplayEvt *)lParam1; const ReplayEvt *evt2 = (const ReplayEvt *)lParam2; unsigned long rep1 = evt1->Time(); unsigned long rep2 = evt2->Time(); switch(lParamSort) { case 0: diff = rep1 - rep2; break; default: assert(0); break; } return gbAscendingAction ? diff : -diff; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnAddevent() { // get path CString path; if(!_GetReplayFileName(path)) return; // add events from that replay LoadReplay(path,false); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnRclickPlstats(NMHDR* pNMHDR, LRESULT* pResult) { CPoint pt; GetCursorPos(&pt); // select only one player for(int i=0;i<m_plStats.GetItemCount();i++) m_plStats.SetItemState(i,0, LVIS_SELECTED+LVIS_FOCUSED); // find corresponding item m_plStats.ScreenToClient(&pt); UINT uFlags; int nItem = m_plStats.HitTest(pt,&uFlags); if(nItem!=-1 && (uFlags & LVHT_ONITEMLABEL)!=0) { // select item m_selectedPlayerList = (ReplayEvtList *)m_plStats.GetItemData(nItem); m_plStats.SetItemState(nItem,LVIS_SELECTED+LVIS_FOCUSED, LVIS_SELECTED+LVIS_FOCUSED); // load menu CMenu menu; menu.LoadMenu(IDR_POPUPPLAYER); CMenu *pSub = menu.GetSubMenu(0); // display popup menu m_plStats.ClientToScreen(&pt); pSub->TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON, pt.x, pt.y, this); } *pResult = 0; } //---------------------------------------------------------------------------------------- void DlgStats::OnRemovePlayer() { if(m_selectedPlayerList!=0) { // remove player events m_replay.RemovePlayer(m_selectedPlayerList,&m_listEvents); m_selectedPlayer=0; // update player stats list _DisplayPlayerStats(); //repaint Invalidate(TRUE); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnSeemap() { m_dlgmap->ShowWindow(SW_SHOW); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::StopAnimation() { if(m_bIsAnimating) OnAnimate(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_UpdateAnimSpeed() { CString str; if(m_bIsAnimating) str.Format("(x%d)",m_animationSpeed); SetDlgItemText(IDC_ANIMSPEED,str); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_ToggleAnimateButtons(bool enable) { CString str; str.LoadString(enable ? IDS_ANIMATE:IDS_STOP); SetDlgItemText(IDC_ANIMATE,str); GetDlgItem(IDC_SPEEDPLUS)->EnableWindow(enable ? FALSE : TRUE); GetDlgItem(IDC_SPEEDMINUS)->EnableWindow(enable ? FALSE : TRUE); GetDlgItem(IDC_PAUSE)->EnableWindow(enable ? FALSE : TRUE); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnAnimate() { if(m_bIsAnimating) { // if we are on pause, unpause if(m_prevAnimationSpeed!=0) OnPause(); //stopping KillTimer(m_timer); m_bIsAnimating=false; _ToggleAnimateButtons(true); GetDlgItem(IDC_ZOOM)->EnableWindow(TRUE); GetDlgItem(IDC_CHARTTYPE)->EnableWindow(TRUE); // tell map m_dlgmap->Animate(false); // repaint Invalidate(); } else if(m_replay.IsDone()) { // starting m_timeBegin = 0; m_timeEnd = m_replay.GetEndTime(); //m_timeCursor = 0; m_zoom=0; UpdateData(FALSE); _ToggleAnimateButtons(false); GetDlgItem(IDC_ZOOM)->EnableWindow(FALSE); GetDlgItem(IDC_CHARTTYPE)->EnableWindow(FALSE); m_bIsAnimating=true; _UpdateAnimSpeed(); InvalidateRect(m_boardRect,TRUE); UpdateWindow(); // show animated map m_dlgmap->Animate(true); m_dlgmap->ShowWindow(SW_SHOW); // start timer m_timer = SetTimer(1,1000/TIMERSPEED,0); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnTimer(UINT nIDEvent) { // compute next position unsigned long newpos = m_timeCursor+m_replay.QueryFile()->QueryHeader()->Sec2Tick(m_animationSpeed)/TIMERSPEED; // if we reach the end, stop animation if(newpos>m_timeEnd) OnAnimate(); // udpate cursor if(m_animationSpeed>0) _SetTimeCursor(newpos, true,false); // update map if(m_dlgmap->IsWindowVisible()) m_dlgmap->UpdateTime(newpos); CDialog::OnTimer(nIDEvent); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnPause() { if(m_prevAnimationSpeed==0) { m_prevAnimationSpeed = m_animationSpeed; m_animationSpeed = 0; } else { m_animationSpeed = m_prevAnimationSpeed; m_prevAnimationSpeed = 0; } } void DlgStats::OnSpeedminus() { if(m_animationSpeed>1) m_animationSpeed/=2; _UpdateAnimSpeed(); } void DlgStats::OnSpeedplus() { if(m_animationSpeed<32) m_animationSpeed*=2; _UpdateAnimSpeed(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnGetdispinfoListevents(NMHDR* pNMHDR, LRESULT* pResult) { LV_DISPINFO* pDispInfo = (LV_DISPINFO*)pNMHDR; LV_ITEM* pItem= &(pDispInfo)->item; int iItemIndx= pItem->iItem; if (pItem->mask & LVIF_TEXT) //valid text buffer? { // get action const IStarcraftAction *action = m_replay.GetEnAction(iItemIndx);//m_replay.QueryFile()->QueryActions()->GetAction(iItemIndx); assert(action!=0); // get corresponding actionlist ReplayEvtList *list = (ReplayEvtList *)action->GetUserData(0); assert(list!=0); // get event description ReplayEvt *evt = list->GetEvent(action->GetUserData(1)); assert(evt!=0); // display value switch(pItem->iSubItem) { case 0: //time strcpy(pItem->pszText,_MkTime(m_replay.QueryFile()->QueryHeader(),evt->Time(),m_useSeconds?true:false)); break; case 1: //player if(evt->IsSuspect() || evt->IsHack()) sprintf(pItem->pszText,"#FF0000%s",list->PlayerName()); else strcpy(pItem->pszText,list->PlayerName()); break; case 2: //action //assert(evt->Time()!=37925); if(OPTIONSCHART->m_coloredevents) sprintf(pItem->pszText,"%s%s",evt->strTypeColor(),evt->strType()); else sprintf(pItem->pszText,"%s",evt->strType()); break; case 3: //parameters strcpy(pItem->pszText,action->GetParameters(list->GetElemList())); break; case 4: //discard & suspect flag strcpy(pItem->pszText,evt->IsDiscarded()?"*":evt->IsSuspect()?"#FF0000?":evt->IsHack()?"#FF0000!":""); break; case 5: // units ID strcpy(pItem->pszText,action->GetUnitsID(list->GetElemList())); break; default: assert(0); break; } assert(pItem->cchTextMax>(int)strlen(pItem->pszText)); } if(pItem->mask & LVIF_IMAGE) //valid image? pItem->iImage=0; *pResult = 0; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_GetResizeRect(CRect& resizeRect) { GetClientRect(&resizeRect); resizeRect.top = resizeRect.bottom - m_hlist - 8 - 6; resizeRect.bottom =resizeRect.top+6; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_GetHorizResizeRect(CRect& resizeRect) { GetClientRect(&resizeRect); resizeRect.top = resizeRect.bottom - m_hlist - 8 - 6; resizeRect.left = m_boardRect.left+ m_wlist; resizeRect.right = m_boardRect.left+m_wlist+8; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnLButtonDown(UINT nFlags, CPoint point) { // get tracking rect for resizing CRect resizeRect; _GetResizeRect(resizeRect); CRect horizResizeRect; _GetHorizResizeRect(horizResizeRect); // clicking on the resize part? if(resizeRect.PtInRect(point)) { m_resizing=VERTICAL_RESIZE; SetCapture(); m_ystart = point.y; } // clicking on the horizontal resize part? else if(horizResizeRect.PtInRect(point)) { m_resizing=HORIZONTAL_RESIZE; SetCapture(); m_xstart = point.x; } // clicking on map name? else if(m_rectMapName.PtInRect(point)) { OnSeemap(); } else { CRect rect = m_boardRect; rect.left+=hleft+m_dataAreaX; rect.right-=hright; // clicking on the graphics? if(rect.PtInRect(point) && m_maxPlayerOnBoard>0 && (m_chartType==APM || m_chartType==RESOURCES || m_chartType==BUILDORDER || m_chartType==MAPCOVERAGE || m_chartType==HOTKEYS || m_chartType>=MIX_APMHOTKEYS)) { // what player? if(!m_singleChart[m_chartType]) m_selectedPlayer = (point.y-m_boardRect.top) / (m_boardRect.Height() / m_maxPlayerOnBoard); // change time cursor float fx = (float)(point.x-rect.left); float finc = (float)(rect.Width())/(float)(m_timeEnd - m_timeBegin); _SetTimeCursor(m_timeBegin + (unsigned long)(fx/finc)); } } CDialog::OnLButtonDown(nFlags, point); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnLButtonUp(UINT nFlags, CPoint point) { if(m_resizing!=NONE) { // release capture ReleaseCapture(); // compute new layout if(m_resizing==VERTICAL_RESIZE) { int newhlist = m_hlist + (m_ystart-point.y); m_hlist = newhlist; } else { int newwlist = m_wlist + (point.x-m_xstart); m_wlist = newwlist; } // resize CRect rect; GetClientRect(&rect); _Resize(rect.Width(),rect.Height()); // end resizing m_resizing=NONE; } CDialog::OnLButtonUp(nFlags, point); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_GetHotKeyDesc(ReplayEvtList *list, int slot, CString& info) { info=""; // browse hotkey events for(int i=0;i<(int)list->GetHKEventCount();i++) { // get event const HotKeyEvent *hkevt = list->GetHKEvent(i); // skip events for other slots if(hkevt->m_slot!=slot) continue; // skip hotkey selection if(hkevt->m_type==HotKeyEvent::SELECT) continue; // new line if(!info.IsEmpty()) info+="\r\n"; // build unit list as string char buffer[64]; strcpy(buffer,_MkTime(m_replay.QueryFile()->QueryHeader(),hkevt->m_time,m_useSeconds?true:false)); info+=buffer+CString(" => "); const HotKey * hk = hkevt->GetHotKey(); for(int uidx=0;uidx<hk->m_unitcount;uidx++) { if(uidx>0) info+=", "; m_replay.QueryFile()->QueryHeader()->MkUnitID2String(buffer, hk->m_hotkeyUnits[uidx], list->GetElemList(), hkevt->m_time); info += buffer; } } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_CheckForHotKey(ReplayEvtList *list, CPoint& point, CRect& datarect, int delta) { CRect symRect; // check hotkey numbers if(point.x < datarect.left+m_dataAreaX+delta) { // height of a key strip int levelhk = (datarect.Height()-8-vplayer)/10; // check all keys for(int i=0;i<10;i++) { // compute symbol position int y = datarect.top+vplayer + i*levelhk; CRect rectkey(datarect.left+6,y,datarect.left+6+m_dataAreaX+delta,y+levelhk); if(rectkey.PtInRect(point)) { // build description CString info; _GetHotKeyDesc(list, i, info); // update overlay window m_over->SetText(info,this,point); return; } } } // check hotkey events datarect.left+=m_dataAreaX; for(int i=0;i<(int)list->GetHKEventCount();i++) { // get event const HotKeyEvent *hkevt = list->GetHKEvent(i); if(hkevt->m_time < m_timeBegin || hkevt->m_time > m_timeEnd) continue; // view hotkey selection? if(!m_viewHKselect && hkevt->m_type==HotKeyEvent::SELECT) continue; // compute symbol position _ComputeHotkeySymbolRect(list, hkevt, datarect, symRect); // is mouse over this event? const HotKey * hk = hkevt->GetHotKey(); if(symRect.PtInRect(point) && hk!=0) { // build unit list as string CString info; char buffer[64]; for(int uidx=0;uidx<hk->m_unitcount;uidx++) { if(!info.IsEmpty()) info+="\r\n"; m_replay.QueryFile()->QueryHeader()->MkUnitID2String(buffer, hk->m_hotkeyUnits[uidx], list->GetElemList(), hkevt->m_time); info += buffer; } // update overlay window m_over->SetText(info,this,point); return; } } m_over->Show(false); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnMouseMove(UINT nFlags, CPoint point) { if(m_resizing!=NONE) { m_over->Show(false); //int newhlist = m_hlist + (m_ystart-point.y); //CRect resizeRect = m_boardRect; //resizeRect.top =newhlist; //resizeRect.bottom =newhlist+2; //DrawTrackRect( } else if(m_chartType==HOTKEYS) { // for each player on board CRect rect; for(int i=0,j=0; i<m_replay.GetPlayerCount() && j<m_maxPlayerOnBoard; i++) { // get event list for that player ReplayEvtList *list = m_replay.GetEvtList(i); if(!list->IsEnabled()) continue; // get rect for the player's charts _GetDataRectForPlayer(j++, rect, m_maxPlayerOnBoard); // is mouse in that rect? if(rect.PtInRect(point)) { // check if mouse is over a hotkey symbol _CheckForHotKey(list,point, rect); return; } } m_over->Show(false); } else if(m_chartType==MIX_APMHOTKEYS) { if(m_MixedPlayerIdx<m_replay.GetPlayerCount() && m_mixedCount>0) { // get event list for current player ReplayEvtList *list = m_replay.GetEvtList(m_MixedPlayerIdx); // get rect for the player's charts CRect rect; _GetDataRectForPlayer(1, rect, m_mixedCount); // is mouse in that rect? if(rect.PtInRect(point)) { // check if mouse is over a hotkey symbol _CheckForHotKey(list,point, rect, 32); return; } } m_over->Show(false); } CDialog::OnMouseMove(nFlags, point); } //----------------------------------------------------------------------------------------------------------------- BOOL DlgStats::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { // get tracking rect for vertical resizing CRect resizeRect; _GetResizeRect(resizeRect); // get tracking rect for horizontal resizing CRect horizResizeRect; _GetHorizResizeRect(horizResizeRect); // mouse over the resize part? CPoint point; GetCursorPos(&point); ScreenToClient(&point); if(resizeRect.PtInRect(point)) { // top/bottom resize ::SetCursor(::LoadCursor(0,IDC_SIZENS)); return TRUE; } else if(horizResizeRect.PtInRect(point)) { // left/right resize ::SetCursor(::LoadCursor(0,IDC_SIZEWE)); return TRUE; } else if(m_rectMapName.PtInRect(point)) { // map name ::SetCursor(AfxGetApp()->LoadStandardCursor(MAKEINTRESOURCE(32649))); return TRUE; } return CDialog::OnSetCursor(pWnd, nHitTest, message); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnRButtonDown(UINT nFlags, CPoint point) { if(!m_replay.IsDone()) return; CPoint pt; GetCursorPos(&pt); // load menu CMenu menu; menu.LoadMenu(IDR_WATCHREP); CMenu *pSub = menu.GetSubMenu(0); // display popup menu pSub->TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON, pt.x, pt.y, this); CDialog::OnRButtonDown(nFlags, point); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::_StartCurrentReplay(int mode) { CFileFind finder; BOOL bWorking = finder.FindFile(m_replay.GetFileName()); if(bWorking) { // get replay file info finder.FindNextFile(); // get replay info object from replay ReplayInfo *rep = MAINWND->pGetBrowser()->_ProcessReplay(finder.GetRoot(),finder); if(rep) MAINWND->pGetBrowser()->StartReplay(rep, mode); } } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay111() { _StartCurrentReplay(BW_111); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay112() { _StartCurrentReplay(BW_112); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay114() { _StartCurrentReplay(BW_114); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay115() { _StartCurrentReplay(BW_115); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay116() { _StartCurrentReplay(BW_116); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay113() { _StartCurrentReplay(BW_113); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay110() { _StartCurrentReplay(BW_110); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay109() { _StartCurrentReplay(BW_109); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplaySC() { _StartCurrentReplay(BW_SC); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay() { _StartCurrentReplay(BW_AUTO); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnRclickListevents(NMHDR* pNMHDR, LRESULT* pResult) { if(m_replay.IsDone()) { // load menu CMenu menu; menu.LoadMenu(IDR_MENU_EVENTS); CMenu *pSub = menu.GetSubMenu(0); // display popup menu CPoint pt; GetCursorPos(&pt); pSub->TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON, pt.x, pt.y, this); } *pResult = 0; } //------------------------------------------------------------------------------------- static char szFilterTxt[] = "Text File (*.txt)|*.txt|All Files (*.*)|*.*||"; static char szFilterHtml[] = "HTML File (*.html)|*.html|All Files (*.*)|*.*||"; bool DlgStats::_GetFileName(const char *filter, const char *ext, const char *def, CString& file) { CFileDialog dlg(FALSE,ext,def,0,filter,this); CString str = AfxGetApp()->GetProfileString("BWCHART_MAIN","EXPDIR",""); if(!str.IsEmpty()) dlg.m_ofn.lpstrInitialDir = str; if(dlg.DoModal()==IDOK) { file = dlg.GetPathName(); AfxGetApp()->WriteProfileString("BWCHART_MAIN","EXPDIR",file); return true; } return false; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnExportToText() { assert(m_replay.IsDone()); // get export file CString file; if(!_GetFileName(szFilterTxt, "txt", "bwchart.txt", file)) return; // create file CWaitCursor wait; int err = m_replay.ExportToText(file,m_useSeconds?true:false,'\t'); if(err==-1) {AfxMessageBox(IDS_CANTCREATFILE); return;} } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnExportToBWCoach() { assert(m_replay.IsDone()); ExportCoachDlg dlg(this,&m_replay); dlg.DoModal(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnExportToHtml() { assert(m_replay.IsDone()); // get export file CString file; if(!_GetFileName(szFilterHtml, "html", "bwchart.html", file)) return; // create file FILE *fp=fopen(file,"wb"); if(fp==0) {AfxMessageBox(IDS_CANTCREATFILE); return;} // list events in list view CWaitCursor wait; for(unsigned long i=0;i<m_replay.GetEnActionCount(); i++) { // get action const IStarcraftAction *action = m_replay.GetEnAction((int)i); } //close file fclose(fp); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnFilterChange() { UpdateData(TRUE); _UpdateActionFilter(true); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnNextSuspect() { if(!m_replay.IsDone()) return; // find next suspect event int newidx = m_replay.GetNextSuspectEvent(m_selectedAction); if(newidx!=-1) { // select corresponding line in list view m_lockListView=true; m_listEvents.SetItemState(newidx,LVIS_SELECTED|LVIS_FOCUSED,LVIS_SELECTED|LVIS_FOCUSED); m_listEvents.EnsureVisible(newidx,FALSE); m_lockListView=false; // update selected player & cursor pos _SelectAction(newidx); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnSelchangeApmstyle() { UpdateData(TRUE); if(m_replay.IsDone()) { // if apm style was changed if(m_replay.UpdateAPM(m_apmStyle[APM],m_apmStyle[MAPCOVERAGE])) { // repaint chart InvalidateRect(m_boardRect,FALSE); // update player stats _DisplayPlayerStats(); } } } //-----------------------------------------------------------------------------------------------------------------
29.947953
165
0.609408
udonyang
1c2682699ff4fe1a11841ac9317106789dfb46ed
369
hpp
C++
phase_1/eval/york/challenge/src/http/request_state.hpp
cromulencellc/chess-aces
7780e29de1991758078816ca501ff79a2586b8c2
[ "MIT" ]
null
null
null
phase_1/eval/york/challenge/src/http/request_state.hpp
cromulencellc/chess-aces
7780e29de1991758078816ca501ff79a2586b8c2
[ "MIT" ]
null
null
null
phase_1/eval/york/challenge/src/http/request_state.hpp
cromulencellc/chess-aces
7780e29de1991758078816ca501ff79a2586b8c2
[ "MIT" ]
null
null
null
#pragma once #include <optional> #include <vector> namespace http { struct RequestState { public: bool abort = false; bool want_line = false; std::optional<size_t> want_bytes; bool ready_to_respond = false; bool in_valid_state() const; }; } std::ostream& operator<<(std::ostream& o, const http::RequestState& rs);
18.45
55
0.634146
cromulencellc
1c27fe1b64d1ff82139e5e8dac02a3cbfa0bd650
872
cpp
C++
engine/visibility/BackSurfaceCull/BackSurfaceCull.cpp
PiroDev/graphics-engine
bf1e5f57878c02421e2e8a787d94ce6074637402
[ "Apache-2.0" ]
null
null
null
engine/visibility/BackSurfaceCull/BackSurfaceCull.cpp
PiroDev/graphics-engine
bf1e5f57878c02421e2e8a787d94ce6074637402
[ "Apache-2.0" ]
null
null
null
engine/visibility/BackSurfaceCull/BackSurfaceCull.cpp
PiroDev/graphics-engine
bf1e5f57878c02421e2e8a787d94ce6074637402
[ "Apache-2.0" ]
null
null
null
#include "BackSurfaceCull.hpp" void BackSurfaceCull::operator()(std::shared_ptr<Model> &model, const Point3f &eye) const { std::vector<Polygon> remaining; const auto &polygons = model->Polygons(); const auto &points = model->Points(); const auto &normals = model->Normals(); for (const auto &polygon: model->Polygons()) { bool isCulled = true; const auto &pPos = polygon.Points(); const auto &nPos = polygon.Normals(); for (auto i = 0; i < pPos.size() && isCulled; i++) { auto p = points[pPos[i]]; auto n = normals[nPos[i]]; auto eyePointVec = Normal(p, eye); if (n * eyePointVec >= 0) { isCulled = false; } } if (!isCulled) { remaining.push_back(polygon); } } model->Polygons() = remaining; }
28.129032
91
0.544725
PiroDev
1c28a6c2d84c8db78475da19c2ed7f4c02177055
2,687
cc
C++
cagey-engine/source/cagey/window/Window.cc
theycallmecoach/cagey-engine
7a90826da687a1ea2837d0f614aa260aa1b63262
[ "MIT" ]
null
null
null
cagey-engine/source/cagey/window/Window.cc
theycallmecoach/cagey-engine
7a90826da687a1ea2837d0f614aa260aa1b63262
[ "MIT" ]
null
null
null
cagey-engine/source/cagey/window/Window.cc
theycallmecoach/cagey-engine
7a90826da687a1ea2837d0f614aa260aa1b63262
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////////////// //// //// cagey-engine - Toy 3D Engine //// Copyright (c) 2014 Kyle Girard <theycallmecoach@gmail.com> //// //// The MIT License (MIT) //// //// Permission is hereby granted, free of charge, to any person obtaining a copy //// of this software and associated documentation files (the "Software"), to deal //// in the Software without restriction, including without limitation the rights //// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //// copies of the Software, and to permit persons to whom the Software is //// furnished to do so, subject to the following conditions: //// //// The above copyright notice and this permission notice shall be included in //// all copies or substantial portions of the Software. //// //// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //// SOFTWARE. //// ////////////////////////////////////////////////////////////////////////////////// // //#include <cagey/window/Window.hh> //#include <cagey/window/VideoMode.hh> //#include "cagey/window/WindowFactory.hh" //#include "cagey/window/IWindowImpl.hh" //#include <iostream> // //namespace { // cagey::window::Window const * fullScreenWindow = nullptr; //} // //namespace cagey { //namespace window { // //Window::Window(VideoMode const & vidMode, std::string const & winName, StyleSet const & winStyle) // : mImpl{}, // mVideoMode{vidMode}, // mName{winName}, // mStyle{winStyle}, // mVisible{false} { // // if (winStyle.test(Style::Fullscreen)) { // if (fullScreenWindow) { // std::cerr << "Unable to create two fullscreen windows" << std::endl; // mStyle.flip(Style::Fullscreen); // } else { // if (!mVideoMode.isValid()) { // //@TODO invalid video mode...should have better exception // throw 0; // } // fullScreenWindow = this; // } // } // // mImpl = detail::WindowFactory::create(mVideoMode, mName, mStyle); // mVisible = true; //} // //auto Window::getTitle() const -> std::string { // return mName; //} // //auto Window::setTitle(std::string const & newTitle) -> void { // mName = newTitle; // mImpl->setTitle(newTitle); //} // //} // namespace window //} // namespace cagey // // //
34.012658
99
0.629326
theycallmecoach
1c2a37052907e1c29dfc55784516f8f3d7af259a
8,085
cc
C++
src/system/kernel/core/process/Process.cc
jmolloy/pedigree
4f02647d8237cc19cff3c20584c0fdd27b14a7d4
[ "0BSD" ]
37
2015-01-11T20:08:48.000Z
2022-01-06T17:25:22.000Z
src/system/kernel/core/process/Process.cc
jmolloy/pedigree
4f02647d8237cc19cff3c20584c0fdd27b14a7d4
[ "0BSD" ]
4
2016-05-20T01:01:59.000Z
2016-06-22T00:03:27.000Z
src/system/kernel/core/process/Process.cc
jmolloy/pedigree
4f02647d8237cc19cff3c20584c0fdd27b14a7d4
[ "0BSD" ]
6
2015-09-14T14:44:20.000Z
2019-01-11T09:52:21.000Z
/* * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #if defined(THREADS) #include <processor/types.h> #include <process/Process.h> #include <processor/Processor.h> #include <process/Scheduler.h> #include <processor/VirtualAddressSpace.h> #include <linker/Elf.h> #include <processor/PhysicalMemoryManager.h> #include <Log.h> #include <utilities/ZombieQueue.h> #include <process/SignalEvent.h> #include <Subsystem.h> #include <vfs/File.h> Process::Process() : m_Threads(), m_NextTid(0), m_Id(0), str(), m_pParent(0), m_pAddressSpace(&VirtualAddressSpace::getKernelAddressSpace()), m_ExitStatus(0), m_Cwd(0), m_Ctty(0), m_SpaceAllocator(true), m_pUser(0), m_pGroup(0), m_pEffectiveUser(0), m_pEffectiveGroup(0), m_pDynamicLinker(0), m_pSubsystem(0), m_DeadThreads(0) { m_Id = Scheduler::instance().addProcess(this); m_SpaceAllocator.free(m_pAddressSpace->getUserStart(), m_pAddressSpace->getUserReservedStart()); } Process::Process(Process *pParent) : m_Threads(), m_NextTid(0), m_Id(0), str(), m_pParent(pParent), m_pAddressSpace(0), m_ExitStatus(0), m_Cwd(pParent->m_Cwd), m_Ctty(pParent->m_Ctty), m_SpaceAllocator(pParent->m_SpaceAllocator), m_pUser(pParent->m_pUser), m_pGroup(pParent->m_pGroup), m_pEffectiveUser(pParent->m_pEffectiveUser), m_pEffectiveGroup(pParent->m_pEffectiveGroup), m_pDynamicLinker(pParent->m_pDynamicLinker), m_pSubsystem(0), m_DeadThreads(0) { m_pAddressSpace = pParent->m_pAddressSpace->clone(); // Copy the heap, but only if it's not the kernel heap (which is static) uintptr_t parentHeap = reinterpret_cast<uintptr_t>(pParent->m_pAddressSpace->m_Heap); // 0xc0000000 if(parentHeap < m_pAddressSpace->getKernelStart()) /// \todo A better way would be nice. m_pAddressSpace->setHeap(pParent->m_pAddressSpace->m_Heap, pParent->m_pAddressSpace->m_HeapEnd); m_Id = Scheduler::instance().addProcess(this); // Set a temporary description. str = m_pParent->str; str += "<F>"; // F for forked. } Process::~Process() { Scheduler::instance().removeProcess(this); Thread *pThread = m_Threads[0]; if(m_Threads.count()) m_Threads.erase(m_Threads.begin()); else WARNING("Process with an empty thread list, potentially unstable situation"); if(!pThread && m_Threads.count()) WARNING("Process with a null entry for the first thread, potentially unstable situation"); if (pThread != Processor::information().getCurrentThread()) delete pThread; // Calls Scheduler::remove and this::remove. else if(pThread) pThread->setParent(0); if(m_pSubsystem) delete m_pSubsystem; Spinlock lock; lock.acquire(); // Disables interrupts. VirtualAddressSpace &VAddressSpace = Processor::information().getVirtualAddressSpace(); Processor::switchAddressSpace(*m_pAddressSpace); m_pAddressSpace->revertToKernelAddressSpace(); Processor::switchAddressSpace(VAddressSpace); delete m_pAddressSpace; lock.release(); } size_t Process::addThread(Thread *pThread) { m_Threads.pushBack(pThread); return (m_NextTid += 1); } void Process::removeThread(Thread *pThread) { for(Vector<Thread*>::Iterator it = m_Threads.begin(); it != m_Threads.end(); it++) { if (*it == pThread) { m_Threads.erase(it); break; } } } size_t Process::getNumThreads() { return m_Threads.count(); } Thread *Process::getThread(size_t n) { if (n >= m_Threads.count()) { FATAL("Process::getThread(" << Dec << n << Hex << ") - Parameter out of bounds."); return 0; } return m_Threads[n]; } void Process::kill() { /// \todo Grab the scheduler lock! Processor::setInterrupts(false); if(m_pParent) NOTICE("Kill: " << m_Id << " (parent: " << m_pParent->getId() << ")"); else NOTICE("Kill: " << m_Id << " (parent: <orphan>)"); // Redraw on kill. /// \todo Caveat with redirection, maybe? Hmm... if(m_Ctty) m_Ctty->truncate(); // Bye bye process - have we got any zombie children? for (size_t i = 0; i < Scheduler::instance().getNumProcesses(); i++) { Process *pProcess = Scheduler::instance().getProcess(i); if (pProcess && (pProcess->m_pParent == this)) { if (pProcess->getThread(0)->getStatus() == Thread::Zombie) { // Kill 'em all! delete pProcess; } else { pProcess->m_pParent = 0; } } } // Kill all our threads except one, which exists in Zombie state. while (m_Threads.count() > 1) { Thread *pThread = m_Threads[0]; if (pThread != Processor::information().getCurrentThread()) { m_Threads.erase(m_Threads.begin()); delete pThread; // Calls Scheduler::remove and this::remove. } } // Tell any threads that may be waiting for us to die. if (m_pParent) m_pParent->m_DeadThreads.release(); else { NOTICE("Adding process to zombie queue for cleanup"); ZombieQueue::instance().addObject(new ZombieProcess(this)); Processor::information().getScheduler().killCurrentThread(); // Should never get here. FATAL("Process: should never get here"); } // We'll get reaped elsewhere NOTICE("Not adding process to zombie queue for cleanup"); Processor::information().getScheduler().schedule(Thread::Zombie); FATAL("Should never get here"); } uintptr_t Process::create(uint8_t *elf, size_t elfSize, const char *name) { FATAL("This function isn't implemented correctly - registration with the dynamic linker is required!"); // At this point we're uninterruptible, as we're forking. Spinlock lock; lock.acquire(); // Create a new process for the init process. Process *pProcess = new Process(Processor::information().getCurrentThread()->getParent()); pProcess->description().clear(); pProcess->description().append(name); VirtualAddressSpace &oldAS = Processor::information().getVirtualAddressSpace(); // Switch to the init process' address space. Processor::switchAddressSpace(*pProcess->getAddressSpace()); // That will have forked - we don't want to fork, so clear out all the chaff in the new address space that's not // in the kernel address space so we have a clean slate. pProcess->getAddressSpace()->revertToKernelAddressSpace(); Elf initElf; // initElf.load(elf, elfSize); // uintptr_t iter = 0; // const char *lib = initElf.neededLibrary(iter); // initElf.allocateSegments(); // initElf.writeSegments(); for (int j = 0; j < 0x20000; j += 0x1000) { physical_uintptr_t phys = PhysicalMemoryManager::instance().allocatePage(); bool b = Processor::information().getVirtualAddressSpace().map(phys, reinterpret_cast<void*> (j+0x40000000), VirtualAddressSpace::Write| VirtualAddressSpace::Execute); if (!b) WARNING("map() failed in init"); } // Alrighty - lets create a new thread for this program - -8 as PPC assumes the previous stack frame is available... new Thread(pProcess, reinterpret_cast<Thread::ThreadStartFunc>(initElf.getEntryPoint()), 0x0 /* parameter */, reinterpret_cast<void*>(0x40020000-8) /* Stack */); // Switch back to the old address space. Processor::switchAddressSpace(oldAS); lock.release(); return pProcess->getId(); } #endif
33
164
0.687322
jmolloy
1c2ab67c1db41c545f994247455c2e688cd42224
321
cpp
C++
src/Omega_h_timer.cpp
overfelt/omega_h
dfc19cc3ea0e183692ca6c548dda39f7892301b5
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/Omega_h_timer.cpp
overfelt/omega_h
dfc19cc3ea0e183692ca6c548dda39f7892301b5
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/Omega_h_timer.cpp
overfelt/omega_h
dfc19cc3ea0e183692ca6c548dda39f7892301b5
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#include "Omega_h_timer.hpp" namespace Omega_h { Now now() { Now t; t.impl = std::chrono::high_resolution_clock::now(); return t; } Real operator-(Now b, Now a) { return std::chrono::duration_cast<std::chrono::nanoseconds>(b.impl - a.impl) .count() * 1e-9; } } // end namespace Omega_h
17.833333
78
0.619938
overfelt
1c2cf5f3e0ce5d29833ec36397e7c4fea8733201
1,321
cpp
C++
src/plugins/cgal/nodes/topology/convex_hull.cpp
martin-pr/possumwood
0ee3e0fe13ef27cf14795a79fb497e4d700bef63
[ "MIT" ]
232
2017-10-09T11:45:28.000Z
2022-03-28T11:14:46.000Z
src/plugins/cgal/nodes/topology/convex_hull.cpp
martin-pr/possumwood
0ee3e0fe13ef27cf14795a79fb497e4d700bef63
[ "MIT" ]
26
2019-01-20T21:38:25.000Z
2021-10-16T03:57:17.000Z
src/plugins/cgal/nodes/topology/convex_hull.cpp
martin-pr/possumwood
0ee3e0fe13ef27cf14795a79fb497e4d700bef63
[ "MIT" ]
33
2017-10-26T19:20:38.000Z
2022-03-16T11:21:43.000Z
#include <CGAL/convex_hull_3.h> #include <possumwood_sdk/node_implementation.h> #include "datatypes/meshes.h" #include "errors.h" namespace { using possumwood::CGALPolyhedron; using possumwood::Meshes; typedef possumwood::CGALPolyhedron Mesh; dependency_graph::InAttr<Meshes> a_inMesh; dependency_graph::OutAttr<Meshes> a_outMesh; dependency_graph::State compute(dependency_graph::Values& data) { possumwood::ScopedOutputRedirect redirect; // inefficient - an adaptor to replace this would be much better std::vector<possumwood::CGALKernel::Point_3> points; for(auto& mesh : data.get(a_inMesh)) points.insert(points.end(), mesh.polyhedron().points_begin(), mesh.polyhedron().points_end()); possumwood::Mesh mesh("convex_hull"); CGAL::convex_hull_3(points.begin(), points.end(), mesh.edit().polyhedron()); Meshes result; result.addMesh(mesh); data.set(a_outMesh, result); return redirect.state(); } void init(possumwood::Metadata& meta) { meta.addAttribute(a_inMesh, "in_mesh", possumwood::Meshes(), possumwood::AttrFlags::kVertical); meta.addAttribute(a_outMesh, "out_mesh", possumwood::Meshes(), possumwood::AttrFlags::kVertical); meta.addInfluence(a_inMesh, a_outMesh); meta.setCompute(compute); } possumwood::NodeImplementation s_impl("cgal/topology/convex_hull", init); } // namespace
28.106383
98
0.766086
martin-pr
1c2e89d744f4124d22abdfe05d593e26c4d67f5a
6,353
cpp
C++
Child/Releases/r081211/Code/tListInputData/tListInputData.cpp
dvalters/child
9874278f5308ab6c5f0cb93ed879bca9761d24b9
[ "MIT" ]
9
2015-02-23T15:47:20.000Z
2020-05-19T23:42:05.000Z
Child/Releases/r081211/Code/tListInputData/tListInputData.cpp
dvalters/child
9874278f5308ab6c5f0cb93ed879bca9761d24b9
[ "MIT" ]
3
2020-04-21T06:12:53.000Z
2020-08-20T16:56:17.000Z
Child/Releases/r081211/Code/tListInputData/tListInputData.cpp
dvalters/child
9874278f5308ab6c5f0cb93ed879bca9761d24b9
[ "MIT" ]
12
2015-02-18T18:34:57.000Z
2020-07-12T04:04:36.000Z
/**************************************************************************/ /** ** @file tListInputData.cpp ** @brief Functions for class tListInputData. ** ** Modifications: ** - changed .tri file format from points-edges-triangles to ** points-triangles-edges, compatible with earlier format (gt 1/98) ** - GT merged tListIFStreams and tListInputData into a single class ** to avoid multiple definition errors resulting from mixing ** template & non-template classes (1/99) ** - Bug fix in constructor: nnodes was being read from edge and ** triangle files -- thus arrays dimensioned incorrectly! (GT 04/02) ** - Remove dead code. Add findRightTime (AD 07/03) ** - Add Random number generator handling. (AD 08/03) ** - Refactoring with multiple classes (AD 11/03) ** - Add tVegetation handling (AD 11/03) ** ** $Id: tListInputData.cpp,v 1.25 2004/06/16 13:37:35 childcvs Exp $ */ /**************************************************************************/ #include "tListInputData.h" #include <iostream> #include "../Mathutil/mathutil.h" void tListInputDataBase:: ReportIOError(IOErrorType t, const char *filename, const char *suffix, int n) { std::cerr << "\nFile: '" << filename << suffix << "' " << "- Can't read "; switch (t){ case IOTime: std::cerr << "time"; break; case IOSize: std::cerr << "size"; break; case IORecord: std::cerr << "record " << n; break; } std::cerr << "." << std::endl; ReportFatalError( "Input/Output Error." ); } /**************************************************************************\ ** ** tListInputDataBase::openFile ** ** Find the right time in file and position it for reading ** \**************************************************************************/ void tListInputDataBase:: openFile( std::ifstream &infile, const char *basename, const char *ext) { char inname[80]; // full name of an input file // Open each of the four files assert( strlen(basename)+strlen(ext)<sizeof(inname) ); strcpy( inname, basename ); strcat( inname, ext ); infile.open(inname); if( !infile.good() ) { std::cerr << "Error: I can't find the following files:\n" << "\t" << basename << ext << "\n"; ReportFatalError( "Unable to open triangulation input file(s)." ); } } /**************************************************************************\ ** ** tListInputData::findRightTime ** ** Find the right time in file and position it for reading ** \**************************************************************************/ void tListInputDataBase:: findRightTime( std::ifstream &infile, int &nn, double intime, const char *basename, const char *ext, const char *typefile) { char headerLine[kMaxNameLength]; // header line read from input file bool righttime = false; double time; while( !( infile.eof() ) && !righttime ) { /*infile.getline( headerLine, kMaxNameLength ); if( headerLine[0] == kTimeLineMark ) { infile.seekg( -infile.gcount(), ios::cur ); infile >> time; std::cout << "from file, time = " << time << std::endl; std::cout << "Read: " << headerLine << std::endl; if( time == intime ) righttime = 1; }*/ infile >> time; if (infile.fail()) ReportIOError(IOTime, basename, ext); if (0) //DEBUG std::cout << "Read time: " << time << std::endl; if( time < intime ) { infile >> nn; if (infile.fail()) ReportIOError(IOSize, basename, ext); if (0) //DEBUG std::cout << "nn (" << typefile << ")= " << nn << std::endl; int i; for( i=1; i<=nn+1; i++ ) { infile.getline( headerLine, kMaxNameLength ); } } else righttime = true; if (0) //DEBUG std::cout << " NOW are we at eof? " << infile.eof() << std::endl; } if( !( infile.eof() ) ) { infile >> nn; if (infile.fail()) ReportIOError(IOSize, basename, ext); } else { std::cerr << "Couldn't find the specified input time in the " << typefile << " file\n"; ReportFatalError( "Input error" ); } } /**************************************************************************\ ** ** tListInputDataRand::tListInputDataRand() ** ** Read state from file ** \**************************************************************************/ tListInputDataRand:: tListInputDataRand( const tInputFile &inputfile, tRand &rand ) { double intime; // desired time char basename[80]; inputfile.ReadItem( basename, sizeof(basename), "INPUTDATAFILE" ); std::ifstream dataInfile; openFile( dataInfile, basename, SRANDOM); // Find out which time slice we want to extract intime = inputfile.ReadItem( intime, "INPUTTIME" ); if (1) //DEBUG std::cout << "intime = " << intime << std::endl; // Find specified input times in input data files and read # items. int nn; findRightTime( dataInfile, nn, intime, basename, SRANDOM, "random number generator"); if ( rand.numberRecords() != nn ) { std::cerr << "Invalid number of records for the random number generator\n"; ReportFatalError( "Input error" ); } // Read in data from file rand.readFromFile( dataInfile ); } /**************************************************************************\ ** ** tListInputDataVegetation::tListInputDataVegetation() ** ** Read state from file ** \**************************************************************************/ tListInputDataVegetation:: tListInputDataVegetation( const tInputFile &inputfile ) { double intime; // desired time char basename[80]; // Read base name for triangulation files from inputfile inputfile.ReadItem( basename, sizeof(basename), "INPUTDATAFILE" ); std::ifstream dataInfile; openFile( dataInfile, basename, SVEG); // Find out which time slice we want to extract intime = inputfile.ReadItem( intime, "INPUTTIME" ); if (1) //DEBUG std::cout << "intime = " << intime << std::endl; // Find specified input times in input data files and read # items. int nn; findRightTime( dataInfile, nn, intime, basename, SVEG, "vegetation mask"); // Read in data from file vegCov.setSize(nn); for( int i=0; i<nn; ++i ){ dataInfile >> vegCov[i]; if (dataInfile.fail()) ReportIOError(IORecord, basename, SVEG, i); } }
30.990244
79
0.555171
dvalters
1c330f7ac0367e8acfd10060b8804c48af9818e7
353
cpp
C++
source/code/programs/examples/saturating/main.cpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
33
2019-05-30T07:43:32.000Z
2021-12-30T13:12:32.000Z
source/code/programs/examples/saturating/main.cpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
371
2019-05-16T15:23:50.000Z
2021-09-04T15:45:27.000Z
source/code/programs/examples/saturating/main.cpp
UniLang/compiler
c338ee92994600af801033a37dfb2f1a0c9ca897
[ "MIT" ]
6
2019-08-22T17:37:36.000Z
2020-11-07T07:15:32.000Z
#include <cstddef> #include <cstdint> #include <iostream> #include "types.hpp" uint8_t x[] { 101, 27, 3, 95 }; int main () { uint_sat8_t s = 25; for (const auto& v : x) { s -= v; } // s == 0 s++; // s == 1 for (const auto& v : x) { s *= v; } unsigned j = s; // s == 255 std::cout << j << std::endl; }
16.045455
32
0.456091
luxe
1c3585e9f7e941a11ef84bd043a79cf2de61c87f
2,522
cpp
C++
LeetCode/C++/General/Hard/LongestValidParentheses/main.cpp
busebd12/InterviewPreparation
e68c41f16f7790e44b10a229548186e13edb5998
[ "MIT" ]
null
null
null
LeetCode/C++/General/Hard/LongestValidParentheses/main.cpp
busebd12/InterviewPreparation
e68c41f16f7790e44b10a229548186e13edb5998
[ "MIT" ]
null
null
null
LeetCode/C++/General/Hard/LongestValidParentheses/main.cpp
busebd12/InterviewPreparation
e68c41f16f7790e44b10a229548186e13edb5998
[ "MIT" ]
null
null
null
#include <iostream> #include <stack> #include <string> #include <vector> /* * Solutions: * * 1. Brute-force. We generate every possible substring and if the substring is valid, update the result * to be the length of the longest one of these substrings. * * Time complexity: O(n^3) [where n is the length of the input string] * Space complexity: O(n^3) * * * 2. We "colour"/label each pair of valid parentheses with 1's and all invalid parentheses with 0's. * Then, the problem is reduced to finding the maximum substring sum of all 1's. * * Time complexity: O(n) [where n is the length of the input string] * Space complexity: O(n) */ bool isValid(std::string & str) { int count=0; for(const auto & character : str) { if(character=='(') { count++; } else { if(count <= 0) { return false; } count--; } } return count==0; } int longestValidParentheses(std::string s) { int result=0; if(s.empty()) { return result; } int n=int(s.size()); for(int start=0;start<=n;++start) { for(int length=1;length<=n-start;++length) { std::string substring=s.substr(start, length); if(isValid(substring)) { if(result==0 || substring.length() > result) { result=substring.length(); } } } } return result; } int longestValidParentheses(std::string s) { int result=0; if(s.empty()) { return result; } std::stack<int> stk; auto n=s.size(); std::vector<int> digits(n, 0); for(auto i=0;i<n;++i) { char character=s[i]; if(character=='(') { stk.push(i); } else { if(!stk.empty()) { if(s[stk.top()]=='(') { digits[stk.top()]=1; digits[i]=1; stk.pop(); } } else { stk.push(i); } } } int length=0; for(const auto & digit : digits) { if(digit==1) { length++; } else { result=std::max(result, length); length=0; } } result=std::max(result, length); return result; }
18.143885
104
0.458763
busebd12
1c3910f2a6205a1a12e5f64cf3fca1df90a4da2b
8,952
cpp
C++
Web/src/ApacheAgent/ApacheAgent.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Web/src/ApacheAgent/ApacheAgent.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Web/src/ApacheAgent/ApacheAgent.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
// // Copyright (C) 2004-2011 by Autodesk, Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of version 2.1 of the GNU Lesser // General Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // #include "MapGuideCommon.h" #include "httpd.h" #include "http_config.h" #include "ap_config.h" #include "http_log.h" #include "http_protocol.h" #include "http_main.h" #include "util_script.h" #include "http_core.h" #include "apr_strings.h" #include "apr_tables.h" #ifdef strtoul #undef strtoul #endif #define strtoul strtoul #ifndef _WIN32 #ifdef REG_NOMATCH #undef REG_NOMATCH #endif #endif #include "WebSupport.h" #include "HttpHandler.h" #include "MapAgentGetParser.h" #include "MapAgentStrings.h" #include "MapAgentCommon.h" #include "ApacheResponseHandler.h" #include "ApachePostParser.h" #include <stdio.h> #include <string.h> #include <stdarg.h> #include <stdlib.h> extern "C" module AP_MODULE_DECLARE_DATA mgmapagent_module; void Initialize(request_rec *r); STRING gConfigPath; // Iterate through the values in an apr_table. // Used only during debugging/development to identify the available environment variables. int iterate_func(void *req, const char *key, const char *value) { int stat; char *line; request_rec *r = (request_rec *)req; if (key == NULL || value == NULL || value[0] == '\0') return 1; line = apr_psprintf(r->pool, "%s => %s\n", key, value); stat = ap_rputs(line, r); return 1; } // Extract the values in the apr_tables. // Used only during debugging/development to identify the available environment variables. static int dump_request(request_rec *r) { // if (strcmp(r->handler, "mgmapagent-handler")) // return DECLINED; ap_set_content_type(r, "text/plain"); if (r->header_only) return OK; apr_table_do(iterate_func, r, r->headers_in, NULL); apr_table_do(iterate_func, r, r->subprocess_env, NULL); apr_table_do(iterate_func, r, r->headers_out, NULL); return OK; } string GetServerVariable(request_rec *r, const char *variableName) { string sValue; const char *value = apr_table_get(r->subprocess_env, variableName); if (value) { sValue.append(value); } return sValue; } static int mgmapagent_handler (request_rec *r) { if (strcmp(r->handler, "mgmapagent_handler") != 0) // NOXLATE { return DECLINED; } Initialize(r); ApacheResponseHandler responseHandler(r); MG_TRY() // Construct self Url. It is embedded into the output stream // of some requests (like GetMap). Use a fully qualified URL. string serverName = GetServerVariable(r, MapAgentStrings::ServerName); string serverPort = GetServerVariable(r, MapAgentStrings::ServerPort); string scriptName = GetServerVariable(r, MapAgentStrings::ScriptName); string remoteAddr = GetServerVariable(r, MapAgentStrings::RemoteAddr); string httpClientIp = GetServerVariable(r, MapAgentStrings::HttpClientIp); string httpXFF = GetServerVariable(r, MapAgentStrings::HttpXForwardedFor); string sSecure = GetServerVariable(r, MapAgentStrings::Secure); const char * secure = sSecure.c_str(); bool isSecure = (secure != NULL && !_stricmp(secure, "on")); // NOXLATE string url = isSecure ? MapAgentStrings::Https : MapAgentStrings::Http; if (!serverName.empty() && !serverPort.empty() && !scriptName.empty()) { url.append(serverName); url += ':'; url.append(serverPort); url.append(scriptName); } STRING wUrl = MgUtil::MultiByteToWideChar(url); Ptr<MgHttpRequest> request = new MgHttpRequest(wUrl); Ptr<MgHttpRequestParam> params = request->GetRequestParam(); string query = GetServerVariable(r, MapAgentStrings::QueryString); string requestMethod = GetServerVariable(r, MapAgentStrings::RequestMethod); ApachePostParser postParser(r); if (!requestMethod.empty() && requestMethod.find("POST") != string::npos) // NOXLATE { // Must be a POST request postParser.Parse(params); } else if (!query.empty()) { MapAgentGetParser::Parse(query.c_str(), params); } // check for CLIENTIP, if it's not there (and it shouldn't be), // add it in using httpClientIp. httpXFF or remoteAddr STRING clientIp = L""; if (!params->ContainsParameter(L"CLIENTIP")) // NOXLATE { if (!httpClientIp.empty() && _stricmp(httpClientIp.c_str(), MapAgentStrings::Unknown) != 0) { clientIp = MgUtil::MultiByteToWideChar(httpClientIp); params->AddParameter(L"CLIENTIP", clientIp); // NOXLATE } else if (!httpXFF.empty() && _stricmp(httpXFF.c_str(), MapAgentStrings::Unknown) != 0) { clientIp = MgUtil::MultiByteToWideChar(httpXFF); params->AddParameter(L"CLIENTIP", clientIp); // NOXLATE } else if (!remoteAddr.empty()) { clientIp = MgUtil::MultiByteToWideChar(remoteAddr); params->AddParameter(L"CLIENTIP", clientIp); // NOXLATE } } // Check for HTTP Basic Auth header string auth = GetServerVariable(r, MapAgentStrings::HttpAuth); bool gotAuth = MapAgentCommon::ParseAuth((char *)auth.c_str(), params); if (!gotAuth) { // And check for a REMOTE_USER remapped header auth = GetServerVariable(r, MapAgentStrings::HttpRemoteUser); gotAuth = MapAgentCommon::ParseAuth((char *)auth.c_str(), params); } // Log request information string postData = ""; if (!requestMethod.empty() && requestMethod.find("POST") != string::npos) // NOXLATE { // Get the post xml data postData = params->GetXmlPostData(); } STRING client = params->GetParameterValue(MgHttpResourceStrings::reqClientAgent); MapAgentCommon::LogRequest(client, clientIp, url, requestMethod, postData, query); Ptr<MgPropertyCollection> paramList = params->GetParameters()->GetPropertyCollection(); if (paramList != NULL) { // Check to be sure that we have some kind of credentials before continuing. Either // username/password or sessionid. bool bValid = paramList->Contains(MgHttpResourceStrings::reqSession); // Strike two: no session? how about a username? if (!bValid) bValid = paramList->Contains(MgHttpResourceStrings::reqUsername); // Strike three: no username either? How about if it's an XML POST if (!bValid) bValid = params->GetXmlPostData().length() != 0; // Certain operations do not require authentication STRING operation = params->GetParameterValue(L"OPERATION"); if((_wcsicmp(operation.c_str(), L"GETSITESTATUS") == 0)) { bValid = true; } if (!bValid) { // Invalid authentication information is not fatal, we should continue. responseHandler.RequestAuth(); return OK; } Ptr<MgHttpResponse> response = request->Execute(); responseHandler.SendResponse(response); } MG_CATCH(L"ApacheAgent.mgmapagent_handler"); if (mgException != NULL) { responseHandler.SendError(mgException); } return OK; } static void register_hooks (apr_pool_t *p) { ap_hook_handler(mgmapagent_handler, NULL, NULL, APR_HOOK_FIRST); } extern "C" { module AP_MODULE_DECLARE_DATA mgmapagent_module = { STANDARD20_MODULE_STUFF, NULL, NULL, NULL, NULL, NULL, register_hooks, }; }; void Initialize(request_rec *r) { ap_add_cgi_vars(r); ap_add_common_vars(r); // Uncomment for Debugging only //dump_request(r); if (!IsWebTierInitialized()) { STRING scriptPath = MgUtil::MultiByteToWideChar(GetServerVariable(r, MapAgentStrings::ScriptFileName)); STRING::size_type lastSlash = scriptPath.find_last_of(L"/"); // NOXLATE if (lastSlash < scriptPath.length()) { gConfigPath = scriptPath.substr(0, lastSlash + 1); } else { gConfigPath = scriptPath; } STRING configFile = gConfigPath; configFile.append(MapAgentStrings::WebConfig); MG_TRY() MgInitializeWebTier(configFile); MG_CATCH_AND_THROW(L"ApacheAgent.Initialize"); } }
30.040268
111
0.661416
achilex
1c39384ce95547642533d79874ef7f0dda03a3c5
4,864
cpp
C++
source/Foundation/DataStream.cpp
GrimshawA/Nephilim
1e69df544078b55fdaf58a04db963e20094f27a9
[ "Zlib" ]
19
2015-12-19T11:15:57.000Z
2022-03-09T11:22:11.000Z
source/Foundation/DataStream.cpp
DevilWithin/Nephilim
1e69df544078b55fdaf58a04db963e20094f27a9
[ "Zlib" ]
1
2017-05-17T09:31:10.000Z
2017-05-19T17:01:31.000Z
source/Foundation/DataStream.cpp
GrimshawA/Nephilim
1e69df544078b55fdaf58a04db963e20094f27a9
[ "Zlib" ]
3
2015-12-14T17:40:26.000Z
2021-02-25T00:42:42.000Z
#include <Nephilim/Foundation/DataStream.h> #include <Nephilim/Foundation/IODevice.h> #include <Nephilim/Foundation/String.h> #include <assert.h> #include <stdio.h> NEPHILIM_NS_BEGIN /// Constructs a invalid data stream DataStream::DataStream() : m_device(NULL) { } /// Constructs a data stream from a device DataStream::DataStream(IODevice& device) : m_device(&device) { } /// Set the device of this data stream void DataStream::setDevice(IODevice& device) { m_device = &device; } /// Read <size> bytes from the stream void DataStream::read(void* destination, uint32_t size) { assert(m_device); m_device->read(reinterpret_cast<char*>(destination), size); } /// Write a memory segment to the stream as-is void DataStream::write(void* source, uint32_t size) { assert(m_device); m_device->write(reinterpret_cast<char*>(source), size); } /// Write a uint32_t to the stream void DataStream::write_uint32(uint32_t v) { assert(m_device); m_device->write(reinterpret_cast<const char*>(&v), sizeof(v)); } /// Reads the next byte as a char char DataStream::readChar() { char c = EOF; if(m_device) { m_device->read(&c, sizeof(char)); } return c; } /// Reads count chars and stores them in the pre allocated buffer destination void DataStream::readChars(int count, char* destination) { if(m_device) { for(int i = 0; i < count; ++i) { m_device->read(&destination[i], sizeof(char)); } } } /// Write a 64-bit integer DataStream& DataStream::operator<<(Int64 value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Write a 64-bit signed integer DataStream& DataStream::operator<<(Int32 value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Write a 16-bit signed integer DataStream& DataStream::operator<<(Int16 value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Write a 8-bit signed integer DataStream& DataStream::operator<<(Int8 value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Write a 32-bit unsigned integer DataStream& DataStream::operator<<(Uint32 value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Write a boolean as a unsigned byte DataStream& DataStream::operator<<(bool value) { if(m_device) { Uint8 tempValue = static_cast<Uint8>(value); m_device->write(reinterpret_cast<const char*>(&tempValue), sizeof(tempValue)); } return *this; } /// Write a String DataStream& DataStream::operator<<(const String& value) { if(m_device) { *this << static_cast<Int64>(value.length()); m_device->write(value.c_str(), sizeof(char)*value.length()); } return *this; } /// Write a float DataStream& DataStream::operator<<(float value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Read a 64-bit integer DataStream& DataStream::operator>>(Int64& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Int64)); } return *this; } /// Read a 32-bit signed integer DataStream& DataStream::operator>>(Int32& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Int32)); } return *this; } /// Read a 16-bit signed integer DataStream& DataStream::operator>>(Int16& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Int16)); } return *this; } /// Read a 32-bit unsigned integer DataStream& DataStream::operator>>(Uint32& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Uint32)); } return *this; } /// Read a 16-bit unsigned integer DataStream& DataStream::operator>>(Uint16& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Uint16)); } return *this; } /// Read a 8-bit unsigned integer DataStream& DataStream::operator>>(Uint8& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Uint8)); } return *this; } /// Read a 8-bit boolean DataStream& DataStream::operator>>(bool& value) { if(m_device) { Uint8 tempValue; m_device->read(reinterpret_cast<char*>(&tempValue), sizeof(Uint8)); value = static_cast<bool>(tempValue); } return *this; } /// Read a String DataStream& DataStream::operator>>(String& value) { if(m_device) { Int64 length = 0; *this >> length; char* buffer = new char[length+1]; m_device->read(buffer, length); buffer[length] = '\0'; value = buffer; } return *this; } /// Read a float DataStream& DataStream::operator>>(float& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(float)); } return *this; } NEPHILIM_NS_END
19.07451
80
0.694901
GrimshawA
1c3b4e522196f9a659bf825df253016e8ed0edf2
1,881
cpp
C++
src/bpfrequencytracker.cpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
22
2016-08-11T06:16:25.000Z
2022-02-22T00:06:59.000Z
src/bpfrequencytracker.cpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
9
2016-12-08T12:42:38.000Z
2021-12-28T20:12:15.000Z
src/bpfrequencytracker.cpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
8
2017-06-26T13:15:06.000Z
2021-11-12T18:39:54.000Z
// // bpfrequencytracker.cpp // barcode_project // // Created by luzhao on 4/21/16. // Copyright © 2016 luzhao. All rights reserved. // #include "bpfrequencytracker.hpp" #include <array> #include <cassert> #include <vector> using std::array; using std::vector; namespace barcodeSpace { BPFrequencyTracker::BPFrequencyTracker(size_t num_positions) { _total_position = num_positions; assert(_total_position > 0); _totalFrequency = 0; _condition_frequency_tracker.assign(num_positions, vector<ConditionFrequencyTable>(num_positions,ConditionFrequencyTable())); _self_marginal_frequency.assign(_total_position,array<uint64_t,4>()); for (size_t pos = 0; pos < _total_position; ++pos) { for (auto& t : _condition_frequency_tracker[pos]) { for (auto& c : t) { c.fill(0); } } } for (auto& marg : _self_marginal_frequency) { marg.fill(0); } _dict = kmersDictionary::getAutoInstance(); _bps_buffer.assign(_total_position, 0); } void BPFrequencyTracker::addFrequency(const std::string& seq, size_t freq) { assert(seq.length() == _total_position); for (size_t pos = 0; pos < _total_position; ++pos) { _bps_buffer[pos] = _dict->asc2dna(seq[pos]); _self_marginal_frequency[pos][_bps_buffer[pos]] += 1; } _totalFrequency += freq; // update the conditional frequency table for (size_t pos = 0; pos < _total_position - 1; ++pos) { for (size_t n_pos = pos + 1; n_pos < _total_position; ++n_pos) { _condition_frequency_tracker[pos][n_pos][_bps_buffer[pos]][_bps_buffer[n_pos]] += freq; } } } } // namespace barcodeSpace
34.2
133
0.596491
LaoZZZZZ
1c3f0bc21d3ed41f6fe8b58cb8a63f66eb007ca4
2,627
inl
C++
src/wire/core/transport.inl
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
5
2016-04-07T19:49:39.000Z
2021-08-03T05:24:11.000Z
src/wire/core/transport.inl
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
null
null
null
src/wire/core/transport.inl
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
1
2020-12-27T11:47:31.000Z
2020-12-27T11:47:31.000Z
/* * transport.inl * * Created on: Feb 8, 2016 * Author: zmij */ #ifndef WIRE_CORE_TRANSPORT_INL_ #define WIRE_CORE_TRANSPORT_INL_ #include <wire/core/transport.hpp> #include <wire/util/debug_log.hpp> namespace wire { namespace core { template < typename Session, transport_type Type > transport_listener< Session, Type >::transport_listener( asio_config::io_service_ptr svc, session_factory factory) : io_service_{svc}, acceptor_{*svc}, factory_{factory}, ready_{false}, closed_{true} { } template < typename Session, transport_type Type > transport_listener< Session, Type >::~transport_listener() { try { close(); } catch (...) {} } template < typename Session, transport_type Type > void transport_listener< Session, Type >::open(endpoint const& ep, bool rp) { endpoint_type proto_ep = traits::create_endpoint(io_service_, ep); acceptor_.open(proto_ep.protocol()); acceptor_.set_option( typename acceptor_type::reuse_address{true} ); acceptor_.set_option( typename acceptor_type::keep_alive{ true } ); if (rp) { acceptor_.set_option( reuse_port{true} ); } acceptor_.bind(proto_ep); acceptor_.listen(); closed_ = false; start_accept(); ready_ = true; } template < typename Session, transport_type Type > void transport_listener< Session, Type >::close() { if (!closed_) { closed_ = true; traits::close_acceptor(acceptor_); ready_ = false; } } template < typename Session, transport_type Type > typename transport_listener<Session, Type>::session_ptr transport_listener<Session, Type>::create_session() { return factory_( io_service_ ); } template < typename Session, transport_type Type > endpoint transport_listener<Session, Type>::local_endpoint() const { return traits::get_endpoint_data(acceptor_.local_endpoint()); } template < typename Session, transport_type Type > void transport_listener<Session, Type>::start_accept() { session_ptr session = create_session(); acceptor_.async_accept(session->socket(), ::std::bind(&transport_listener::handle_accept, this, session, ::std::placeholders::_1)); } template < typename Session, transport_type Type > void transport_listener<Session, Type>::handle_accept(session_ptr session, asio_config::error_code const& ec) { if (!ec) { session->start_session(); if (!closed_) start_accept(); } else { DEBUG_LOG(3, "Listener accept error code " << ec.message()); } } } // namespace core } // namespace wire #endif /* WIRE_CORE_TRANSPORT_INL_ */
25.019048
104
0.694328
zmij
1c4131f4e99beaf367375d11ca8b722024d71696
3,249
hpp
C++
include/Common/math.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
2
2020-05-05T13:31:55.000Z
2022-01-16T15:38:00.000Z
include/Common/math.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
null
null
null
include/Common/math.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
1
2021-11-27T02:32:24.000Z
2021-11-27T02:32:24.000Z
#ifndef MATH_HPP #define MATH_HPP #include <cfloat> #include <cmath> #include <iostream> #include <vector> #include "glm/glm.hpp" using namespace std; #define FLT_CMP(a, b) (abs(a-b)<=FLT_EPSILON) #define DEG2RAD(x) (x*M_PI/180.0) #define RAD2DEG(x) (x*180.0/M_PI) template <typename T> ostream& operator<<(ostream& o, const vector<T>& v){ cout<<"["; for(int i=0;i<v.size();i++) cout<<v[i]<<" "; cout<<"]"; return o; } struct Size{ float w; float h; Size(); }; class Vec2D{ public: Vec2D(); Vec2D(float x, float y); void Set(float x, float y); void Normalize(); float Len() const; float Cross(const Vec2D v) const; float Dot(const Vec2D v) const; void Rotate(float degree); Vec2D operator=(const Vec2D v); Vec2D operator+(const Vec2D v); Vec2D operator-(const Vec2D v); Vec2D operator*(const Vec2D v); Vec2D operator/(const Vec2D v); Vec2D operator+=(const Vec2D v); Vec2D operator-=(const Vec2D v); Vec2D operator*=(const Vec2D v); Vec2D operator/=(const Vec2D v); bool operator==(const Vec2D v); bool operator!=(const Vec2D v); Vec2D operator+(float v); Vec2D operator-(float v); Vec2D operator*(float v); Vec2D operator/(float v); Vec2D operator+=(float v); Vec2D operator-=(float v); Vec2D operator*=(float v); Vec2D operator/=(float v); float x; float y; void Print() const; }; float Distance(Vec2D v1, Vec2D v2); Vec2D Normalize(Vec2D v); Vec2D Rotate(Vec2D v, float degree); Vec2D operator+(float n, Vec2D v); Vec2D operator-(float n, Vec2D v); Vec2D operator*(float n, Vec2D v); Vec2D operator/(float n, Vec2D v); ostream& operator<<(ostream& o, const Vec2D v); using Vec = Vec2D; struct Range{ Range(); Range(float a, float b); void Set(float a, float b); float GetMax() const; float GetMin() const; float Len() const; float min; float max; void Print() const; }; ostream& operator<<(ostream& o, Range range); Range GetCoveredRange(const Range r1, const Range r2); Range CombineRange(const Range r1, const Range r2); bool PointInRange(const Range r, float p); bool IsRangeCovered(const Range r1, const Range r2); class Rot2D{ public: Rot2D(); Rot2D(float degree); void Set(float degree); Vec2D GetAxisX() const; Vec2D GetAxisY() const; float GetDegree() const; private: float s; float c; }; struct Mat22{ Mat22(); Mat22(Vec2D c1, Vec2D c2); Mat22(float m00, float m01, float m10, float m11); void Identify(); void Zero(); Mat22 Times(const Mat22 m); Mat22 operator+(const Mat22 m); Mat22 operator-(const Mat22 m); Mat22 operator*(const Mat22 m); Vec2D operator*(const Vec2D v); Mat22 operator*(float n); Mat22 operator/(const Mat22 m); Mat22 operator/(float n); Mat22 operator+=(const Mat22 m); Mat22 operator-=(const Mat22 m); Mat22 operator*=(const Mat22 m); Mat22 operator/=(const Mat22 m); float m00; float m01; float m10; float m11; void Print() const; }; ostream& operator<<(ostream& o, Mat22 m); Mat22 operator*(float n, Mat22 m); Mat22 operator/(float n, Mat22 m); Mat22 GenRotMat22(float degree); #endif
23.374101
54
0.644814
VisualGMQ
1c4340895d9ff32d7ffa191d42ebd2c4e08e39ec
732
cpp
C++
anagram/anagram.cpp
aydinsimsek/exercism-solutions-cpp
6d7c8d37f628840559509d7f6e5b7788c8c637b6
[ "MIT" ]
1
2022-02-04T19:22:58.000Z
2022-02-04T19:22:58.000Z
anagram/anagram.cpp
aydinsimsek/exercism-solutions-cpp
6d7c8d37f628840559509d7f6e5b7788c8c637b6
[ "MIT" ]
null
null
null
anagram/anagram.cpp
aydinsimsek/exercism-solutions-cpp
6d7c8d37f628840559509d7f6e5b7788c8c637b6
[ "MIT" ]
null
null
null
#include "anagram.h" namespace anagram { anagram::anagram(string s) { word = s; } vector <string> anagram::matches(vector <string> v) { size_t w; for (int i = 0; i < v.size(); i++) { if (word.length() == v[i].length()) { temp1 = v[i]; for (int j = 0; j < v[i].length(); j++) { v[i][j] = tolower(v[i][j]); word[j] = tolower(word[j]); } temp2= v[i]; for (int j = 0; j < v[i].length(); j++) { w = temp2.find(word[j]); if (w == string::npos || word == v[i]) { break; } else { temp2.erase(w, 1); } } if (temp2.length() == 0) { vec.push_back(temp1); } } } return vec; } } // namespace anagram
17.023256
53
0.449454
aydinsimsek
1c49c154874b273a42fea95b7447dfd1476a38c6
2,902
cpp
C++
src/input.cpp
Bryankaveen/tanks-ce
27670778dbf6329b7fa4e69d12f8a4e5fa1f3ad9
[ "MIT" ]
14
2020-08-11T14:39:52.000Z
2022-02-08T21:17:56.000Z
src/input.cpp
commandblockguy/Tanks-CE
9eb79438a0ecd12cbde23be207257c650b703acb
[ "MIT" ]
1
2020-11-04T08:17:52.000Z
2020-11-05T22:41:46.000Z
src/input.cpp
commandblockguy/Tanks-CE
9eb79438a0ecd12cbde23be207257c650b703acb
[ "MIT" ]
1
2021-12-16T19:24:04.000Z
2021-12-16T19:24:04.000Z
#include "game.h" #include "gui/pause.h" #include "objects/tank.h" #include "util/profiler.h" #include <keypadc.h> #define PLAYER_BARREL_ROTATION DEGREES_TO_ANGLE(5) //1/3 of a second for 90 degree rotation #define PLAYER_TREAD_ROTATION (DEGREES_TO_ANGLE(90) / (TARGET_TICK_RATE / 3)) void handle_movement() { Tank *player = game.player; angle_t target_rot; uint8_t keys = 0; if(kb_IsDown(kb_KeyDown)) keys |= DOWN; if(kb_IsDown(kb_KeyLeft)) keys |= LEFT; if(kb_IsDown(kb_KeyRight)) keys |= RIGHT; if(kb_IsDown(kb_KeyUp)) keys |= UP; switch(keys) { default: player->set_velocity(0); return; case UP: target_rot = DEGREES_TO_ANGLE(270); break; case DOWN: target_rot = DEGREES_TO_ANGLE(90); break; case LEFT: target_rot = DEGREES_TO_ANGLE(180); break; case RIGHT: target_rot = DEGREES_TO_ANGLE(0); break; case UP | RIGHT: target_rot = DEGREES_TO_ANGLE(315); break; case DOWN | RIGHT: target_rot = DEGREES_TO_ANGLE(45); break; case UP | LEFT: target_rot = DEGREES_TO_ANGLE(225); break; case DOWN | LEFT: target_rot = DEGREES_TO_ANGLE(135); } int diff = player->tread_rot - target_rot; if((uint)abs(diff) > DEGREES_TO_ANGLE(90)) { player->tread_rot += DEGREES_TO_ANGLE(180); diff = (int) (player->tread_rot - target_rot); } if(diff < -(int) PLAYER_TREAD_ROTATION) { player->tread_rot += PLAYER_TREAD_ROTATION; } else if(diff > (int) PLAYER_TREAD_ROTATION) { player->tread_rot -= PLAYER_TREAD_ROTATION; } else { player->tread_rot = target_rot; } if((uint)abs(diff) <= DEGREES_TO_ANGLE(45)) { player->set_velocity(TANK_SPEED_NORMAL); } else { player->set_velocity(0); } } uint8_t handle_input() { profiler_start(input); Tank *player = game.player; handle_movement(); if(kb_IsDown(kb_Key2nd)) { player->fire_shell(); } if(kb_IsDown(kb_KeyAlpha)) { player->lay_mine(); } if(kb_IsDown(kb_KeyMode)) { player->barrel_rot -= PLAYER_BARREL_ROTATION; } if(kb_IsDown(kb_KeyGraphVar)) { player->barrel_rot += PLAYER_BARREL_ROTATION; } if(kb_IsDown(kb_KeyAdd)) { switch(pause_menu()) { default: case 0: break; case 1: // todo: restart case 2: return QUIT; } } if(kb_IsDown(kb_KeyDel)) { // TODO: remove return NEXT_LEVEL; } if(kb_IsDown(kb_KeyClear)) { return QUIT; } if(kb_IsDown(kb_KeyYequ)) { profiler_print(); } profiler_end(input); return 0; }
25.910714
77
0.569952
Bryankaveen
1c50b7b697cd116c9bd383da141940098b7b88dd
1,001
hpp
C++
branch_predictor/btb_set.hpp
thild/orcs
3cf377e5573e05843a15d338c29d595d95ed1495
[ "MIT" ]
null
null
null
branch_predictor/btb_set.hpp
thild/orcs
3cf377e5573e05843a15d338c29d595d95ed1495
[ "MIT" ]
null
null
null
branch_predictor/btb_set.hpp
thild/orcs
3cf377e5573e05843a15d338c29d595d95ed1495
[ "MIT" ]
null
null
null
#include <tuple> #include <cmath> using namespace std; class btb_set_t { public: btb_line_t *lines = NULL; uint8_t depth = 0; // ==================================================================== /// Methods // ==================================================================== // hit, target_address, opcode_address uint64_t search (uint32_t index, uint64_t opcode_address) { return lines[index].search(opcode_address); } void update (uint32_t index, uint64_t opcode_address, uint64_t target_address) { lines[index].update(opcode_address, target_address); } void allocate() { auto numlines = (uint16_t)pow (2, this->depth); this->lines = new btb_line_t[numlines]; } btb_set_t(uint8_t depth) { this->depth = depth; } ~btb_set_t() { if (this->lines) delete [] lines; } };
28.6
88
0.467532
thild
1c5164bdec19659eaffe195a7202c4bdcdd32ff4
1,463
cpp
C++
platforms/gfg/0455_k_maximum_sum_overlapping_contiguous_sub_arrays.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
2
2020-09-17T09:04:00.000Z
2020-11-20T19:43:18.000Z
platforms/gfg/0455_k_maximum_sum_overlapping_contiguous_sub_arrays.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
platforms/gfg/0455_k_maximum_sum_overlapping_contiguous_sub_arrays.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
#include "../../template.hpp" void GetKMaxSums(vi arr, int k) { int n = arr.size(); vi presum(n + 1); for (int i = 1; i <= n; ++i) { presum[i] = arr[i - 1] + presum[i - 1]; } vi sums; for (int i = 1; i <= n; ++i) { for (int j = i; j <= n; ++j) { sums.push_back(presum[j] - presum[i - 1]); } } sort(sums.rbegin(), sums.rend()); for (int i = 0; i < k; ++i) { cout << sums[i] << ' '; } cout << endl; } void GetKMaxSums2(vi arr, int k) { int n = arr.size(); vi presum(n + 1); for (int i = 1; i <= n; ++i) { presum[i] += arr[i - 1] + presum[i - 1]; } priority_queue<int, vector<int>, greater<int>> pq; for (int i = 1; i <= n; ++i) { for (int j = i; j <= n; ++j) { int sum = presum[j] - presum[i - 1]; if (pq.size() < k) { pq.push(sum); } else { if (pq.top() < sum) { pq.pop(); pq.push(sum); } } } } while (not pq.empty()) { cout << pq.top() << ' '; pq.pop(); } cout << endl; } int main() { TimeMeasure _; vi arr1 = {4, -8, 9, -4, 1, -8, -1, 6}; int k1 = 4; vi arr2 = {-2, -3, 4, -1, -2, 1, 5, -3}; int k2 = 3; GetKMaxSums(arr1, k1); GetKMaxSums(arr2, k2); cout << endl; GetKMaxSums2(arr1, k1); GetKMaxSums2(arr2, k2); }
24.383333
56
0.395079
idfumg
1c5287128a8e952846a5208fa07831366f7e1a2e
2,141
cpp
C++
src/logger/logger.cpp
gratonos/cxlog
1e2befb466d600545db3ad79cb0001f2f0056476
[ "MIT" ]
null
null
null
src/logger/logger.cpp
gratonos/cxlog
1e2befb466d600545db3ad79cb0001f2f0056476
[ "MIT" ]
null
null
null
src/logger/logger.cpp
gratonos/cxlog
1e2befb466d600545db3ad79cb0001f2f0056476
[ "MIT" ]
null
null
null
#include <cxlog/logger/logger.h> NAMESPACE_CXLOG_BEGIN void Logger::Log(Level level, const char *file, std::size_t line, const char *func, std::string &&msg) const { const Additional &additional = this->additional; std::vector<Context> contexts; contexts.reserve(additional.statics->size() + additional.dynamics->size()); for (StaticContext &context : *additional.statics) { contexts.emplace_back(Context{context.GetKey(), context.GetValue()}); } for (DynamicContext &context : *additional.dynamics) { contexts.emplace_back(Context{context.GetKey(), context.GetValue()}); } LockGuard lock(this->intrinsic->lock); Record record; record.time = Clock::now(); record.level = level; record.file = file; record.line = line; record.func = func; record.msg = std::move(msg); record.prefix = *additional.prefix; record.contexts = std::move(contexts); record.mark = additional.mark; if (additional.filter(record) && this->intrinsic->config.DoFilter(record)) { this->FormatAndWrite(level, record); } } void Logger::FormatAndWrite(Level level, const Record &record) const { const Intrinsic &intrinsic = *this->intrinsic; std::array<std::string, SlotCount> logs; for (std::size_t i = 0; i < SlotCount; i++) { const Slot &slot = intrinsic.slots[i]; if (slot.NeedToLog(level, record)) { std::string &log = logs[i]; if (log.empty()) { log = slot.Format(record); for (size_t n : intrinsic.equivalents[i]) { logs[n] = log; } } slot.Write(log, record); } } } void Logger::UpdateEquivalents() { Intrinsic &intrinsic = *this->intrinsic; for (std::size_t i = 0; i < SlotCount; i++) { intrinsic.equivalents[i].clear(); for (std::size_t j = i + 1; j < SlotCount; j++) { if (intrinsic.slots[i].GetFormatter() == intrinsic.slots[j].GetFormatter()) { intrinsic.equivalents[i].push_back(j); } } } } NAMESPACE_CXLOG_END
31.485294
89
0.601121
gratonos
1c545e6a82c9f3620c90a0f0cb67fffe2415267f
781
cpp
C++
Olympiad Solutions/DMOJ/bts17p4.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
Olympiad Solutions/DMOJ/bts17p4.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
Olympiad Solutions/DMOJ/bts17p4.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
// Ivan Carvalho // Solution to https://dmoj.ca/problem/bts17p4 #include <bits/stdc++.h> using namespace std; typedef pair<int,int> ii; vector<ii> todos; vector<int> menores; int N,M,J; int checa(int t){ menores.clear(); for(ii d : todos){ if(d.second <= t) menores.push_back(d.first); } sort(menores.begin(),menores.end()); int pos = 0; for(int i : menores){ if(i - pos <= J) pos = i; } if((N + 1) - pos <= J) return 1; return 0; } int main(){ scanf("%d %d %d",&N,&M,&J); while(M--){ int a,b; scanf("%d %d",&a,&b); todos.push_back(ii(a,b)); } int ini = 0, fim = 1000010 , meio, resp = -1; while(ini <= fim){ meio = (ini+fim)/2; if(checa(meio)){ resp = meio; fim = meio - 1; } else{ ini = meio + 1; } } printf("%d\n",resp); return 0; }
18.595238
47
0.567222
Ashwanigupta9125
1c551e9d9dd8a9379c999a289f2501eaa2dff666
22,647
cpp
C++
src/plugins/grass/qgsgrasstools.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/plugins/grass/qgsgrasstools.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/plugins/grass/qgsgrasstools.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgsgrasstools.cpp ------------------- begin : March, 2005 copyright : (C) 2005 by Radim Blazek email : blazek@itc.it ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "qgsgrasstools.h" #include "qgsgrassmodule.h" #include "qgsgrassregion.h" #include "qgsgrassshell.h" #include "qgsgrass.h" #include "qgsconfig.h" #include "qgisinterface.h" #include "qgsapplication.h" #include "qgslogger.h" #include "qgssettings.h" #include <QCloseEvent> #include <QDomDocument> #include <QFile> #include <QHeaderView> #include <QMessageBox> #include <QPainter> // // For experimental model view alternative ui by Tim // // #include "qgsdetaileditemdata.h" #include "qgsdetaileditemdelegate.h" #ifdef Q_OS_WIN #include "qgsgrassutils.h" #endif QgsGrassTools::QgsGrassTools( QgisInterface *iface, QWidget *parent, const char *name, Qt::WindowFlags f ) : QgsDockWidget( parent, f ) { Q_UNUSED( name ); QgsDebugMsg( "QgsGrassTools()" ); setupUi( this ); connect( mFilterInput, &QLineEdit::textChanged, this, &QgsGrassTools::mFilterInput_textChanged ); connect( mDebugButton, &QPushButton::clicked, this, &QgsGrassTools::mDebugButton_clicked ); connect( mCloseDebugButton, &QPushButton::clicked, this, &QgsGrassTools::mCloseDebugButton_clicked ); connect( mViewModeButton, &QToolButton::clicked, this, &QgsGrassTools::mViewModeButton_clicked ); QPushButton *closeMapsetButton = new QPushButton( QgsApplication::getThemeIcon( QStringLiteral( "mActionFileExit.svg" ) ), tr( "Close mapset" ), this ); mTabWidget->setCornerWidget( closeMapsetButton ); connect( closeMapsetButton, &QAbstractButton::clicked, this, &QgsGrassTools::closeMapset ); qRegisterMetaType<QgsDetailedItemData>(); mIface = iface; mCanvas = mIface->mapCanvas(); //statusBar()->hide(); // set the dialog title resetTitle(); // Tree view code. if ( !QgsGrass::modulesDebug() ) { mDebugWidget->hide(); } // List view mTreeModel = new QStandardItemModel( 0, 1 ); mTreeModelProxy = new QgsGrassToolsTreeFilterProxyModel( this ); mTreeModelProxy->setSourceModel( mTreeModel ); mTreeModelProxy->setFilterRole( Qt::UserRole + Search ); mTreeView->setModel( mTreeModelProxy ); connect( mTreeView, &QAbstractItemView::clicked, this, &QgsGrassTools::itemClicked ); // List view with filter mModulesListModel = new QStandardItemModel( 0, 1 ); mModelProxy = new QSortFilterProxyModel( this ); mModelProxy->setSourceModel( mModulesListModel ); mModelProxy->setFilterRole( Qt::UserRole + 2 ); mListView->setModel( mModelProxy ); connect( mListView, &QAbstractItemView::clicked, this, &QgsGrassTools::itemClicked ); mListView->hide(); connect( QgsGrass::instance(), &QgsGrass::modulesConfigChanged, this, static_cast<bool ( QgsGrassTools::* )()>( &QgsGrassTools::loadConfig ) ); connect( QgsGrass::instance(), &QgsGrass::modulesDebugChanged, this, &QgsGrassTools::debugChanged ); connect( mDebugReloadButton, &QAbstractButton::clicked, this, static_cast<bool ( QgsGrassTools::* )()>( &QgsGrassTools::loadConfig ) ); // Region widget tab mRegion = new QgsGrassRegion( mIface, this ); mTabWidget->addTab( mRegion, tr( "Region" ) ); // Show before loadConfig() so that user can see loading restorePosition(); showTabs(); } void QgsGrassTools::resetTitle() { QString title; if ( QgsGrass::activeMode() ) { title = tr( "GRASS Tools: %1/%2" ).arg( QgsGrass::getDefaultLocation(), QgsGrass::getDefaultMapset() ); } else { title = tr( "GRASS Tools" ); } setWindowTitle( title ); } void QgsGrassTools::showTabs() { resetTitle(); // Build modules tree if empty QgsDebugMsg( QString( "mTreeModel->rowCount() = %1" ).arg( mTreeModel->rowCount() ) ); if ( mTreeModel->rowCount() == 0 ) { // Load the modules lists QApplication::setOverrideCursor( Qt::WaitCursor ); loadConfig(); QApplication::restoreOverrideCursor(); QgsDebugMsg( QString( "mTreeModel->rowCount() = %1" ).arg( mTreeModel->rowCount() ) ); } // we always show tabs but disabled if not active if ( QgsGrass::activeMode() ) { mMessageLabel->hide(); mTabWidget->setEnabled( true ); } else { mMessageLabel->show(); mTabWidget->setEnabled( false ); } } void QgsGrassTools::runModule( QString name, bool direct ) { if ( name.length() == 0 ) { return; // Section } #ifdef HAVE_POSIX_OPENPT QgsGrassShell *sh = nullptr; #endif QWidget *m = nullptr; if ( name == QLatin1String( "shell" ) ) { #ifdef Q_OS_WIN QgsGrass::putEnv( "GRASS_HTML_BROWSER", QgsGrassUtils::htmlBrowserPath() ); QStringList env; QByteArray origPath = qgetenv( "PATH" ); QByteArray origPythonPath = qgetenv( "PYTHONPATH" ); QString path = QString( origPath ) + QgsGrass::pathSeparator() + QgsGrass::grassModulesPaths().join( QgsGrass::pathSeparator() ); QString pythonPath = QString( origPythonPath ) + QgsGrass::pathSeparator() + QgsGrass::getPythonPath(); QgsDebugMsg( "path = " + path ); QgsDebugMsg( "pythonPath = " + pythonPath ); qputenv( "PATH", path.toLocal8Bit() ); qputenv( "PYTHONPATH", pythonPath.toLocal8Bit() ); // QProcess does not support environment for startDetached() -> set/reset to orig if ( !QProcess::startDetached( getenv( "COMSPEC" ) ) ) { QMessageBox::warning( 0, "Warning", tr( "Cannot start command shell (%1)" ).arg( getenv( "COMSPEC" ) ) ); } qputenv( "PATH", origPath ); qputenv( "PYTHONPATH", origPythonPath ); return; #else #ifdef HAVE_POSIX_OPENPT sh = new QgsGrassShell( this, mTabWidget ); m = qobject_cast<QWidget *>( sh ); #else QMessageBox::warning( 0, tr( "Warning" ), tr( "GRASS Shell is not compiled." ) ); #endif #endif // Q_OS_WIN } else { // set wait cursor because starting module may be slow because of getting temporal datasets (t.list) QApplication::setOverrideCursor( Qt::WaitCursor ); QgsGrassModule *gmod = new QgsGrassModule( this, name, mIface, direct, mTabWidget ); QApplication::restoreOverrideCursor(); if ( !gmod->errors().isEmpty() ) { QgsGrass::warning( gmod->errors().join( QStringLiteral( "\n" ) ) ); } m = qobject_cast<QWidget *>( gmod ); } int height = mTabWidget->iconSize().height(); QString path = QgsGrass::modulesConfigDirPath() + "/" + name; QPixmap pixmap = QgsGrassModule::pixmap( path, height ); if ( !pixmap.isNull() ) { // Icon size in QT does not seem to be variable // -> reset the width to max icon width if ( mTabWidget->iconSize().width() < pixmap.width() ) { mTabWidget->setIconSize( QSize( pixmap.width(), mTabWidget->iconSize().height() ) ); } QIcon is; is.addPixmap( pixmap ); mTabWidget->addTab( m, is, QString() ); } else { mTabWidget->addTab( m, name ); } mTabWidget->setCurrentIndex( mTabWidget->count() - 1 ); // We must call resize to reset COLUMNS environment variable // used by bash !!! #if 0 /* TODO: Implement something that resizes the terminal without * crashes. */ #ifdef HAVE_POSIX_OPENPT if ( sh ) { sh->resizeTerminal(); } #endif #endif } bool QgsGrassTools::loadConfig() { QString conf = QgsGrass::modulesConfigDirPath() + "/default.qgc"; return loadConfig( conf, mTreeModel, mModulesListModel, false ); } bool QgsGrassTools::loadConfig( QString filePath, QStandardItemModel *treeModel, QStandardItemModel *modulesListModel, bool direct ) { QgsDebugMsg( filePath ); treeModel->clear(); modulesListModel->clear(); QFile file( filePath ); if ( !file.exists() ) { QMessageBox::warning( nullptr, tr( "Warning" ), tr( "The config file (%1) not found." ).arg( filePath ) ); return false; } if ( ! file.open( QIODevice::ReadOnly ) ) { QMessageBox::warning( nullptr, tr( "Warning" ), tr( "Cannot open config file (%1)." ).arg( filePath ) ); return false; } QDomDocument doc( QStringLiteral( "qgisgrass" ) ); QString err; int line, column; if ( !doc.setContent( &file, &err, &line, &column ) ) { QString errmsg = tr( "Cannot read config file (%1):" ).arg( filePath ) + tr( "\n%1\nat line %2 column %3" ).arg( err ).arg( line ).arg( column ); QgsDebugMsg( errmsg ); QMessageBox::warning( nullptr, tr( "Warning" ), errmsg ); file.close(); return false; } QDomElement docElem = doc.documentElement(); QDomNodeList modulesNodes = docElem.elementsByTagName( QStringLiteral( "modules" ) ); if ( modulesNodes.count() == 0 ) { file.close(); return false; } QDomNode modulesNode = modulesNodes.item( 0 ); QDomElement modulesElem = modulesNode.toElement(); // Go through the sections and modules and add them to the list view addModules( nullptr, modulesElem, treeModel, modulesListModel, false ); if ( direct ) { removeEmptyItems( treeModel ); } mTreeView->expandToDepth( 0 ); file.close(); return true; } void QgsGrassTools::debugChanged() { if ( QgsGrass::modulesDebug() ) { mDebugWidget->show(); } else { mDebugWidget->hide(); } } void QgsGrassTools::appendItem( QStandardItemModel *treeModel, QStandardItem *parent, QStandardItem *item ) { if ( parent ) { parent->appendRow( item ); } else if ( treeModel ) { treeModel->appendRow( item ); } } void QgsGrassTools::addModules( QStandardItem *parent, QDomElement &element, QStandardItemModel *treeModel, QStandardItemModel *modulesListModel, bool direct ) { QDomNode n = element.firstChild(); while ( !n.isNull() ) { QDomElement e = n.toElement(); if ( !e.isNull() ) { // QgsDebugMsg(QString("tag = %1").arg(e.tagName())); if ( e.tagName() != QLatin1String( "section" ) && e.tagName() != QLatin1String( "grass" ) ) { QgsDebugMsg( QString( "Unknown tag: %1" ).arg( e.tagName() ) ); continue; } // Check GRASS version QStringList errors; if ( !QgsGrassModuleOption::checkVersion( e.attribute( QStringLiteral( "version_min" ) ), e.attribute( QStringLiteral( "version_max" ) ), errors ) ) { // TODO: show somehow errors only in debug mode, but without reloading tree if ( !errors.isEmpty() ) { QString label = e.attribute( QStringLiteral( "label" ) ) + e.attribute( QStringLiteral( "name" ) ); // one should be non empty label += "\n ERROR:\t" + errors.join( QStringLiteral( "\n\t" ) ); QStandardItem *item = new QStandardItem( label ); item->setData( label, Qt::UserRole + Label ); item->setData( label, Qt::UserRole + Search ); item->setData( QgsApplication::getThemeIcon( QStringLiteral( "mIconWarning.svg" ) ), Qt::DecorationRole ); appendItem( treeModel, parent, item ); } n = n.nextSibling(); continue; } if ( e.tagName() == QLatin1String( "section" ) ) { QString label = QApplication::translate( "grasslabel", e.attribute( QStringLiteral( "label" ) ).toUtf8() ); QgsDebugMsg( QString( "label = %1" ).arg( label ) ); QStandardItem *item = new QStandardItem( label ); item->setData( label, Qt::UserRole + Label ); // original label, for debug item->setData( label, Qt::UserRole + Search ); // for filtering later addModules( item, e, treeModel, modulesListModel, direct ); appendItem( treeModel, parent, item ); } else if ( e.tagName() == QLatin1String( "grass" ) ) { // GRASS module QString name = e.attribute( QStringLiteral( "name" ) ); QgsDebugMsgLevel( QString( "name = %1" ).arg( name ), 1 ); //QString path = QgsApplication::pkgDataPath() + "/grass/modules/" + name; QString path = QgsGrass::modulesConfigDirPath() + "/" + name; QgsGrassModule::Description description = QgsGrassModule::description( path ); if ( !direct || description.direct ) { QString label = name + " - " + description.label; QPixmap pixmap = QgsGrassModule::pixmap( path, 32 ); QStandardItem *item = new QStandardItem( name + "\n" + description.label ); item->setData( name, Qt::UserRole + Name ); // for calling runModule later item->setData( label, Qt::UserRole + Label ); // original label, for debug item->setData( label, Qt::UserRole + Search ); // for filtering later item->setData( pixmap, Qt::DecorationRole ); item->setCheckable( false ); item->setEditable( false ); appendItem( treeModel, parent, item ); bool exists = false; for ( int i = 0; i < modulesListModel->rowCount(); i++ ) { if ( modulesListModel->item( i )->data( Qt::UserRole + Name ).toString() == name ) { exists = true; break; } } if ( !exists ) { QStandardItem *listItem = item->clone(); listItem->setText( name + "\n" + description.label ); // setData in the delegate with a variantised QgsDetailedItemData QgsDetailedItemData myData; myData.setTitle( name ); myData.setDetail( label ); myData.setIcon( pixmap ); myData.setCheckable( false ); myData.setRenderAsWidget( false ); QVariant myVariant = qVariantFromValue( myData ); listItem->setData( myVariant, Qt::UserRole ); modulesListModel->appendRow( listItem ); } } } } n = n.nextSibling(); } } // used for direct void QgsGrassTools::removeEmptyItems( QStandardItemModel *treeModel ) { // TODO: never tested if ( !treeModel ) { return; } // Clean tree nodes without children for ( int i = treeModel->rowCount() - 1; i >= 0; i-- ) { QStandardItem *item = treeModel->item( i ); removeEmptyItems( item ); if ( item->rowCount() == 0 ) { treeModel->removeRow( i ); } } } // used for direct void QgsGrassTools::removeEmptyItems( QStandardItem *item ) { // TODO: never tested for ( int i = item->rowCount() - 1; i >= 0; i-- ) { QStandardItem *sub = item->child( i ); removeEmptyItems( sub ); if ( sub->rowCount() == 0 ) { item->removeRow( i ); } } } void QgsGrassTools::closeMapset() { QgsGrass::instance()->closeMapsetWarn(); QgsGrass::saveMapset(); } void QgsGrassTools::mapsetChanged() { mTabWidget->setCurrentIndex( 0 ); closeTools(); mRegion->mapsetChanged(); showTabs(); } QgsGrassTools::~QgsGrassTools() { saveWindowLocation(); } QString QgsGrassTools::appDir( void ) { #if defined(Q_OS_WIN) return QgsGrass::shortPath( QgsApplication::applicationDirPath() ); #else return QgsApplication::applicationDirPath(); #endif } void QgsGrassTools::close( void ) { saveWindowLocation(); hide(); } void QgsGrassTools::closeEvent( QCloseEvent *e ) { saveWindowLocation(); e->accept(); } void QgsGrassTools::restorePosition() { QgsSettings settings; restoreGeometry( settings.value( QStringLiteral( "GRASS/windows/tools/geometry" ) ).toByteArray() ); show(); } void QgsGrassTools::saveWindowLocation() { QgsSettings settings; settings.setValue( QStringLiteral( "GRASS/windows/tools/geometry" ), saveGeometry() ); } void QgsGrassTools::emitRegionChanged() { emit regionChanged(); } void QgsGrassTools::closeTools() { for ( int i = mTabWidget->count() - 1; i > 1; i-- ) // first is module tree, second is region { delete mTabWidget->widget( i ); } } // // Helper function for Tim's experimental model list // void QgsGrassTools::mFilterInput_textChanged( QString text ) { QgsDebugMsg( "GRASS modules filter changed to :" + text ); mTreeModelProxy->setFilter( text ); if ( text.isEmpty() ) { mTreeView->collapseAll(); mTreeView->expandToDepth( 0 ); } else { mTreeView->expandAll(); } // using simple wildcard filter which is probably what users is expecting, at least until // there is a filter type switch in UI QRegExp::PatternSyntax mySyntax = QRegExp::PatternSyntax( QRegExp::Wildcard ); Qt::CaseSensitivity myCaseSensitivity = Qt::CaseInsensitive; QRegExp myRegExp( text, myCaseSensitivity, mySyntax ); mModelProxy->setFilterRegExp( myRegExp ); } void QgsGrassTools::itemClicked( const QModelIndex &index ) { QgsDebugMsg( "Entered" ); if ( index.column() == 0 ) { // // If the model has been filtered, the index row in the proxy won't match // the index row in the underlying model so we need to jump through this // little hoop to get the correct item // const QSortFilterProxyModel *proxyModel = qobject_cast<const QSortFilterProxyModel *>( index.model() ); if ( !proxyModel ) { return; } QModelIndex modelIndex = proxyModel->mapToSource( index ); QStandardItemModel *model = nullptr; if ( proxyModel == mTreeModelProxy ) { model = mTreeModel; } else { model = mModulesListModel; } QStandardItem *mypItem = model->itemFromIndex( modelIndex ); if ( mypItem ) { QString myModuleName = mypItem->data( Qt::UserRole + Name ).toString(); runModule( myModuleName, false ); } } } void QgsGrassTools::mDebugButton_clicked() { QApplication::setOverrideCursor( Qt::BusyCursor ); int errors = 0; for ( int i = 0; i < mTreeModel->rowCount(); i++ ) { errors += debug( mTreeModel->item( i ) ); } mDebugLabel->setText( tr( "%1 errors found" ).arg( errors ) ); QApplication::restoreOverrideCursor(); } int QgsGrassTools::debug( QStandardItem *item ) { if ( !item ) { return 0; } QString name = item->data( Qt::UserRole + Name ).toString(); QString label = item->data( Qt::UserRole + Label ).toString(); if ( name.isEmpty() ) // section { int errors = 0; for ( int i = 0; i < item->rowCount(); i++ ) { QStandardItem *sub = item->child( i ); errors += debug( sub ); } if ( errors > 0 ) { label += " ( " + tr( "%1 errors" ).arg( errors ) + " )"; item->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mIconWarning.svg" ) ) ); } else { item->setIcon( QIcon() ); } item->setText( label ); return errors; } else // module { if ( name == QLatin1String( "shell" ) ) { return 0; } QgsGrassModule *module = new QgsGrassModule( this, name, mIface, false ); QgsDebugMsg( QString( "module: %1 errors: %2" ).arg( name ).arg( module->errors().size() ) ); Q_FOREACH ( QString error, module->errors() ) { // each error may have multiple rows and may be html formatted (<br>) label += "\n ERROR:\t" + error.replace( QLatin1String( "<br>" ), QLatin1String( "\n" ) ).replace( QLatin1String( "\n" ), QLatin1String( "\n\t" ) ); } item->setText( label ); int nErrors = module->errors().size(); delete module; return nErrors; } } void QgsGrassTools::mCloseDebugButton_clicked() { QgsGrass::instance()->setModulesDebug( false ); } void QgsGrassTools::mViewModeButton_clicked() { if ( mTreeView->isHidden() ) { mListView->hide(); mTreeView->show(); mViewModeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mIconListView.svg" ) ) ); } else { mTreeView->hide(); mListView->show(); mViewModeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mIconTreeView.svg" ) ) ); } } QgsGrassToolsTreeFilterProxyModel::QgsGrassToolsTreeFilterProxyModel( QObject *parent ) : QSortFilterProxyModel( parent ) { setDynamicSortFilter( true ); mRegExp.setPatternSyntax( QRegExp::Wildcard ); mRegExp.setCaseSensitivity( Qt::CaseInsensitive ); } void QgsGrassToolsTreeFilterProxyModel::setSourceModel( QAbstractItemModel *sourceModel ) { mModel = sourceModel; QSortFilterProxyModel::setSourceModel( sourceModel ); } void QgsGrassToolsTreeFilterProxyModel::setFilter( const QString &filter ) { QgsDebugMsg( QString( "filter = %1" ).arg( filter ) ); if ( mFilter == filter ) { return; } mFilter = filter; mRegExp.setPattern( mFilter ); invalidateFilter(); } bool QgsGrassToolsTreeFilterProxyModel::filterAcceptsString( const QString &value ) const { return value.contains( mRegExp ); } bool QgsGrassToolsTreeFilterProxyModel::filterAcceptsRow( int sourceRow, const QModelIndex &sourceParent ) const { if ( mFilter.isEmpty() || !mModel ) { return true; } QModelIndex sourceIndex = mModel->index( sourceRow, 0, sourceParent ); return filterAcceptsItem( sourceIndex ) || filterAcceptsAncestor( sourceIndex ) || filterAcceptsDescendant( sourceIndex ); } bool QgsGrassToolsTreeFilterProxyModel::filterAcceptsAncestor( const QModelIndex &sourceIndex ) const { if ( !mModel ) { return true; } QModelIndex sourceParentIndex = mModel->parent( sourceIndex ); if ( !sourceParentIndex.isValid() ) return false; if ( filterAcceptsItem( sourceParentIndex ) ) return true; return filterAcceptsAncestor( sourceParentIndex ); } bool QgsGrassToolsTreeFilterProxyModel::filterAcceptsDescendant( const QModelIndex &sourceIndex ) const { if ( !mModel ) { return true; } for ( int i = 0; i < mModel->rowCount( sourceIndex ); i++ ) { QModelIndex sourceChildIndex = mModel->index( i, 0, sourceIndex ); if ( filterAcceptsItem( sourceChildIndex ) ) return true; if ( filterAcceptsDescendant( sourceChildIndex ) ) return true; } return false; } bool QgsGrassToolsTreeFilterProxyModel::filterAcceptsItem( const QModelIndex &sourceIndex ) const { if ( !mModel ) { return true; } return filterAcceptsString( mModel->data( sourceIndex, filterRole() ).toString() ); }
29.034615
159
0.634654
dyna-mis
1c5856d4b398bc8f8bf0bc558731f2f7feff1882
1,311
cpp
C++
c++/Test/GlobalData/weoExceptionMessageCreator.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
c++/Test/GlobalData/weoExceptionMessageCreator.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
c++/Test/GlobalData/weoExceptionMessageCreator.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
 //------------------------------------------------------------------- // include //------------------------------------------------------------------- #include "weoExceptionMessageCreator.h" #include <sstream> namespace pm_mode { /******************************************************************** * @brief 一定のフォーマットに法った文字列を作成する * @note ExceptionMessage に使用されることを前提としている * @param[in] message 何か残したい特別なメッセージ * @param[in] fileName 文字列を作成したファイルの名前 * @param[in] line 文字列を作成した行 * @param[in] function 文字列を作成した関数 * @return 情報をまとめた文字列 *******************************************************************/ std::string messageCreator(const std::string& message, bool isException, weString fileName, int line, weString function) throw() { std::stringstream ss; std::string returnValue; if (isException) { returnValue += "Exception is thrown!!!\nmessage: " + message; } else { returnValue += "Have Message!!!\nmessage: " + message; } returnValue.append("\nfile: "); returnValue.append(fileName); ss << line; returnValue += "\nline: "; returnValue += ss.str(); returnValue.append("\nfunction: "); returnValue.append(function); returnValue.append("\n"); return returnValue; } } // namespace pm_mode
26.755102
129
0.515637
taku-xhift
1c5b3de7fce16286f16fb22e379723f676ef5d50
546
hpp
C++
jmax/shader/Shader.hpp
JeanGamain/jmax
1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04
[ "MIT" ]
null
null
null
jmax/shader/Shader.hpp
JeanGamain/jmax
1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04
[ "MIT" ]
null
null
null
jmax/shader/Shader.hpp
JeanGamain/jmax
1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04
[ "MIT" ]
null
null
null
#ifndef SHADER_HPP_ #define SHADER_HPP_ #include "../jmax.hpp" #include <string> #include <vector> namespace jmax { class Shader { public: Shader(std::string const& filePath, GLenum shaderType = 0); virtual ~Shader(); public: static GLuint compileShaderFile(std::string const& shaderFilePath, GLenum shaderType); static GLenum Shader::getShaderType(std::string const& filePath); public: std::string const& filePath; const GLenum type; const GLuint shaderId; bool deleted; }; } // namespace jmax #endif /* !SHADER_HPP_ */
19.5
88
0.725275
JeanGamain
1c5b779943d9abe8389382f1717d224f7c402fef
816
cpp
C++
Linked List/Singly Linked List/Insert/add_at_front.cpp
dipanshuchaubey/competitive-coding
9b41f4693a30fdcf00b82db9aad5ced7d0dc454f
[ "MIT" ]
null
null
null
Linked List/Singly Linked List/Insert/add_at_front.cpp
dipanshuchaubey/competitive-coding
9b41f4693a30fdcf00b82db9aad5ced7d0dc454f
[ "MIT" ]
null
null
null
Linked List/Singly Linked List/Insert/add_at_front.cpp
dipanshuchaubey/competitive-coding
9b41f4693a30fdcf00b82db9aad5ced7d0dc454f
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class Node { public: Node *next; int data; }; void printList(Node *n) { while (n != NULL) { cout << n->data << "\t"; n = n->next; } } void insertAtFront(Node **start_node, int data) { Node *new_node = new Node(); new_node->data = data; new_node->next = *start_node; *start_node = new_node; } int main() { Node *first = new Node(); Node *second = new Node(); Node *third = new Node(); first->data = 1; first->next = second; second->data = 2; second->next = third; third->data = 3; third->next = NULL; cout << "Default List: \t"; printList(first); insertAtFront(&first, 0); cout << "\nList after inserting at front: \t"; printList(first); return 0; }
14.571429
50
0.551471
dipanshuchaubey
1c5c19ab2d119c2ccec4e995d72e9230b11a2b97
1,807
cpp
C++
src/LG/lg-P1659.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
1
2021-08-13T14:27:39.000Z
2021-08-13T14:27:39.000Z
src/LG/lg-P1659.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
null
null
null
src/LG/lg-P1659.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstring> #include <iostream> #define int long long const int MAX_N = 2000050; const int MOD = 19930726; std::string d, s; int re[MAX_N], cnt[MAX_N]; int n, nn, k; void init(); void manacher(); int quick_pow(int a, int b); signed main() { std::ios::sync_with_stdio(false); std::cin >> nn >> k >> s; int sum = 0, ans = 1; n = nn; init(); manacher(); for (int i = nn; i > 0; i--) { if (i % 2) { sum += cnt[i]; if (k >= sum) { ans *= quick_pow(i, sum); ans %= MOD; k -= sum; } else { ans *= quick_pow(i, k); ans %= MOD; k -= sum; break; } } else { continue; } } if (k > 0) { std::cout << -1 << '\n'; } else { std::cout << ans << '\n'; } return 0; } void init() { d.resize(2 * n + 10); d[0] = d[1] = 'A'; for (int i = 0; i < n; i++) { d[i * 2 + 2] = s[i]; d[i * 2 + 3] = 'A'; } n = 2 * n + 2; d[n] = 0; } void manacher() { int r = 0, mid = 0; for (int l = 1; l < n; l++) { if (l < r) { re[l] = std::min(re[mid * 2 - l], re[mid] + mid - l); } else { re[l] = 1; } while (d[l + re[l]] == d[l - re[l]]) { re[l]++; } if (re[l] + l > r) { r = re[l] + l; mid = l; } if ((re[l] - 1) % 2) { cnt[re[l] - 1]++; } } } int quick_pow(int a, int b) { a %= MOD; int res = 1; while (b) { if (b & 1) { res = res * a % MOD; } a = a * a % MOD; b >>= 1; } return res; }
17.891089
65
0.342557
krishukr
1c5d2d09af639b8b275c0a1e970826844b4512c4
129
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/doc/special_examples/Tutorial_sparse_example_details.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/special_examples/Tutorial_sparse_example_details.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/special_examples/Tutorial_sparse_example_details.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:338e6e57d5446ad622a48ab505a62e4ddf72367f1dd3bd9dee9773f0f43ab857 size 1576
32.25
75
0.883721
initialz
1c60fa930f611edaa3a07a5d07828882b70c0b10
974
cpp
C++
demo/src/main.cpp
fundies/Crash2D
40b14d4259d7cedeea27d46f7206b80a07a3327c
[ "MIT" ]
1
2017-05-25T13:49:18.000Z
2017-05-25T13:49:18.000Z
demo/src/main.cpp
fundies/SAT
40b14d4259d7cedeea27d46f7206b80a07a3327c
[ "MIT" ]
6
2016-09-27T22:57:13.000Z
2017-05-11T17:01:26.000Z
demo/src/main.cpp
fundies/SAT
40b14d4259d7cedeea27d46f7206b80a07a3327c
[ "MIT" ]
4
2016-09-29T01:19:44.000Z
2021-04-02T07:45:59.000Z
#include "MTVDemo.hpp" #include "BroadphaseDemo.hpp" int main(int argc, char **argv) { sf::RenderWindow window(sf::VideoMode(800, 600), "Crash2D Demo"); window.setFramerateLimit(60); Demo *demo = new MTVDemo(window); size_t demoId = 0; while (window.isOpen()) { // check all the window's events that were triggered since the last iteration of the loop sf::Event event; while (window.pollEvent(event)) { switch (event.type) { // "close requested" event: we close the window case sf::Event::Closed: window.close(); break; case sf::Event::KeyReleased: if (event.key.code == sf::Keyboard::Space) { delete demo; ++demoId; if (demoId > 1) demoId = 0; switch (demoId) { case 0: demo = new MTVDemo(window); break; case 1: demo = new BroadphaseDemo(window); break; } } break; default: break; } } demo->draw(); window.display(); } }
21.173913
91
0.596509
fundies
1c61f3b6817b5d6e4326b7725944537b55eeac20
1,007
cpp
C++
Exam Practice/dice.cpp
egmnklc/Egemen-Files
34d409fa593ec41fc0d2cb48e23658663a1a06db
[ "MIT" ]
null
null
null
Exam Practice/dice.cpp
egmnklc/Egemen-Files
34d409fa593ec41fc0d2cb48e23658663a1a06db
[ "MIT" ]
null
null
null
Exam Practice/dice.cpp
egmnklc/Egemen-Files
34d409fa593ec41fc0d2cb48e23658663a1a06db
[ "MIT" ]
null
null
null
#include "dice.h" #include "randgen.h" // implementation of dice class // written Jan 31, 1994, modified 5/10/94 to use RandGen class // modified 3/31/99 to move RandGen class here from .h file Dice::Dice(int sides) // postcondition: all private fields initialized { myRollCount = 0; mySides = sides; } int Dice::Roll() // postcondition: number of rolls updated // random 'die' roll returned { RandGen gen; // random number generator myRollCount= myRollCount + 1; // update # of times die rolled return gen.RandInt(1,mySides); // in range [1..mySides] } int Dice::NumSides() const // postcondition: return # of sides of die { return mySides; } int Dice::NumRolls() const // postcondition: return # of times die has been rolled { return myRollCount; } int Dice::MultipleRoll(int n) { int i = 0; unsigned int sum = 0; while (i < n) { sum += Roll(); i+=1; } return sum; }
20.55102
73
0.608739
egmnklc
1c6a083592b615ed772efc3dab21d3feb3c4330e
14,096
cpp
C++
Common/win32/ProxyResolver.cpp
JzHuai0108/bluefox-mlc-continuous-capture-avi
b04a2c80223c6f3afa15ca05ba3068f20702549a
[ "BSD-3-Clause" ]
null
null
null
Common/win32/ProxyResolver.cpp
JzHuai0108/bluefox-mlc-continuous-capture-avi
b04a2c80223c6f3afa15ca05ba3068f20702549a
[ "BSD-3-Clause" ]
null
null
null
Common/win32/ProxyResolver.cpp
JzHuai0108/bluefox-mlc-continuous-capture-avi
b04a2c80223c6f3afa15ca05ba3068f20702549a
[ "BSD-3-Clause" ]
null
null
null
#include "ProxyResolver.h" #if _WIN32_WINNT < 0x0602 // This stuff became available with Windows 8 # define WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE 0x01000000 # define WINHTTP_CALLBACK_FLAG_GETPROXYFORURL_COMPLETE WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE # define API_GET_PROXY_FOR_URL (6) #endif // #if _WIN32_WINNT < _WIN32_WINNT_WIN8 PFNWINHTTPGETPROXYFORURLEX ProxyResolver::s_pfnWinhttpGetProxyForUrlEx = NULL; PFNWINHTTPFREEPROXYLIST ProxyResolver::s_pfnWinhttpFreeProxyList = NULL; PFNWINHTTPCREATEPROXYRESOLVER ProxyResolver::s_pfnWinhttpCreateProxyResolver = NULL; PFNWINHTTPGETPROXYRESULT ProxyResolver::s_pfnWinhttpGetProxyResult = NULL; //----------------------------------------------------------------------------- ProxyResolver::ProxyResolver() : m_fInit( FALSE ), m_fExtendedAPI( FALSE ), m_dwError( ERROR_SUCCESS ), m_hEvent( 0 ) //----------------------------------------------------------------------------- { ZeroMemory( &m_wprProxyResult, sizeof( WINHTTP_PROXY_RESULT ) ); ZeroMemory( &m_wpiProxyInfo, sizeof( WINHTTP_PROXY_INFO ) ); HMODULE hWinhttp = GetModuleHandle( L"winhttp.dll" ); if( hWinhttp != NULL ) { s_pfnWinhttpGetProxyForUrlEx = ( PFNWINHTTPGETPROXYFORURLEX )GetProcAddress( hWinhttp, "WinHttpGetProxyForUrlEx" ); s_pfnWinhttpFreeProxyList = ( PFNWINHTTPFREEPROXYLIST )GetProcAddress( hWinhttp, "WinHttpFreeProxyResult" ); s_pfnWinhttpCreateProxyResolver = ( PFNWINHTTPCREATEPROXYRESOLVER )GetProcAddress( hWinhttp, "WinHttpCreateProxyResolver" ); s_pfnWinhttpGetProxyResult = ( PFNWINHTTPGETPROXYRESULT )GetProcAddress( hWinhttp, "WinHttpGetProxyResult" ); } m_fExtendedAPI = s_pfnWinhttpGetProxyForUrlEx && s_pfnWinhttpFreeProxyList && s_pfnWinhttpCreateProxyResolver && s_pfnWinhttpGetProxyResult; } //----------------------------------------------------------------------------- ProxyResolver::~ProxyResolver() //----------------------------------------------------------------------------- { if( m_wpiProxyInfo.lpszProxy != NULL ) { GlobalFree( m_wpiProxyInfo.lpszProxy ); } if( m_wpiProxyInfo.lpszProxyBypass != NULL ) { GlobalFree( m_wpiProxyInfo.lpszProxyBypass ); } if( m_fExtendedAPI ) { s_pfnWinhttpFreeProxyList( &m_wprProxyResult ); } if( m_hEvent != NULL ) { CloseHandle( m_hEvent ); } } //----------------------------------------------------------------------------- BOOL ProxyResolver::IsRecoverableAutoProxyError( _In_ DWORD dwError ) //----------------------------------------------------------------------------- { switch( dwError ) { case ERROR_SUCCESS: case ERROR_INVALID_PARAMETER: case ERROR_WINHTTP_AUTO_PROXY_SERVICE_ERROR: case ERROR_WINHTTP_AUTODETECTION_FAILED: case ERROR_WINHTTP_BAD_AUTO_PROXY_SCRIPT: case ERROR_WINHTTP_LOGIN_FAILURE: case ERROR_WINHTTP_OPERATION_CANCELLED: case ERROR_WINHTTP_TIMEOUT: case ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT: case ERROR_WINHTTP_UNRECOGNIZED_SCHEME: return TRUE; default: break; } return FALSE; } //----------------------------------------------------------------------------- VOID CALLBACK ProxyResolver::GetProxyCallBack( _In_ HINTERNET hResolver, _In_ DWORD_PTR dwContext, _In_ DWORD dwInternetStatus, _In_ PVOID pvStatusInformation, _In_ DWORD /*dwStatusInformationLength*/ ) //----------------------------------------------------------------------------- { ProxyResolver* pProxyResolver = ( ProxyResolver* )dwContext; if( ( dwInternetStatus != WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE && dwInternetStatus != WINHTTP_CALLBACK_STATUS_REQUEST_ERROR ) || pProxyResolver == NULL ) { return; } if( dwInternetStatus == WINHTTP_CALLBACK_STATUS_REQUEST_ERROR ) { WINHTTP_ASYNC_RESULT* pAsyncResult = ( WINHTTP_ASYNC_RESULT* )pvStatusInformation; if( pAsyncResult->dwResult != API_GET_PROXY_FOR_URL ) { return; } pProxyResolver->m_dwError = pAsyncResult->dwError; } else if( dwInternetStatus == WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE ) { pProxyResolver->m_dwError = s_pfnWinhttpGetProxyResult( hResolver, &pProxyResolver->m_wprProxyResult ); } if( hResolver != NULL ) { WinHttpCloseHandle( hResolver ); hResolver = NULL; } SetEvent( pProxyResolver->m_hEvent ); } #define CLOSE_RESOLVER_HANDLE_AND_RETURN_ERROR_CODE(HRESOLVER, ERROR_CODE) \ if( HRESOLVER != NULL ) \ { \ WinHttpCloseHandle( HRESOLVER ); \ } \ return ERROR_CODE //----------------------------------------------------------------------------- DWORD ProxyResolver::GetProxyForUrlEx( _In_ HINTERNET hSession, _In_z_ PCWSTR pwszUrl, _In_ WINHTTP_AUTOPROXY_OPTIONS* pAutoProxyOptions ) //----------------------------------------------------------------------------- { // Create proxy resolver handle. It's best to close the handle during call back. HINTERNET hResolver = NULL; DWORD dwError = s_pfnWinhttpCreateProxyResolver( hSession, &hResolver ); if( dwError != ERROR_SUCCESS ) { CLOSE_RESOLVER_HANDLE_AND_RETURN_ERROR_CODE( hResolver, dwError ); } // Sets up a callback function that WinHTTP can call as proxy results are resolved. WINHTTP_STATUS_CALLBACK wscCallback = WinHttpSetStatusCallback( hResolver, GetProxyCallBack, WINHTTP_CALLBACK_FLAG_REQUEST_ERROR | WINHTTP_CALLBACK_FLAG_GETPROXYFORURL_COMPLETE, 0 ); if( wscCallback == WINHTTP_INVALID_STATUS_CALLBACK ) { dwError = GetLastError(); CLOSE_RESOLVER_HANDLE_AND_RETURN_ERROR_CODE( hResolver, dwError ); } // The extended API works in asynchronous mode, therefore wait until the // results are set in the call back function. dwError = s_pfnWinhttpGetProxyForUrlEx( hResolver, pwszUrl, pAutoProxyOptions, ( DWORD_PTR )this ); if( dwError != ERROR_IO_PENDING ) { CLOSE_RESOLVER_HANDLE_AND_RETURN_ERROR_CODE( hResolver, dwError ); } // The resolver handle will get closed in the callback and cannot be used any longer. hResolver = NULL; dwError = WaitForSingleObjectEx( m_hEvent, INFINITE, FALSE ); if( dwError != WAIT_OBJECT_0 ) { return GetLastError(); } return m_dwError; } //----------------------------------------------------------------------------- _Success_( return == ERROR_SUCCESS ) DWORD ProxyResolver::GetProxyForAutoSettings( _In_ HINTERNET hSession, _In_z_ PCWSTR pwszUrl, _In_opt_z_ PCWSTR pwszAutoConfigUrl, _Outptr_result_maybenull_ PWSTR* ppwszProxy, _Outptr_result_maybenull_ PWSTR* ppwszProxyBypass ) //----------------------------------------------------------------------------- { DWORD dwError = ERROR_SUCCESS; WINHTTP_AUTOPROXY_OPTIONS waoOptions = {}; WINHTTP_PROXY_INFO wpiProxyInfo = {}; *ppwszProxy = NULL; *ppwszProxyBypass = NULL; if( pwszAutoConfigUrl ) { waoOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL; waoOptions.lpszAutoConfigUrl = pwszAutoConfigUrl; } else { waoOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT; waoOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A; } // First call with no autologon. Autologon prevents the // session (in proc) or autoproxy service (out of proc) from caching // the proxy script. This causes repetitive network traffic, so it is // best not to do autologon unless it is required according to the // result of WinHttpGetProxyForUrl. // This applies to both WinHttpGetProxyForUrl and WinhttpGetProxyForUrlEx. if( m_fExtendedAPI ) { m_hEvent = CreateEventEx( NULL, NULL, 0, EVENT_ALL_ACCESS ); if( m_hEvent == NULL ) { dwError = GetLastError(); goto quit; } dwError = GetProxyForUrlEx( hSession, pwszUrl, &waoOptions ); if( dwError != ERROR_WINHTTP_LOGIN_FAILURE ) { // Unless we need to retry with auto-logon exit the function with the // result, on success the proxy list will be stored in m_wprProxyResult // by GetProxyCallBack. goto quit; } // Enable autologon if challenged. waoOptions.fAutoLogonIfChallenged = TRUE; dwError = GetProxyForUrlEx( hSession, pwszUrl, &waoOptions ); goto quit; } if( !WinHttpGetProxyForUrl( hSession, pwszUrl, &waoOptions, &wpiProxyInfo ) ) { dwError = GetLastError(); if( dwError != ERROR_WINHTTP_LOGIN_FAILURE ) { goto quit; } // Enable autologon if challenged. dwError = ERROR_SUCCESS; waoOptions.fAutoLogonIfChallenged = TRUE; if( !WinHttpGetProxyForUrl( hSession, pwszUrl, &waoOptions, &wpiProxyInfo ) ) { dwError = GetLastError(); goto quit; } } *ppwszProxy = wpiProxyInfo.lpszProxy; wpiProxyInfo.lpszProxy = NULL; *ppwszProxyBypass = wpiProxyInfo.lpszProxyBypass; wpiProxyInfo.lpszProxyBypass = NULL; quit: if( wpiProxyInfo.lpszProxy ) { GlobalFree( wpiProxyInfo.lpszProxy ); wpiProxyInfo.lpszProxy = NULL; } if( wpiProxyInfo.lpszProxyBypass ) { GlobalFree( wpiProxyInfo.lpszProxyBypass ); wpiProxyInfo.lpszProxyBypass = NULL; } return dwError; } //----------------------------------------------------------------------------- DWORD ProxyResolver::ResolveProxy( _In_ HINTERNET hSession, _In_z_ PCWSTR pwszUrl ) //----------------------------------------------------------------------------- { DWORD dwError = ERROR_SUCCESS; WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ProxyConfig = {}; PWSTR pwszProxy = NULL; PWSTR pwszProxyBypass = NULL; BOOL fFailOverValid = FALSE; if( m_fInit ) { dwError = ERROR_INVALID_OPERATION; goto quit; } if( !WinHttpGetIEProxyConfigForCurrentUser( &ProxyConfig ) ) { dwError = GetLastError(); if( dwError != ERROR_FILE_NOT_FOUND ) { goto quit; } // No IE proxy settings found, just do autodetect. ProxyConfig.fAutoDetect = TRUE; dwError = ERROR_SUCCESS; } // Begin processing the proxy settings in the following order: // 1) Auto-Detect if configured. // 2) Auto-Config URL if configured. // 3) Static Proxy Settings if configured. // // Once any of these methods succeed in finding a proxy we are finished. // In the event one mechanism fails with an expected error code it is // required to fall back to the next mechanism. If the request fails // after exhausting all detected proxies, there should be no attempt // to discover additional proxies. if( ProxyConfig.fAutoDetect ) { fFailOverValid = TRUE; // Detect Proxy Settings. dwError = GetProxyForAutoSettings( hSession, pwszUrl, NULL, &pwszProxy, &pwszProxyBypass ); if( dwError == ERROR_SUCCESS ) { goto commit; } if( !IsRecoverableAutoProxyError( dwError ) ) { goto quit; } // Fall back to Autoconfig URL or Static settings. An application can // optionally take some action such as logging, or creating a mechanism // to expose multiple error codes in the class. dwError = ERROR_SUCCESS; } if( ProxyConfig.lpszAutoConfigUrl ) { fFailOverValid = TRUE; // Run autoproxy with AutoConfig URL. dwError = GetProxyForAutoSettings( hSession, pwszUrl, ProxyConfig.lpszAutoConfigUrl, &pwszProxy, &pwszProxyBypass ); if( dwError == ERROR_SUCCESS ) { goto commit; } if( !IsRecoverableAutoProxyError( dwError ) ) { goto quit; } // Fall back to Static Settings. An application can optionally take some // action such as logging, or creating a mechanism to to expose multiple // error codes in the class. dwError = ERROR_SUCCESS; } fFailOverValid = FALSE; // Static Proxy Config. Failover is not valid for static proxy since // it is always either a single proxy or a list containing protocol // specific proxies such as "proxy" or http=httpproxy;https=sslproxy pwszProxy = ProxyConfig.lpszProxy; ProxyConfig.lpszProxy = NULL; pwszProxyBypass = ProxyConfig.lpszProxyBypass; ProxyConfig.lpszProxyBypass = NULL; commit: if( pwszProxy == NULL ) { m_wpiProxyInfo.dwAccessType = WINHTTP_ACCESS_TYPE_NO_PROXY; } else { m_wpiProxyInfo.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY; } m_wpiProxyInfo.lpszProxy = pwszProxy; pwszProxy = NULL; m_wpiProxyInfo.lpszProxyBypass = pwszProxyBypass; pwszProxyBypass = NULL; m_fInit = TRUE; quit: if( pwszProxy != NULL ) { GlobalFree( pwszProxy ); pwszProxy = NULL; } if( pwszProxyBypass != NULL ) { GlobalFree( pwszProxyBypass ); pwszProxyBypass = NULL; } if( ProxyConfig.lpszAutoConfigUrl != NULL ) { GlobalFree( ProxyConfig.lpszAutoConfigUrl ); ProxyConfig.lpszAutoConfigUrl = NULL; } if( ProxyConfig.lpszProxy != NULL ) { GlobalFree( ProxyConfig.lpszProxy ); ProxyConfig.lpszProxy = NULL; } if( ProxyConfig.lpszProxyBypass != NULL ) { GlobalFree( ProxyConfig.lpszProxyBypass ); ProxyConfig.lpszProxyBypass = NULL; } return dwError; } //----------------------------------------------------------------------------- const WINHTTP_PROXY_RESULT_ENTRY* ProxyResolver::GetProxySetting( const DWORD index ) const //----------------------------------------------------------------------------- { if( index < m_wprProxyResult.cEntries ) { return &m_wprProxyResult.pEntries[index]; } return 0; }
34.380488
264
0.623936
JzHuai0108
1c6a8639fcb04a9a56098c34f080c26b14a84208
896
cpp
C++
UTSO/utso21p2.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
UTSO/utso21p2.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
UTSO/utso21p2.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() using namespace std; #ifndef ONLINE_JUDGE template<typename T> void pr(T a){std::cerr<<a<<std::endl;} template<typename T,typename... Args> void pr(T a, Args... args) {std::cerr<<a<<' ',pr(args...);} #else template<typename... Args> void pr(Args... args){} #endif int n, k; int main(){ cin>>k; for(int n = 1; n <= 101; n++){ assert(n != 101); int cur = n*(n-1)/2+n; vector<int> ans; for(int i = n; i > 0; i--){ int v = i*(i-1)/2+i; while(cur-v >= k){ cur -= v; if(size(ans)) ans.emplace_back(1); for(int j = 0; j < i; j++) ans.emplace_back(2); } } while(size(ans) < n) ans.emplace_back(1); if(size(ans) > n or cur != k) continue; // cout<<cur<<' '<<k<<endl; cout<<n<<'\n'; for(int i: ans) cout<<i<<' '; break; } }
18.666667
60
0.504464
crackersamdjam
1c6d2c7de9a44b122987529f4e6d173c3d381f35
1,127
cpp
C++
src/openloco/townmgr.cpp
Gymnasiast/OpenLoco
1bef36f96bcce0d6095d1b804a8d9f9df9651d07
[ "MIT" ]
null
null
null
src/openloco/townmgr.cpp
Gymnasiast/OpenLoco
1bef36f96bcce0d6095d1b804a8d9f9df9651d07
[ "MIT" ]
null
null
null
src/openloco/townmgr.cpp
Gymnasiast/OpenLoco
1bef36f96bcce0d6095d1b804a8d9f9df9651d07
[ "MIT" ]
null
null
null
#include "townmgr.h" #include "companymgr.h" #include "interop/interop.hpp" #include "openloco.h" using namespace openloco::interop; namespace openloco::townmgr { static loco_global_array<town, 80, 0x005B825C> _towns; std::array<town, max_towns>& towns() { auto arr = (std::array<town, max_towns>*)_towns.get(); return *arr; } town* get(town_id_t id) { if (id >= _towns.size()) { return nullptr; } return &_towns[id]; } // 0x00496B6D void update() { if ((addr<0x00525E28, uint32_t>() & 1) && !is_editor_mode()) { auto ticks = scenario_ticks(); if (ticks % 8 == 0) { town_id_t id = (ticks / 8) % 0x7F; auto town = get(id); if (town != nullptr && !town->empty()) { companymgr::updating_company_id(company_id::neutral); town->update(); } } } } // 0x0049748C void update_monthly() { call(0x0049748C); } }
21.673077
73
0.485359
Gymnasiast
1c6e0f7afc9d0a35fffd5410e137c10c3a38b07e
9,863
cpp
C++
src/opencv_ingestor.cpp
open-edge-insights/video-ingestion
189f50c73df6a2879de278f1232f14f291c8e6cf
[ "MIT" ]
7
2021-05-11T04:28:28.000Z
2022-03-29T00:39:39.000Z
src/opencv_ingestor.cpp
open-edge-insights/video-ingestion
189f50c73df6a2879de278f1232f14f291c8e6cf
[ "MIT" ]
1
2022-02-10T03:38:58.000Z
2022-02-10T03:38:58.000Z
src/opencv_ingestor.cpp
open-edge-insights/video-ingestion
189f50c73df6a2879de278f1232f14f291c8e6cf
[ "MIT" ]
6
2021-09-19T17:48:37.000Z
2022-03-22T04:22:48.000Z
// Copyright (c) 2019 Intel Corporation. // // 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. /** * @file * @brief OpenCV Ingestor implementation */ #include <string> #include <vector> #include <cerrno> #include <unistd.h> #include <eii/msgbus/msgbus.h> #include <eii/utils/logger.h> #include <eii/utils/json_config.h> #include "eii/vi/opencv_ingestor.h" using namespace eii::vi; using namespace eii::utils; using namespace eii::udf; #define PIPELINE "pipeline" #define LOOP_VIDEO "loop_video" #define UUID_LENGTH 5 OpenCvIngestor::OpenCvIngestor(config_t* config, FrameQueue* frame_queue, std::string service_name, std::condition_variable& snapshot_cv, EncodeType enc_type, int enc_lvl): Ingestor(config, frame_queue, service_name, snapshot_cv, enc_type, enc_lvl) { m_width = 0; m_height = 0; m_cap = NULL; m_encoding = false; m_loop_video = false; m_double_frames = false; m_initialized.store(true); config_value_t* cvt_double = config_get(config, "double_frames"); if (cvt_double != NULL) { LOG_DEBUG_0("DOUBLING FRAMES"); if (cvt_double->type != CVT_BOOLEAN) { config_value_destroy(cvt_double); LOG_ERROR_0("double_frames must be a boolean"); throw "ERROR"; } m_double_frames = cvt_double->body.boolean; config_value_destroy(cvt_double); } config_value_t* cvt_pipeline = config->get_config_value(config->cfg, PIPELINE); LOG_INFO("cvt_pipeline initialized"); if(cvt_pipeline == NULL) { const char* err = "JSON missing key"; LOG_ERROR("%s \'%s\'", err, PIPELINE); throw(err); } else if(cvt_pipeline->type != CVT_STRING) { config_value_destroy(cvt_pipeline); const char* err = "JSON value must be a string"; LOG_ERROR("%s for \'%s\'", err, PIPELINE); throw(err); } m_pipeline = std::string(cvt_pipeline->body.string); LOG_INFO("Pipeline: %s", m_pipeline.c_str()); config_value_destroy(cvt_pipeline); config_value_t* cvt_loop_video = config->get_config_value( config->cfg, LOOP_VIDEO); if(cvt_loop_video != NULL) { if(cvt_loop_video->type != CVT_BOOLEAN) { LOG_ERROR_0("Loop video must be a boolean"); config_value_destroy(cvt_loop_video); } if(cvt_loop_video->body.boolean) { m_loop_video = true; } config_value_destroy(cvt_loop_video); } m_cap = new cv::VideoCapture(m_pipeline); if(!m_cap->isOpened()) { LOG_ERROR("Failed to open gstreamer pipeline: %s", m_pipeline.c_str()); } } OpenCvIngestor::~OpenCvIngestor() { LOG_DEBUG_0("OpenCV ingestor destructor"); if(m_cap != NULL) { m_cap->release(); LOG_DEBUG_0("Cap deleted"); } } void free_cv_frame(void* obj) { cv::Mat* frame = (cv::Mat*) obj; frame->release(); delete frame; } void OpenCvIngestor::run(bool snapshot_mode) { // indicate that the run() function corresponding to the m_th thread has started m_running.store(true); LOG_INFO_0("Ingestor thread running publishing on stream"); Frame* frame = NULL; int64_t frame_count = 0; msg_envelope_elem_body_t* elem = NULL; try { while (!m_stop.load()) { this->read(frame); msg_envelope_t* meta_data = frame->get_meta_data(); // Profiling start DO_PROFILING(this->m_profile, meta_data, "ts_Ingestor_entry") // Profiling end msgbus_ret_t ret; if(frame_count == INT64_MAX) { LOG_WARN_0("frame count has reached INT64_MAX, so resetting \ it back to zero"); frame_count = 0; } frame_count++; elem = msgbus_msg_envelope_new_integer(frame_count); if (elem == NULL) { delete frame; const char* err = "Failed to create frame_number element"; LOG_ERROR("%s", err); throw err; } ret = msgbus_msg_envelope_put(meta_data, "frame_number", elem); if(ret != MSG_SUCCESS) { delete frame; const char* err = "Failed to put frame_number in meta-data"; LOG_ERROR("%s", err); throw err; } elem = NULL; LOG_DEBUG("Frame number: %ld", frame_count); // Profiling start DO_PROFILING(this->m_profile, meta_data, "ts_filterQ_entry") // Profiling end // Set encding type and level try { frame->set_encoding(m_enc_type, m_enc_lvl); } catch(const char *err) { LOG_ERROR("Exception: %s", err); } catch(...) { LOG_ERROR("Exception occurred in set_encoding()"); } QueueRetCode ret_queue = m_udf_input_queue->push(frame); if(ret_queue == QueueRetCode::QUEUE_FULL) { if(m_udf_input_queue->push_wait(frame) != QueueRetCode::SUCCESS) { LOG_ERROR_0("Failed to enqueue message, " "message dropped"); } // Add timestamp which acts as a marker if queue if blocked DO_PROFILING(this->m_profile, meta_data, m_ingestor_block_key.c_str()); } frame = NULL; if(snapshot_mode) { m_stop.store(true); m_snapshot_cv.notify_all(); } } } catch(const char* err) { LOG_ERROR("Exception: %s", err); if (elem != NULL) msgbus_msg_envelope_elem_destroy(elem); if(frame != NULL) delete frame; throw err; } catch(...) { LOG_ERROR("Exception occured in opencv ingestor run()"); if (elem != NULL) msgbus_msg_envelope_elem_destroy(elem); if(frame != NULL) delete frame; throw; } if (elem != NULL) msgbus_msg_envelope_elem_destroy(elem); if(frame != NULL) delete frame; LOG_INFO_0("Ingestor thread stopped"); if(snapshot_mode) m_running.store(false); } void OpenCvIngestor::read(Frame*& frame) { cv::Mat* cv_frame = new cv::Mat(); cv::Mat* frame_copy = NULL; if (m_cap == NULL) { m_cap = new cv::VideoCapture(m_pipeline); if(!m_cap->isOpened()) { LOG_ERROR("Failed to open gstreamer pipeline: %s", m_pipeline.c_str()); } } if(!m_cap->read(*cv_frame)) { if(cv_frame->empty()) { // cv_frame->empty signifies video has ended if(m_loop_video == true) { // Re-opening the video capture LOG_WARN_0("Video ended. Looping..."); m_cap->release(); delete m_cap; m_cap = new cv::VideoCapture(m_pipeline); } else { const char* err = "Video ended..."; LOG_WARN("%s", err); // Sleeping indefinitely to avoid restart while(true) { std::this_thread::sleep_for(std::chrono::seconds(5)); } } m_cap->read(*cv_frame); } else { // Error due to malformed frame const char* err = "Failed to read frame from OpenCV video capture"; LOG_ERROR("%s", err); } } LOG_DEBUG_0("Frame read successfully"); frame = new Frame( (void*) cv_frame, free_cv_frame, (void*) cv_frame->data, cv_frame->cols, cv_frame->rows, cv_frame->channels()); if (m_double_frames) { frame_copy = new cv::Mat(); *frame_copy = cv_frame->clone(); frame->add_frame( (void*) frame_copy, free_cv_frame, (void*) frame_copy->data, frame_copy->cols, frame_copy->rows, frame_copy->channels(), EncodeType::NONE, 0); } if(m_poll_interval > 0) { usleep(m_poll_interval * 1000 * 1000); } } void OpenCvIngestor::stop() { if(m_initialized.load()) { if(!m_stop.load()) { m_stop.store(true); // wait for the ingestor thread function run() to finish its execution. if(m_th != NULL) { m_th->join(); } } // After its made sure that the Ingestor run() function has been stopped (as in m_th-> join() above), m_stop flag is reset // so that the ingestor is ready for the next ingestion. m_running.store(false); m_stop.store(false); LOG_INFO_0("Releasing video capture object"); if(m_cap != NULL) { m_cap->release(); delete m_cap; m_cap = NULL; LOG_DEBUG_0("Capture object deleted"); } } }
33.433898
172
0.590794
open-edge-insights
cc6033dfeeb05bcadef587cf2cd59cd5542fc7f6
117,939
cpp
C++
Visual Mercutio/zModelBP/PSS_ProcedureSymbolBP.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
1
2022-01-31T06:24:24.000Z
2022-01-31T06:24:24.000Z
Visual Mercutio/zModelBP/PSS_ProcedureSymbolBP.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-04-11T15:50:42.000Z
2021-06-05T08:23:04.000Z
Visual Mercutio/zModelBP/PSS_ProcedureSymbolBP.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-01-08T00:55:18.000Z
2022-01-31T06:24:18.000Z
/**************************************************************************** * ==> PSS_ProcedureSymbolBP -----------------------------------------------* **************************************************************************** * Description : Provides a procedure symbol for banking process * * Developer : Processsoft * ****************************************************************************/ #include "stdafx.h" #include "PSS_ProcedureSymbolBP.h" // processsoft #include "zBaseLib\PSS_Tokenizer.h" #include "zBaseLib\PSS_Global.h" #include "zBaseLib\PSS_ToolbarObserverMsg.h" #include "zBaseLib\PSS_MsgBox.h" #include "zBaseLib\PSS_DrawFunctions.h" #include "zBaseSym\zBaseSymRes.h" #include "zModel\PSS_ModelGlobal.h" #include "zModel\PSS_UserGroupEntity.h" #include "zModel\PSS_ProcessGraphModelDoc.h" #include "zModel\PSS_SelectUserGroupDlg.h" #include "zModel\PSS_ODSymbolManipulator.h" #define _ZMODELEXPORT #include "zModel\PSS_BasicProperties.h" #undef _ZMODELEXPORT #include "zProperty\PSS_PropertyAttributes.h" #include "zProperty\PSS_PropertyObserverMsg.h" #include "PSS_DeliverableLinkSymbolBP.h" #include "PSS_RuleListPropertiesBP.h" #include "PSS_TaskListPropertiesBP.h" #include "PSS_DecisionListPropertiesBP.h" #include "PSS_CostPropertiesProcedureBP_Beta1.h" #include "PSS_UnitPropertiesBP_Beta1.h" #include "PSS_CombinationPropertiesBP.h" #include "PSS_SimPropertiesProcedureBP.h" #include "PSS_AddRemoveCombinationDeliverableDlg.h" #include "PSS_SelectMasterDeliverableDlg.h" #include "PSS_ProcessGraphModelControllerBP.h" #include "PSS_RiskOptionsDlg.h" // resources #include "zModelBPRes.h" #include "PSS_ModelResIDs.h" #include "zModel\zModelRes.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[] = __FILE__; #define new DEBUG_NEW #endif //--------------------------------------------------------------------------- // Global constants //--------------------------------------------------------------------------- const std::size_t g_MaxRuleListSize = 20; const std::size_t g_MaxTaskListSize = 20; const std::size_t g_MaxDecisionListSize = 20; const std::size_t g_MaxCombinationListSize = 20; const std::size_t g_MaxRulesSize = 20; const std::size_t g_MaxRisksSize = 20; //--------------------------------------------------------------------------- // Static variables //--------------------------------------------------------------------------- static CMenu g_CombinationMenu; static CMenu g_RulesMenu; static CMenu g_RiskMenu; //--------------------------------------------------------------------------- // Serialization //--------------------------------------------------------------------------- IMPLEMENT_SERIAL(PSS_ProcedureSymbolBP, PSS_Symbol, g_DefVersion) //--------------------------------------------------------------------------- // PSS_ProcedureSymbolBP //--------------------------------------------------------------------------- PSS_ProcedureSymbolBP::PSS_ProcedureSymbolBP(const CString& name) : PSS_Symbol(), m_Combinations(this) { ShowAttributeArea(true); PSS_Symbol::SetSymbolName(name); CreateSymbolProperties(); } //--------------------------------------------------------------------------- PSS_ProcedureSymbolBP::PSS_ProcedureSymbolBP(const PSS_ProcedureSymbolBP& other) { *this = other; } //--------------------------------------------------------------------------- PSS_ProcedureSymbolBP::~PSS_ProcedureSymbolBP() {} //--------------------------------------------------------------------------- PSS_ProcedureSymbolBP& PSS_ProcedureSymbolBP::operator = (const PSS_ProcedureSymbolBP& other) { PSS_Symbol::operator = ((const PSS_Symbol&)other); m_Combinations = other.m_Combinations; m_Rules = other.m_Rules; m_Risks = other.m_Risks; return *this; } //--------------------------------------------------------------------------- BOOL PSS_ProcedureSymbolBP::Create(const CString& name) { BOOL result = FALSE; try { m_IsInCreationProcess = true; result = PSS_Symbol::Create(IDR_BP_PROCEDURE, ::AfxFindResourceHandle(MAKEINTRESOURCE(IDR_PACKAGE_SYM), _T("Symbol")), name); if (!CreateSymbolProperties()) result = FALSE; } catch (...) { m_IsInCreationProcess = false; throw; } m_IsInCreationProcess = false; return result; } //--------------------------------------------------------------------------- CODComponent* PSS_ProcedureSymbolBP::Dup() const { return new PSS_ProcedureSymbolBP(*this); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::CopySymbolDefinitionFrom(const CODSymbolComponent& src) { PSS_Symbol::CopySymbolDefinitionFrom(src); const PSS_ProcedureSymbolBP* pProcedure = dynamic_cast<const PSS_ProcedureSymbolBP*>(&src); if (pProcedure) { m_Combinations = pProcedure->m_Combinations; m_Combinations.SetParent(this); m_SimulationProperties = pProcedure->m_SimulationProperties; m_UnitProp = pProcedure->m_UnitProp; m_CostProcedureProp = pProcedure->m_CostProcedureProp; m_Rules = pProcedure->m_Rules; m_Risks = pProcedure->m_Risks; m_CommentRect = pProcedure->m_CommentRect; // fill the unit double validation type array m_UnitDoubleValidationTypeArray.RemoveAll(); GetUnitDoubleValidationTypeStringArray(m_UnitDoubleValidationTypeArray); } } //--------------------------------------------------------------------------- BOOL PSS_ProcedureSymbolBP::SetSymbolName(const CString& value) { return PSS_Symbol::SetSymbolName(value); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::AcceptDropItem(CObject* pObj, const CPoint& point) { // don't allow the drop if the symbol isn't local if (!IsLocal()) return false; // is an user entity? if (pObj && ISA(pObj, PSS_UserGroupEntity)) return true; // is a rule? if (pObj && ISA(pObj, PSS_LogicalRulesEntity)) return true; return PSS_Symbol::AcceptDropItem(pObj, point); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::DropItem(CObject* pObj, const CPoint& point) { PSS_UserGroupEntity* pUserGroupEntity = dynamic_cast<PSS_UserGroupEntity*>(pObj); if (pUserGroupEntity) { PSS_ProcessGraphModelMdl* pModel = dynamic_cast<PSS_ProcessGraphModelMdl*>(GetRootModel()); // is the user group valid? if (pModel && !pModel->MainUserGroupIsValid()) { PSS_MsgBox mBox; mBox.Show(IDS_CANNOTDROP_USERGROUPNOTINLINE, MB_OK); return false; } SetUnitGUID(pUserGroupEntity->GetGUID()); SetUnitName(pUserGroupEntity->GetEntityName()); // change the unit cost SetUnitCost(pUserGroupEntity->GetEntityCost()); // set flag for modification SetModifiedFlag(TRUE); // refresh the attribute area and redraw the symbol RefreshAttributeTextArea(true); return true; } PSS_LogicalRulesEntity* pLogicalRulesEntity = dynamic_cast<PSS_LogicalRulesEntity*>(pObj); if (pLogicalRulesEntity) { PSS_ProcessGraphModelMdl* pModel = dynamic_cast<PSS_ProcessGraphModelMdl*>(GetRootModel()); // is the rule valid? if (pModel && !pModel->MainLogicalRulesIsValid()) { PSS_MsgBox mBox; mBox.Show(IDS_CANNOTDROP_RULENOTINLINE, MB_OK); return false; } std::unique_ptr<PSS_RulesPropertiesBP> pRuleProps(new PSS_RulesPropertiesBP()); pRuleProps->SetRuleName(pLogicalRulesEntity->GetEntityName()); pRuleProps->SetRuleDescription(pLogicalRulesEntity->GetEntityDescription()); pRuleProps->SetRuleGUID(pLogicalRulesEntity->GetGUID()); m_Rules.AddRule(pRuleProps.get()); pRuleProps.release(); // set the procedure symbol as modified SetModifiedFlag(TRUE); // refresh the attribute area and redraw the symbol RefreshAttributeTextArea(true); return true; } return PSS_Symbol::DropItem(pObj, point); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::AcceptExtApp() const { return true; } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::AcceptExtFile() const { return true; } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::CreateSymbolProperties() { if (!PSS_Symbol::CreateSymbolProperties()) return false; PSS_RuleListPropertiesBP propRules; AddProperty(propRules); PSS_TaskListPropertiesBP propTasks; AddProperty(propTasks); PSS_DecisionListPropertiesBP propDecisions; AddProperty(propDecisions); PSS_CostPropertiesProcedureBP_Beta1 propCost; AddProperty(propCost); PSS_UnitPropertiesBP_Beta1 propUnit; AddProperty(propUnit); // create at least one combination property m_Combinations.CreateInitialProperties(); // fill the unit double validation type array m_UnitDoubleValidationTypeArray.RemoveAll(); GetUnitDoubleValidationTypeStringArray(m_UnitDoubleValidationTypeArray); // create at least one risk property m_Risks.CreateInitialProperties(); return true; } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::FillProperties(PSS_Properties::IPropertySet& propSet, bool numericValues, bool groupValues) { // if no file, add a new one if (!GetExtFileCount()) AddNewExtFile(); // if no application, add a new one if (!GetExtAppCount()) AddNewExtApp(); // the "Name", "Description" and "Reference" properties of the "General" group can be found in the base class. // The "External Files" and "External Apps" properties are also available from there if (!PSS_Symbol::FillProperties(propSet, numericValues, groupValues)) return false; // only local symbol may access to properties if (!IsLocal()) return true; PSS_ProcessGraphModelMdl* pProcessGraphModel = dynamic_cast<PSS_ProcessGraphModelMdl*>(GetRootModel()); PSS_ProcessGraphModelDoc* pProcessGraphMdlDoc = pProcessGraphModel ? dynamic_cast<PSS_ProcessGraphModelDoc*>(pProcessGraphModel->GetDocument()) : NULL; // initialize the currency symbol with the user local currency symbol defined in the control panel CString currencySymbol = PSS_Global::GetLocaleCurrency(); // update the currency symbol according to the user selection if (pProcessGraphMdlDoc) currencySymbol = pProcessGraphMdlDoc->GetCurrencySymbol(); bool groupEnabled = true; if (pProcessGraphModel && !pProcessGraphModel->MainUserGroupIsValid()) groupEnabled = false; std::unique_ptr<PSS_Property> pProp; // if the rule menu isn't loaded, load it if (!g_RulesMenu.GetSafeHmenu()) g_RulesMenu.LoadMenu(IDR_RULES_MENU); const int ruleCount = m_Rules.GetRulesCount(); // fill the rule properties if (ruleCount) { CString ruleSectionTitle; ruleSectionTitle.LoadString(IDS_Z_RULES_TITLE); CString ruleDesc; ruleDesc.LoadString(IDS_Z_RULES_DESC); PSS_ProcessGraphModelMdlBP* pOwnerModel = dynamic_cast<PSS_ProcessGraphModelMdlBP*>(GetOwnerModel()); PSS_LogicalRulesEntity* pMainRule = NULL; // get the main rule if (pOwnerModel) { PSS_ProcessGraphModelControllerBP* pModelCtrl = dynamic_cast<PSS_ProcessGraphModelControllerBP*>(pOwnerModel->GetController()); if (pModelCtrl) { PSS_ProcessGraphModelDoc* pDoc = dynamic_cast<PSS_ProcessGraphModelDoc*>(pModelCtrl->GetDocument()); if (pDoc) pMainRule = pDoc->GetMainLogicalRules(); } } // iterate through the rules and add their properties for (int i = 0; i < ruleCount; ++i) { // the rule check can only be performed if the rules are synchronized with the referential if (pProcessGraphModel && pProcessGraphModel->MainLogicalRulesIsValid()) { const CString safeName = GetRuleNameByGUID(pMainRule, m_Rules.GetRuleGUID(i)); if (!safeName.IsEmpty() && safeName != m_Rules.GetRuleName(i)) m_Rules.SetRuleName(i, safeName); } CString ruleName; ruleName.Format(IDS_Z_RULES_NAME, i + 1); // the "Rule x" property of the "Rules" group pProp.reset(new PSS_Property(ruleSectionTitle, ZS_BP_PROP_RULES, ruleName, M_Rule_Name_ID + (i * g_MaxRulesSize), ruleDesc, m_Rules.GetRuleName(i), PSS_Property::IE_T_EditMenu, true, PSS_StringFormat(PSS_StringFormat::IE_FT_General), NULL, &g_RulesMenu)); pProp->EnableDragNDrop(); propSet.Add(pProp.get()); pProp.release(); } } // NOTE BE CAREFUL the previous rules architecture below has now changed, and is designed as controls, because // they became obsolete after the new rules system was implemented since November 2006. But as the two architectures // are too different one from the other, and the both needed to cohabit together, for compatibility reasons with the // previous serialization process, the texts referencing to the previous architecture were modified, and the "Rules" // words were replaced by "Controls" in the text resources, however the code side was not updated, due to a too huge // work to apply the changes. So if a new modification should be applied in the code, please be aware about this point PSS_RuleListPropertiesBP* pRulesProps; // add the rule if ((pRulesProps = static_cast<PSS_RuleListPropertiesBP*>(GetProperty(ZS_BP_PROP_RULELIST))) == NULL) { PSS_RuleListPropertiesBP propRules; AddProperty(propRules); // get it back pRulesProps = static_cast<PSS_RuleListPropertiesBP*>(GetProperty(ZS_BP_PROP_RULELIST)); if (!pRulesProps) return false; } CString propTitle; propTitle.LoadString(IDS_ZS_BP_PROP_RULELST_TITLE); CStringArray* pValueArray = PSS_Global::GetHistoricValueManager().GetFieldHistory(propTitle); CString propName; propName.LoadString(IDS_Z_RULE_LIST_NAME); CString propDesc; propDesc.LoadString(IDS_Z_RULE_LIST_DESC); CString finalPropName; int count = GetRuleCount() + 1; // iterate through all control properties, and define at least one control for (int i = 0; i < g_MaxRuleListSize; ++i) { finalPropName.Format(_T("%s %d"), propName, i + 1); // add control, if count is reached continue to add empty control until reaching the maximum size if (i < count) // the "Control x" property of the "Controls" group pProp.reset(new PSS_Property(propTitle, ZS_BP_PROP_RULELIST, finalPropName, M_Rule_List_ID + (i * g_MaxRuleListSize), propDesc, GetRuleAt(i), PSS_Property::IE_T_EditIntelli, true, PSS_StringFormat(PSS_StringFormat::IE_FT_General), pValueArray)); else // the "Control X" of the "Controls" group, but it is empty and not shown pProp.reset(new PSS_Property(propTitle, ZS_BP_PROP_RULELIST, finalPropName, M_Rule_List_ID + (i * g_MaxRuleListSize), propDesc, _T(""), PSS_Property::IE_T_EditIntelli, false, PSS_StringFormat(PSS_StringFormat::IE_FT_General), pValueArray)); pProp->EnableDragNDrop(); propSet.Add(pProp.get()); pProp.release(); } // load the risk menu if still not exists if (!g_RiskMenu.GetSafeHmenu()) g_RiskMenu.LoadMenu(IDR_RISK_MENU); CString riskTitle; riskTitle.LoadString(IDS_ZS_BP_PROP_RISK_TITLE); // iterate through the risks and add their properties for (int i = 0; i < GetRiskCount(); ++i) { CString finalRiskTitle; finalRiskTitle.Format(_T("%s (%d)"), riskTitle, i + 1); CString riskName; riskName.LoadString(IDS_Z_RISK_NAME_NAME); CString riskDesc; riskDesc.LoadString(IDS_Z_RISK_NAME_DESC); CString finalRiskName; // the "Risk title" property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_Name_ID : (M_Risk_Name_ID + (i * g_MaxRisksSize)), riskDesc, GetRiskName(i), PSS_Property::IE_T_EditMenu, true, PSS_StringFormat(PSS_StringFormat::IE_FT_General), NULL, &g_RiskMenu)); propSet.Add(pProp.get()); pProp.release(); riskName.LoadString(IDS_Z_RISK_DESC_NAME); riskDesc.LoadString(IDS_Z_RISK_DESC_DESC); // the "Description" property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_Desc_ID : (M_Risk_Desc_ID + (i * g_MaxRisksSize)), riskDesc, GetRiskDesc(i), PSS_Property::IE_T_EditExtended)); propSet.Add(pProp.get()); pProp.release(); riskName.LoadString(IDS_Z_RISK_TYPE_NAME); riskDesc.LoadString(IDS_Z_RISK_TYPE_DESC); CString sNoRiskType = _T(""); sNoRiskType.LoadString(IDS_NO_RISK_TYPE); // the "Type" property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_Type_ID : (M_Risk_Type_ID + (i * g_MaxRisksSize)), riskDesc, GetRiskType(i).IsEmpty() ? sNoRiskType : GetRiskType(i), PSS_Property::IE_T_EditExtendedReadOnly)); propSet.Add(pProp.get()); pProp.release(); riskName.LoadString(IDS_Z_RISK_IMPACT_NAME); riskDesc.LoadString(IDS_Z_RISK_IMPACT_DESC); PSS_Application* pApplication = PSS_Application::Instance(); PSS_MainForm* pMainForm = NULL; CString riskImpact; // get the risk impact string if (pApplication) { pMainForm = pApplication->GetMainForm(); if (pMainForm) { PSS_RiskImpactContainer* pContainer = pMainForm->GetRiskImpactContainer(); if (pContainer) riskImpact = pContainer->GetElementAt(GetRiskImpact(i)); } } // the "Impact" property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_Impact_ID : (M_Risk_Impact_ID + (i * g_MaxRisksSize)), riskDesc, riskImpact, PSS_Property::IE_T_EditExtendedReadOnly)); propSet.Add(pProp.get()); pProp.release(); riskName.LoadString(IDS_Z_RISK_PROBABILITY_NAME); riskDesc.LoadString(IDS_Z_RISK_PROBABILITY_DESC); CString riskProbability; if (pMainForm) { PSS_RiskProbabilityContainer* pContainer = pMainForm->GetRiskProbabilityContainer(); if (pContainer) riskProbability = pContainer->GetElementAt(GetRiskProbability(i)); } // the "Probability" property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_Probability_ID : (M_Risk_Probability_ID + (i * g_MaxRisksSize)), riskDesc, riskProbability, PSS_Property::IE_T_EditExtendedReadOnly)); propSet.Add(pProp.get()); pProp.release(); riskName.LoadString(IDS_Z_RISK_SEVERITY_NAME); riskDesc.LoadString(IDS_Z_RISK_SEVERITY_DESC); // the "Severity" property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_Severity_ID : (M_Risk_Severity_ID + (i * g_MaxRisksSize)), riskDesc, double(GetRiskSeverity(i)), PSS_Property::IE_T_EditNumberReadOnly)); propSet.Add(pProp.get()); pProp.release(); riskName.LoadString(IDS_Z_RISK_UE_NAME); riskDesc.LoadString(IDS_Z_RISK_UE_DESC); // the "Unit. est." property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_UE_ID : (M_Risk_UE_ID + (i * g_MaxRisksSize)), riskDesc, GetRiskUE(i), PSS_Property::IE_T_EditNumber, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol))); propSet.Add(pProp.get()); pProp.release(); riskName.LoadString(IDS_Z_RISK_POA_NAME); riskDesc.LoadString(IDS_Z_RISK_POA_DESC); // the "POA" property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_POA_ID : (M_Risk_POA_ID + (i * g_MaxRisksSize)), riskDesc, GetRiskPOA(i), PSS_Property::IE_T_EditNumber, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol))); propSet.Add(pProp.get()); pProp.release(); riskName.LoadString(IDS_Z_RISK_ACTION_NAME); riskDesc.LoadString(IDS_Z_RISK_ACTION_DESC); // the "Action" property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_Action_ID : (M_Risk_Action_ID + (i * g_MaxRisksSize)), riskDesc, GetRiskAction(i) ? PSS_Global::GetYesFromArrayYesNo() : PSS_Global::GetNoFromArrayYesNo(), PSS_Property::IE_T_ComboStringReadOnly, TRUE, PSS_StringFormat(PSS_StringFormat::IE_FT_General), PSS_Global::GetArrayYesNo())); propSet.Add(pProp.get()); pProp.release(); } // add tasks PSS_TaskListPropertiesBP* pTasksProps = static_cast<PSS_TaskListPropertiesBP*>(GetProperty(ZS_BP_PROP_TASKLIST)); if (!pTasksProps) return false; count = GetTaskCount() + 1; propTitle.LoadString(IDS_ZS_BP_PROP_PROCEDURE_TSKLST_TITLE); pValueArray = PSS_Global::GetHistoricValueManager().GetFieldHistory(propTitle); propName.LoadString(IDS_Z_TASK_LIST_NAME); propDesc.LoadString(IDS_Z_TASK_LIST_DESC); // iterate through all task properties, and define at least one task for (int i = 0; i < g_MaxTaskListSize; ++i) { finalPropName.Format(_T("%s %d"), propName, i + 1); // add task, if count is reached continue to add empty task until reaching the maximum size if (i < count) // the "Task x" property of the "Tasks" group pProp.reset(new PSS_Property(propTitle, ZS_BP_PROP_TASKLIST, finalPropName, M_Task_List_ID + (i * g_MaxTaskListSize), propDesc, GetTaskAt(i), PSS_Property::IE_T_EditIntelli, true, PSS_StringFormat(PSS_StringFormat::IE_FT_General), pValueArray)); else // the "Task x" property of the "Tasks" group, but empty and not shown pProp.reset(new PSS_Property(propTitle, ZS_BP_PROP_TASKLIST, finalPropName, M_Task_List_ID + (i * g_MaxTaskListSize), propDesc, _T(""), PSS_Property::IE_T_EditIntelli, false, PSS_StringFormat(PSS_StringFormat::IE_FT_General), pValueArray)); pProp->EnableDragNDrop(); propSet.Add(pProp.get()); pProp.release(); } // get the decisions PSS_DecisionListPropertiesBP* pDecisionsProps = static_cast<PSS_DecisionListPropertiesBP*>(GetProperty(ZS_BP_PROP_DECISIONLIST)); if (!pDecisionsProps) return false; count = GetDecisionCount() + 1; propTitle.LoadString(IDS_ZS_BP_PROP_PROCEDURE_DECLST_TITLE); pValueArray = PSS_Global::GetHistoricValueManager().GetFieldHistory(propTitle); propName.LoadString(IDS_Z_DECISION_LIST_NAME); propDesc.LoadString(IDS_Z_DECISION_LIST_DESC); // iterate through all decision properties, and define at least one decision for (int i = 0; i < g_MaxDecisionListSize; ++i) { finalPropName.Format(_T("%s %d"), propName, i + 1); // add decision, if count is reached continue to add empty decision until reaching the maximum size if (i < count) // the "Decision x" property of the "Decisions" group pProp.reset(new PSS_Property(propTitle, ZS_BP_PROP_DECISIONLIST, finalPropName, M_Decision_List_ID + (i * g_MaxDecisionListSize), propDesc, GetDecisionAt(i), PSS_Property::IE_T_EditIntelli, true, PSS_StringFormat(PSS_StringFormat::IE_FT_General), pValueArray)); else // the "Decision x" property of the "Decisions" group, but it is empty and not shown pProp.reset(new PSS_Property(propTitle, ZS_BP_PROP_DECISIONLIST, finalPropName, M_Decision_List_ID + (i * g_MaxDecisionListSize), propDesc, _T(""), PSS_Property::IE_T_EditIntelli, false, PSS_StringFormat(PSS_StringFormat::IE_FT_General), pValueArray)); pProp->EnableDragNDrop(); propSet.Add(pProp.get()); pProp.release(); } int hourPerDay = -1; int dayPerWeek = -1; int dayPerMonth = -1; int dayPerYear = -1; // get the standard time if (pProcessGraphMdlDoc) { hourPerDay = pProcessGraphMdlDoc->GetHourPerDay(); dayPerWeek = pProcessGraphMdlDoc->GetDayPerWeek(); dayPerMonth = pProcessGraphMdlDoc->GetDayPerMonth(); dayPerYear = pProcessGraphMdlDoc->GetDayPerYear(); } bool error; // do add the procedure and processing unit properties? if (pProcessGraphModel && pProcessGraphModel->GetIntegrateCostSimulation()) { // the "Multiplier" property of the "Procedure" group pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE, ZS_BP_PROP_PROCEDURE_COST, IDS_Z_COST_MULTIPLIER_NAME, M_Cost_Proc_Multiplier_ID, IDS_Z_COST_MULTIPLIER_DESC, GetMultiplier(), PSS_Property::IE_T_EditNumber, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Accounting, true, -1))); propSet.Add(pProp.get()); pProp.release(); // the "Standard time" property of the "Procedure" group if (numericValues) pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE, ZS_BP_PROP_PROCEDURE_COST, IDS_Z_COST_PROCESSING_TIME_NAME, M_Cost_Proc_Processing_Time_ID, IDS_Z_COST_PROCESSING_TIME_DESC, GetProcessingTime(), PSS_Property::IE_T_EditNumber)); else pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE, ZS_BP_PROP_PROCEDURE_COST, IDS_Z_COST_PROCESSING_TIME_NAME, M_Cost_Proc_Processing_Time_ID, IDS_Z_COST_PROCESSING_TIME_DESC, PSS_Duration(GetProcessingTime(), hourPerDay, dayPerWeek, dayPerMonth, dayPerYear), PSS_Property::IE_T_EditDuration, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Duration7))); propSet.Add(pProp.get()); pProp.release(); // the "Unitary cost" property of the "Procedure" group pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE, ZS_BP_PROP_PROCEDURE_COST, IDS_Z_COST_UNITARY_COST_NAME, M_Cost_Proc_Unitary_Cost_ID, IDS_Z_COST_UNITARY_COST_DESC, GetUnitaryCost(), PSS_Property::IE_T_EditNumber, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol))); propSet.Add(pProp.get()); pProp.release(); // the "Average duration (weighted)" property of the "Procedure" group if (numericValues) pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE, ZS_BP_PROP_PROCEDURE_COST, IDS_Z_COST_PROCESSING_DURATION_NAME, M_Cost_Proc_Processing_Duration_ID, IDS_Z_COST_PROCESSING_DURATION_DESC, GetProcessingDuration(), PSS_Property::IE_T_EditNumber)); else pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE, ZS_BP_PROP_PROCEDURE_COST, IDS_Z_COST_PROCESSING_DURATION_NAME, M_Cost_Proc_Processing_Duration_ID, IDS_Z_COST_PROCESSING_DURATION_DESC, PSS_Duration(GetProcessingDuration(), hourPerDay, dayPerWeek, dayPerMonth, dayPerYear), PSS_Property::IE_T_EditDurationReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Duration7))); propSet.Add(pProp.get()); pProp.release(); // the "Average duration (max)" property of the "Procedure" group if (numericValues) pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE, ZS_BP_PROP_PROCEDURE_COST, IDS_Z_COST_PROCESSING_DURATIONMAX_NAME, M_Cost_Proc_Processing_Duration_Max_ID, IDS_Z_COST_PROCESSING_DURATIONMAX_DESC, GetProcessingDurationMax(), PSS_Property::IE_T_EditNumber)); else pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE, ZS_BP_PROP_PROCEDURE_COST, IDS_Z_COST_PROCESSING_DURATIONMAX_NAME, M_Cost_Proc_Processing_Duration_Max_ID, IDS_Z_COST_PROCESSING_DURATIONMAX_DESC, PSS_Duration(GetProcessingDurationMax(), hourPerDay, dayPerWeek, dayPerMonth, dayPerYear), PSS_Property::IE_T_EditDurationReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Duration7))); propSet.Add(pProp.get()); pProp.release(); // get the unit cost const float unitCost = RetrieveUnitCost(GetUnitGUID(), error); // the "Cost" property of the "Processing unit" group pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_UNIT_TITLE, ZS_BP_PROP_UNIT, IDS_Z_UNIT_COST_NAME, M_Unit_Cost_ID, IDS_Z_UNIT_COST_DESC, unitCost, PSS_Property::IE_T_EditNumberReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol))); propSet.Add(pProp.get()); pProp.release(); // the "Double validation" property of the "Processing unit" group if (numericValues) pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_UNIT_TITLE, ZS_BP_PROP_UNIT, IDS_Z_UNIT_DOUBLE_VALIDATION_NAME, M_Unit_Double_Validation_ID, IDS_Z_UNIT_DOUBLE_VALIDATION_DESC, double(GetUnitDoubleValidationType()), PSS_Property::IE_T_EditNumber, false, PSS_StringFormat(PSS_StringFormat::IE_FT_General))); else pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_UNIT_TITLE, ZS_BP_PROP_UNIT, IDS_Z_UNIT_DOUBLE_VALIDATION_NAME, M_Unit_Double_Validation_ID, IDS_Z_UNIT_DOUBLE_VALIDATION_DESC, GetUnitDoubleValidationTypeString(GetUnitDoubleValidationType()), PSS_Property::IE_T_ComboStringReadOnly, false, PSS_StringFormat(PSS_StringFormat::IE_FT_General), &m_UnitDoubleValidationTypeArray)); propSet.Add(pProp.get()); pProp.release(); } // the "Guid" property of the "Processing unit" group. This property isn't enabled, just used for write the unit GUID. // NOTE "GUID" and "Name" properties should appear in Conceptor pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_UNIT_TITLE, ZS_BP_PROP_UNIT, IDS_Z_UNIT_GUID_NAME, M_Unit_GUID_ID, IDS_Z_UNIT_GUID_DESC, GetUnitGUID(), PSS_Property::IE_T_EditExtendedReadOnly, false)); propSet.Add(pProp.get()); pProp.release(); // get the unit name const CString unitName = RetrieveUnitName(GetUnitGUID(), error); // the "Unit" property of the "Processing unit" group pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_UNIT_TITLE, ZS_BP_PROP_UNIT, IDS_Z_UNIT_NAME_NAME, M_Unit_Name_ID, IDS_Z_UNIT_NAME_DESC, unitName, groupEnabled ? PSS_Property::IE_T_EditExtendedReadOnly : PSS_Property::IE_T_EditStringReadOnly)); propSet.Add(pProp.get()); pProp.release(); // if the combination menu is not loaded, load it if (!g_CombinationMenu.GetSafeHmenu()) g_CombinationMenu.LoadMenu(IDR_COMBINATION_MENU); // the combination properties should appear only in Messenger if (pProcessGraphModel && pProcessGraphModel->GetIntegrateCostSimulation()) { CString finalPropTitle; count = GetCombinationCount(); propTitle.LoadString(IDS_ZS_BP_PROP_COMBINATION_TITLE); // necessary to check if the initial combination is correct CheckInitialCombination(); // iterate through all combination properties for (int i = 0; i < count; ++i) { finalPropTitle.Format(_T("%s (%d)"), propTitle, i + 1); propName.LoadString(IDS_Z_COMBINATION_NAME_NAME); propDesc.LoadString(IDS_Z_COMBINATION_NAME_DESC); // the "Combination title" property of the "Combination x" group pProp.reset(new PSS_Property(finalPropTitle, groupValues ? ZS_BP_PROP_COMBINATION : (ZS_BP_PROP_COMBINATION + i), propName, groupValues ? M_Combination_Name_ID : (M_Combination_Name_ID + (i * g_MaxCombinationListSize)), propDesc, GetCombinationName(i), PSS_Property::IE_T_EditMenu, true, PSS_StringFormat(PSS_StringFormat::IE_FT_General), NULL, &g_CombinationMenu)); propSet.Add(pProp.get()); pProp.release(); propName.LoadString(IDS_Z_COMBINATION_DELIVERABLES_NAME); propDesc.LoadString(IDS_Z_COMBINATION_DELIVERABLES_DESC); // the "Deliverables" property of the "Combination x" group pProp.reset(new PSS_Property(finalPropTitle, groupValues ? ZS_BP_PROP_COMBINATION : (ZS_BP_PROP_COMBINATION + i), propName, groupValues ? M_Combination_Deliverables_ID : (M_Combination_Deliverables_ID + (i * g_MaxCombinationListSize)), propDesc, GetCombinationDeliverables(i), PSS_Property::IE_T_EditExtendedReadOnly)); propSet.Add(pProp.get()); pProp.release(); propName.LoadString(IDS_Z_COMBINATION_ACTIVATION_PERC_NAME); propDesc.LoadString(IDS_Z_COMBINATION_ACTIVATION_PERC_DESC); // get the percentage const float maxPercent = GetMaxActivationPerc(GetCombinationMaster(i)); // the "Percentage" property of the "Combination x" group pProp.reset(new PSS_Property(finalPropTitle, groupValues ? ZS_BP_PROP_COMBINATION : (ZS_BP_PROP_COMBINATION + i), propName, groupValues ? M_Combination_Activation_Perc_ID : (M_Combination_Activation_Perc_ID + (i * g_MaxCombinationListSize)), propDesc, maxPercent, PSS_Property::IE_T_EditNumberReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Percentage))); propSet.Add(pProp.get()); pProp.release(); propName.LoadString(IDS_Z_COMBINATION_MASTER_NAME); propDesc.LoadString(IDS_Z_COMBINATION_MASTER_DESC); // the "Master" property of the "Combination x" group pProp.reset(new PSS_Property(finalPropTitle, groupValues ? ZS_BP_PROP_COMBINATION : (ZS_BP_PROP_COMBINATION + i), propName, groupValues ? M_Combination_Master_ID : (M_Combination_Master_ID + (i * g_MaxCombinationListSize)), propDesc, GetCombinationMaster(i), PSS_Property::IE_T_EditExtendedReadOnly)); propSet.Add(pProp.get()); pProp.release(); } } if (pProcessGraphModel && pProcessGraphModel->GetIntegrateCostSimulation()) { // get the procedure activation value const double value = double(CalculateProcedureActivation()); // the "Activation" property of the "Calculations and forecasts" group pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE, ZS_BP_PROP_SIM_PROCEDURE, IDS_Z_SIM_PROCEDURE_ACTIVATION_NAME, M_Sim_Procedure_Activation_ID, IDS_Z_SIM_PROCEDURE_ACTIVATION_DESC, value, PSS_Property::IE_T_EditNumberReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Accounting, true, 0))); propSet.Add(pProp.get()); pProp.release(); // the "HMO cost" property of the "Calculations and forecasts" group pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE, ZS_BP_PROP_SIM_PROCEDURE, IDS_Z_SIM_PROCEDURE_COST_NAME, M_Sim_Procedure_Cost_ID, IDS_Z_SIM_PROCEDURE_COST_DESC, double(GetProcedureCost()), PSS_Property::IE_T_EditNumberReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol))); propSet.Add(pProp.get()); pProp.release(); // the "Charge" property of the "Calculations and forecasts" group if (numericValues) pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE, ZS_BP_PROP_SIM_PROCEDURE, IDS_Z_SIM_PROCEDURE_WORKLOAD_FORECAST_NAME, M_Sim_Procedure_Workload_Forecast_ID, IDS_Z_SIM_PROCEDURE_WORKLOAD_FORECAST_DESC, double(GetProcedureWorkloadForecast()), PSS_Property::IE_T_EditNumber)); else pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE, ZS_BP_PROP_SIM_PROCEDURE, IDS_Z_SIM_PROCEDURE_WORKLOAD_FORECAST_NAME, M_Sim_Procedure_Workload_Forecast_ID, IDS_Z_SIM_PROCEDURE_WORKLOAD_FORECAST_DESC, PSS_Duration(double(GetProcedureWorkloadForecast()), hourPerDay, dayPerWeek, dayPerMonth, dayPerYear), PSS_Property::IE_T_EditDurationReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Duration7))); propSet.Add(pProp.get()); pProp.release(); // the "Cost" property of the "Calculations and forecasts" group pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE, ZS_BP_PROP_SIM_PROCEDURE, IDS_Z_SIM_PROCEDURE_COST_FORECAST_NAME, M_Sim_Procedure_Cost_Forecast_ID, IDS_Z_SIM_PROCEDURE_COST_FORECAST_DESC, double(GetProcedureCostForecast()), PSS_Property::IE_T_EditNumberReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol))); propSet.Add(pProp.get()); pProp.release(); // the "Charge / activation" property of the "Calculations and forecasts" group if (numericValues) pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE, ZS_BP_PROP_SIM_PROCEDURE, IDS_Z_SIM_PROCEDURE_WORKLOAD_P_ACTIV_NAME, M_Sim_Procedure_Workload_Per_Activ_ID, IDS_Z_SIM_PROCEDURE_WORKLOAD_P_ACTIV_DESC, double(GetProcedureWorkloadPerActivity()), PSS_Property::IE_T_EditNumber)); else pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE, ZS_BP_PROP_SIM_PROCEDURE, IDS_Z_SIM_PROCEDURE_WORKLOAD_P_ACTIV_NAME, M_Sim_Procedure_Workload_Per_Activ_ID, IDS_Z_SIM_PROCEDURE_WORKLOAD_P_ACTIV_DESC, PSS_Duration(double(GetProcedureWorkloadPerActivity()), hourPerDay, dayPerWeek, dayPerMonth, dayPerYear), PSS_Property::IE_T_EditDurationReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Duration7))); propSet.Add(pProp.get()); pProp.release(); // the "Cost / activation" property of the "Calculations and forecasts" group pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE, ZS_BP_PROP_SIM_PROCEDURE, IDS_Z_SIM_PROCEDURE_COST_P_ACTIV_NAME, M_Sim_Procedure_Cost_Per_Activ_ID, IDS_Z_SIM_PROCEDURE_COST_P_ACTIV_DESC, GetProcedureCostPerActivity(), PSS_Property::IE_T_EditNumberReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol))); propSet.Add(pProp.get()); pProp.release(); } return true; } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::SaveProperties(PSS_Properties::IPropertySet& propSet) { if (!PSS_Symbol::SaveProperties(propSet)) return false; // only local symbol may access to properties if (!IsLocal()) return true; // save the rules PSS_RuleListPropertiesBP* pRulesProps = static_cast<PSS_RuleListPropertiesBP*>(GetProperty(ZS_BP_PROP_RULELIST)); if (!pRulesProps) return false; PSS_Properties::IPropertyIterator it(&propSet); // empty the task list SetRuleList(_T("")); // iterate through the data list and fill the property set for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_RULELIST) switch (pProp->GetValueType()) { case PSS_Property::IE_VT_String: // if not empty, add this new task if (!pProp->GetValueString().IsEmpty()) AddRule(pProp->GetValueString()); break; } for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) { const int categoryID = pProp->GetCategoryID(); if (categoryID >= ZS_BP_PROP_RISK && categoryID <= ZS_BP_PROP_RISK + GetRiskCount()) { const int itemID = pProp->GetItemID(); const int i = categoryID - ZS_BP_PROP_RISK; if (itemID == M_Risk_Name_ID + (i * g_MaxRisksSize)) SetRiskName(i, pProp->GetValueString()); if (itemID == M_Risk_Desc_ID + (i * g_MaxRisksSize)) SetRiskDesc(i, pProp->GetValueString()); if (itemID == M_Risk_UE_ID + (i * g_MaxRisksSize)) SetRiskUE(i, pProp->GetValueFloat()); if (itemID == M_Risk_POA_ID + (i * g_MaxRisksSize)) SetRiskPOA(i, pProp->GetValueFloat()); if (itemID == M_Risk_Action_ID + (i * g_MaxRisksSize)) SetRiskAction(i, (pProp->GetValueString() == PSS_Global::GetYesFromArrayYesNo() ? 1 : 0)); } } // save the tasks PSS_TaskListPropertiesBP* pTasksProps = static_cast<PSS_TaskListPropertiesBP*>(GetProperty(ZS_BP_PROP_TASKLIST)); if (!pTasksProps) return false; // empty the task list SetTaskList(_T("")); // iterate through the data list and fill the property set for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_TASKLIST) switch (pProp->GetValueType()) { case PSS_Property::IE_VT_String: // if not empty, add this new task if (!pProp->GetValueString().IsEmpty()) AddTask(pProp->GetValueString()); break; } // save the decisions. Because the AddTask() function is called, it's not necessary to call SetProperty() PSS_DecisionListPropertiesBP* pDecisionsProps = static_cast<PSS_DecisionListPropertiesBP*>(GetProperty(ZS_BP_PROP_DECISIONLIST)); if (!pDecisionsProps) return false; // empty the decision list SetDecisionList(_T("")); // iterate through the data list and fill the property set for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_DECISIONLIST) switch (pProp->GetValueType()) { case PSS_Property::IE_VT_String: // if not empty, add this new decision if (!pProp->GetValueString().IsEmpty()) AddDecision(pProp->GetValueString()); break; } // iterate through the data list and fill the property set. Because the AddDecision() function is called, // it's not necessary to call SetProperty() for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_PROCEDURE_COST) { const int itemID = pProp->GetItemID(); switch (pProp->GetValueType()) { case PSS_Property::IE_VT_String: m_CostProcedureProp.SetValue(itemID, pProp->GetValueString()); break; case PSS_Property::IE_VT_Double: m_CostProcedureProp.SetValue(itemID, float( pProp->GetValueDouble())); break; case PSS_Property::IE_VT_Float: m_CostProcedureProp.SetValue(itemID, pProp->GetValueFloat()); break; case PSS_Property::IE_VT_Date: m_CostProcedureProp.SetValue(itemID, float(DATE(pProp->GetValueDate()))); break; case PSS_Property::IE_VT_TimeSpan: m_CostProcedureProp.SetValue(itemID, double( pProp->GetValueTimeSpan())); break; case PSS_Property::IE_VT_Duration: m_CostProcedureProp.SetValue(itemID, double( pProp->GetValueDuration())); break; } } // iterate through the data list and fill the property set for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_UNIT) if (pProp->GetItemID() == M_Unit_Double_Validation_ID) m_UnitProp.SetValue(pProp->GetItemID(), ConvertUnitDoubleValidationString2Type(pProp->GetValueString())); else { const int itemID = pProp->GetItemID(); switch (pProp->GetValueType()) { case PSS_Property::IE_VT_Double: m_UnitProp.SetValue(itemID, float(pProp->GetValueDouble())); break; case PSS_Property::IE_VT_Float: m_UnitProp.SetValue(itemID, pProp->GetValueFloat()); break; case PSS_Property::IE_VT_String: m_UnitProp.SetValue(itemID, pProp->GetValueString()); break; } } // iterate through the data list and fill the property set of combination for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) { const int categoryID = pProp->GetCategoryID(); if (categoryID >= ZS_BP_PROP_COMBINATION && categoryID <= ZS_BP_PROP_COMBINATION + GetCombinationCount()) { const int i = categoryID - ZS_BP_PROP_COMBINATION; PSS_CombinationPropertiesBP* pCombProps = GetCombinationProperty(i); if (!pCombProps) return false; const int itemID = pProp->GetItemID(); switch (pProp->GetValueType()) { case PSS_Property::IE_VT_String: pCombProps->SetValue(itemID - (i * g_MaxCombinationListSize), pProp->GetValueString()); break; case PSS_Property::IE_VT_Double: pCombProps->SetValue(itemID - (i * g_MaxCombinationListSize), float( pProp->GetValueDouble())); break; case PSS_Property::IE_VT_Float: pCombProps->SetValue(itemID - (i * g_MaxCombinationListSize), pProp->GetValueFloat()); break; case PSS_Property::IE_VT_Date: pCombProps->SetValue(itemID - (i * g_MaxCombinationListSize), float(DATE(pProp->GetValueDate()))); break; case PSS_Property::IE_VT_TimeSpan: case PSS_Property::IE_VT_Duration: THROW("Unsupported value"); } } } // iterate through the data list and fill the property set for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_SIM_PROCEDURE) { const int itemID = pProp->GetItemID(); switch (pProp->GetValueType()) { case PSS_Property::IE_VT_String: m_SimulationProperties.SetValue(itemID, pProp->GetValueString()); break; case PSS_Property::IE_VT_Double: m_SimulationProperties.SetValue(itemID, pProp->GetValueDouble()); break; case PSS_Property::IE_VT_Float: m_SimulationProperties.SetValue(itemID, pProp->GetValueFloat()); break; case PSS_Property::IE_VT_Date: m_SimulationProperties.SetValue(itemID, float(DATE(pProp->GetValueDate()))); break; case PSS_Property::IE_VT_TimeSpan: m_SimulationProperties.SetValue(itemID, double( pProp->GetValueTimeSpan())); break; case PSS_Property::IE_VT_Duration: m_SimulationProperties.SetValue(itemID, double( pProp->GetValueDuration())); break; } } RefreshAttributeTextArea(true); return true; } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::SaveProperty(PSS_Property& prop) { if (!PSS_Symbol::SaveProperty(prop)) return false; // only local symbol may access to properties if (!IsLocal()) return true; const int categoryID = prop.GetCategoryID(); if (categoryID >= ZS_BP_PROP_RISK && categoryID <= ZS_BP_PROP_RISK + GetRiskCount()) { const int itemID = prop.GetItemID(); const int i = categoryID - ZS_BP_PROP_RISK; if (itemID == M_Risk_Name_ID + (i * g_MaxRisksSize)) SetRiskName(i, prop.GetValueString()); if (itemID == M_Risk_Desc_ID + (i * g_MaxRisksSize)) SetRiskDesc(i, prop.GetValueString()); if (itemID == M_Risk_UE_ID + (i * g_MaxRisksSize)) SetRiskUE(i, prop.GetValueFloat()); if (itemID == M_Risk_POA_ID + (i * g_MaxRisksSize)) SetRiskPOA(i, prop.GetValueFloat()); if (itemID == M_Risk_Action_ID + (i * g_MaxRisksSize)) SetRiskAction(i, (prop.GetValueString() == PSS_Global::GetYesFromArrayYesNo() ? 1 : 0)); } // check if the user tried to rename a rule, if yes revert to previous name if (categoryID == ZS_BP_PROP_RULES) { const int index = (prop.GetItemID() - M_Rule_Name_ID) / g_MaxRulesSize; if (m_Rules.GetRuleName(index) != prop.GetValueString()) prop.SetValueString(m_Rules.GetRuleName(index)); } if (categoryID >= ZS_BP_PROP_COMBINATION && categoryID <= ZS_BP_PROP_COMBINATION + GetCombinationCount()) { const int i = categoryID - ZS_BP_PROP_COMBINATION; switch (prop.GetItemID() - (i * g_MaxCombinationListSize)) { case M_Combination_Name_ID: SetCombinationName (prop.GetCategoryID() - ZS_BP_PROP_COMBINATION, prop.GetValueString()); break; case M_Combination_Deliverables_ID: SetCombinationDeliverables (prop.GetCategoryID() - ZS_BP_PROP_COMBINATION, prop.GetValueString()); break; case M_Combination_Activation_Perc_ID: SetCombinationActivationPerc(prop.GetCategoryID() - ZS_BP_PROP_COMBINATION, prop.GetValueFloat()); break; case M_Combination_Master_ID: SetCombinationMaster (prop.GetCategoryID() - ZS_BP_PROP_COMBINATION, prop.GetValueString()); break; } } if (categoryID == ZS_BP_PROP_RULELIST) // if not empty, add this new rule if (!prop.GetValueString().IsEmpty()) AddRule(prop.GetValueString()); if (categoryID == ZS_BP_PROP_TASKLIST) // if not empty, add this new task if (!prop.GetValueString().IsEmpty()) AddTask(prop.GetValueString()); if (categoryID == ZS_BP_PROP_DECISIONLIST) // if not empty, add this new task if (!prop.GetValueString().IsEmpty()) AddDecision(prop.GetValueString()); // set the symbol as modified. Do nothing else, the values will be saved by the save properties method SetModifiedFlag(); return true; } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::CheckPropertyValue(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props) { return PSS_Symbol::CheckPropertyValue(prop, value, props); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::ProcessExtendedInput(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh) { const int categoryID = prop.GetCategoryID(); if (categoryID >= ZS_BP_PROP_RISK && categoryID <= ZS_BP_PROP_RISK + GetRiskCount()) { const int i = categoryID - ZS_BP_PROP_RISK; PSS_ProcessGraphModelMdl* pModel = dynamic_cast<PSS_ProcessGraphModelMdl*>(GetRootModel()); CString currencySymbol = PSS_Global::GetLocaleCurrency(); // get the model currency symbol if (pModel) { PSS_ProcessGraphModelDoc* pDoc = dynamic_cast<PSS_ProcessGraphModelDoc*>(pModel->GetDocument()); if (pDoc) currencySymbol = pDoc->GetCurrencySymbol(); } CString noRiskType; noRiskType.LoadString(IDS_NO_RISK_TYPE); PSS_RiskOptionsDlg riskOptions(GetRiskName(i), GetRiskDesc(i), GetRiskType(i).IsEmpty() ? noRiskType : GetRiskType(i), GetRiskImpact(i), GetRiskProbability(i), GetRiskUE(i), GetRiskPOA(i), GetRiskAction(i), currencySymbol); if (riskOptions.DoModal() == IDOK) { SetRiskName (i, riskOptions.GetRiskTitle()); SetRiskDesc (i, riskOptions.GetRiskDescription()); SetRiskType (i, riskOptions.GetRiskType()); SetRiskImpact (i, riskOptions.GetRiskImpact()); SetRiskProbability(i, riskOptions.GetRiskProbability()); SetRiskSeverity (i, riskOptions.GetRiskSeverity()); SetRiskUE (i, riskOptions.GetRiskUE()); SetRiskPOA (i, riskOptions.GetRiskPOA()); SetRiskAction (i, riskOptions.GetRiskAction()); SetModifiedFlag(TRUE); refresh = true; return true; } } if (categoryID == ZS_BP_PROP_UNIT && prop.GetItemID() == M_Unit_Name_ID) { PSS_ProcessGraphModelMdl* pModel = dynamic_cast<PSS_ProcessGraphModelMdl*>(GetOwnerModel()); if (pModel) { PSS_SelectUserGroupDlg dlg(IDS_SELECTAGROUP_T, pModel->GetMainUserGroup(), true, false); if (dlg.DoModal() == IDOK) { PSS_UserEntity* pUserEntity = dlg.GetSelectedUserEntity(); if (pUserEntity) { value = pUserEntity->GetEntityName(); // change the disabled property unit GUID PSS_Properties::IPropertyIterator it(&props); for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_UNIT && pProp->GetItemID() == M_Unit_GUID_ID) { pProp->SetValueString(pUserEntity->GetGUID()); break; } return true; } } } } else if (categoryID >= ZS_BP_PROP_COMBINATION && categoryID <= ZS_BP_PROP_COMBINATION + GetCombinationCount()) { const int i = categoryID - ZS_BP_PROP_COMBINATION; switch (prop.GetItemID() - (i * g_MaxCombinationListSize)) { case M_Combination_Deliverables_ID: { // get the deliverables CString enteringDeliverables; GetEnteringUpDeliverable(enteringDeliverables); CString availableDeliverables = GetAvailableDeliverables(enteringDeliverables); // show the dialog PSS_AddRemoveCombinationDeliverableDlg dlg(availableDeliverables, value); if (dlg.DoModal() == IDOK) { value = dlg.GetDeliverables(); return true; } break; } case M_Combination_Master_ID: { PSS_SelectMasterDeliverableDlg dlg(GetCombinationDeliverables(i), value); if (dlg.DoModal() == IDOK) { value = dlg.GetMaster(); return true; } break; } } } return PSS_Symbol::ProcessExtendedInput(prop, value, props, refresh); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::ProcessMenuCommand(int menuCmdID, PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh) { const int categoryID = prop.GetCategoryID(); if (categoryID >= ZS_BP_PROP_RISK && categoryID <= ZS_BP_PROP_RISK + GetRiskCount()) { switch (menuCmdID) { case ID_ADD_NEWRISK: OnAddNewRisk (prop, value, props, refresh); break; case ID_DEL_CURRENTRISK: OnDelCurrentRisk(prop, value, props, refresh); break; default: break; } return true; } if (categoryID >= ZS_BP_PROP_COMBINATION && categoryID <= ZS_BP_PROP_COMBINATION + GetCombinationCount()) { switch (menuCmdID) { case ID_ADD_NEWCOMBINATION: OnAddNewCombination (prop, value, props, refresh); break; case ID_DEL_CURRENTCOMBINATION: OnDelCurrentCombination (prop, value, props, refresh); break; case ID_ADD_DELIVERABLE_COMBINATION: OnAddDeliverableCombination(prop, value, props, refresh); break; case ID_DEL_DELIVERABLE_COMBINATION: OnDelDeliverableCombination(prop, value, props, refresh); break; default: break; } return true; } if (categoryID == ZS_BP_PROP_RULES) switch (menuCmdID) { case ID_DEL_CURRENTRULE: { const int index = (prop.GetItemID() - M_Rule_Name_ID) / g_MaxRulesSize; m_Rules.DeleteRule(index); refresh = true; break; } default: break; } return PSS_Symbol::ProcessMenuCommand(menuCmdID, prop, value, props, refresh); } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetAttributeString(PSS_PropertyAttributes* pAttributes) const { return PSS_Symbol::GetAttributeString(pAttributes); } //--------------------------------------------------------------------------- int PSS_ProcedureSymbolBP::GetEnteringUpDeliverable(CString& deliverables) { int counter = 0; CODEdgeArray edges; // keep only deliverable symbols if (GetEnteringUpDeliverable(edges) > 0) { // initialize the token with ; as separator PSS_Tokenizer token; const int edgeCount = edges.GetSize(); for (int i = 0; i < edgeCount; ++i) { IODEdge* pIEdge = edges.GetAt(i); PSS_DeliverableLinkSymbolBP* pComp = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge); if (pComp) { token.AddToken(pComp->GetSymbolName()); ++counter; } } // assign the resulting string deliverables = token.GetString(); } return counter; } //--------------------------------------------------------------------------- int PSS_ProcedureSymbolBP::GetEnteringUpDeliverable(CODEdgeArray& edges) { // get all procedure entering up edges GetEdgesEntering_Up(edges); CODComponentSet* pSet = GetReferenceSymbols(); CODComponentSet internalSet; // get all edges from referenced procedures and local symbol if a referenced symbol is defined if (!IsLocal()) { if (!pSet) pSet = &internalSet; CODComponent* pLocalSymbol = GetLocalSymbol(); if (pLocalSymbol) pSet->Add(pLocalSymbol); } if (pSet) { const int setCount = pSet->GetSize(); for (int i = 0; i < setCount; ++i) { PSS_ProcedureSymbolBP* pComp = dynamic_cast<PSS_ProcedureSymbolBP*>(pSet->GetAt(i)); if (pComp) { CODEdgeArray additionalEdges; pComp->GetEdgesEntering_Up(additionalEdges); const int edgeCount = additionalEdges.GetSize(); // copy additional edges to the main edges for (int j = 0; j < edgeCount; ++j) // get the link edges.AddEdge(additionalEdges.GetAt(j)); } } } // keep only deliverable symbols return int(PSS_ODSymbolManipulator::KeepOnlyLinksISA(edges, RUNTIME_CLASS(PSS_DeliverableLinkSymbolBP))); } //--------------------------------------------------------------------------- int PSS_ProcedureSymbolBP::GetLeavingDownDeliverable(CString& deliverables) { int counter = 0; CODEdgeArray edges; if (GetLeavingDownDeliverable(edges) > 0) { // initialize the token with ; as separator PSS_Tokenizer token; const int edgeCount = edges.GetSize(); for (int i = 0; i < edgeCount; ++i) { IODEdge* pIEdge = edges.GetAt(i); PSS_DeliverableLinkSymbolBP* pComp = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge); if (pComp) { token.AddToken(pComp->GetSymbolName()); ++counter; } } // assign the resulting string deliverables = token.GetString(); } return counter; } //--------------------------------------------------------------------------- int PSS_ProcedureSymbolBP::GetLeavingDownDeliverable(CODEdgeArray& edges) { // get all leaving down edges GetEdgesLeaving_Down(edges); CODComponentSet* pSet = GetReferenceSymbols(); CODComponentSet internalSet; // get all edges from referenced procedures and local symbol if a referenced symbol is defined if (!IsLocal()) { if (!pSet) pSet = &internalSet; CODComponent* pLocalSymbol = GetLocalSymbol(); if (pLocalSymbol) pSet->Add(pLocalSymbol); } if (pSet) { const int setCount = pSet->GetSize(); for (int i = 0; i < setCount; ++i) { PSS_ProcedureSymbolBP* pComp = dynamic_cast<PSS_ProcedureSymbolBP*>(pSet->GetAt(i)); if (pComp) { CODEdgeArray additionalEdges; pComp->GetEdgesLeaving_Down(additionalEdges); const int edgeCount = additionalEdges.GetSize(); // copy additional edges to the main edges for (int j = 0; j < edgeCount; ++j) // get the link edges.AddEdge(additionalEdges.GetAt(j)); } } } // keep only deliverable symbols return int(PSS_ODSymbolManipulator::KeepOnlyLinksISA(edges, RUNTIME_CLASS(PSS_DeliverableLinkSymbolBP))); } //--------------------------------------------------------------------------- int PSS_ProcedureSymbolBP::GetLeavingLeftDeliverable(CString& deliverables) { int counter = 0; CODEdgeArray edges; if (GetLeavingLeftDeliverable(edges) > 0) { // initialize the token with ; as separator PSS_Tokenizer token; const int edgeCount = edges.GetSize(); for (int i = 0; i < edgeCount; ++i) { IODEdge* pIEdge = edges.GetAt(i); PSS_DeliverableLinkSymbolBP* pComp = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge); if (pComp) { token.AddToken(pComp->GetSymbolName()); ++counter; } } // assign the resulting string deliverables = token.GetString(); } return counter; } //--------------------------------------------------------------------------- int PSS_ProcedureSymbolBP::GetLeavingLeftDeliverable(CODEdgeArray& edges) { // get all leaving left edges GetEdgesLeaving_Left(edges); CODComponentSet* pSet = GetReferenceSymbols(); CODComponentSet internalSet; // get all edges from referenced procedures and local symbol if a referenced symbol is defined if (!IsLocal()) { if (!pSet) pSet = &internalSet; CODComponent* pLocalSymbol = GetLocalSymbol(); if (pLocalSymbol) pSet->Add(pLocalSymbol); } if (pSet) { const int setCount = pSet->GetSize(); for (int i = 0; i < setCount; ++i) { PSS_ProcedureSymbolBP* pComp = dynamic_cast<PSS_ProcedureSymbolBP*>(pSet->GetAt(i)); if (pComp) { CODEdgeArray additionalEdges; pComp->GetEdgesLeaving_Left(additionalEdges); const int edgeCount = additionalEdges.GetSize(); // copy additional edges to the main edges for (int j = 0; j < edgeCount; ++j) // get the link edges.AddEdge(additionalEdges.GetAt(j)); } } } // keep only deliverable symbols return (int)PSS_ODSymbolManipulator::KeepOnlyLinksISA(edges, RUNTIME_CLASS(PSS_DeliverableLinkSymbolBP)); } //--------------------------------------------------------------------------- int PSS_ProcedureSymbolBP::GetLeavingRightDeliverable(CString& deliverables) { int counter = 0; CODEdgeArray edges; if (GetLeavingRightDeliverable(edges) > 0) { // initialize the token with ; as separator PSS_Tokenizer token; const int edgeCount = edges.GetSize(); for (int i = 0; i < edgeCount; ++i) { IODEdge* pIEdge = edges.GetAt(i); PSS_DeliverableLinkSymbolBP* pComp = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge); if (pComp) { token.AddToken(pComp->GetSymbolName()); ++counter; } } // assign the resulting string deliverables = token.GetString(); } return counter; } //--------------------------------------------------------------------------- int PSS_ProcedureSymbolBP::GetLeavingRightDeliverable(CODEdgeArray& edges) { // get all leaving right edges GetEdgesLeaving_Right(edges); // get all edges from referenced procedures and local symbol if a referenced symbol is defined CODComponentSet* pSet = GetReferenceSymbols(); CODComponentSet internalSet; if (!IsLocal()) { if (!pSet) pSet = &internalSet; CODComponent* pLocalSymbol = GetLocalSymbol(); if (pLocalSymbol) pSet->Add(pLocalSymbol); } if (pSet) { const int setCount = pSet->GetSize(); for (int i = 0; i < setCount; ++i) { PSS_ProcedureSymbolBP* pComp = dynamic_cast<PSS_ProcedureSymbolBP*>(pSet->GetAt(i)); if (pComp) { CODEdgeArray additionalEdges; pComp->GetEdgesLeaving_Right(additionalEdges); const int edgeCount = additionalEdges.GetSize(); // copy additional edges to the main edges for (int j = 0; j < edgeCount; ++j) // get the link edges.AddEdge(additionalEdges.GetAt(j)); } } } // keep only deliverable symbols return (int)PSS_ODSymbolManipulator::KeepOnlyLinksISA(edges, RUNTIME_CLASS(PSS_DeliverableLinkSymbolBP)); } //--------------------------------------------------------------------------- PSS_AnnualNumberPropertiesBP PSS_ProcedureSymbolBP::CalculateProcedureActivation() { // get all entering deliverables CODEdgeArray edges; // get all entering up edges if (!GetEnteringUpDeliverable(edges)) return 0; PSS_AnnualNumberPropertiesBP ProcedureActivation(0); // for each deliverables, calculate the max procedure activation for (int i = 0; i < edges.GetSize(); ++i) { IODEdge* pIEdge = edges.GetAt(i); PSS_DeliverableLinkSymbolBP* pDeliverable = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge); if (!pDeliverable) continue; // check if it's a local symbol if (!pDeliverable->IsLocal()) { // get the local symbol pDeliverable = dynamic_cast<PSS_DeliverableLinkSymbolBP*>(pDeliverable->GetLocalSymbol()); if (!pDeliverable) return false; } const int count = GetCombinationCount(); // iterate through combination and check if this deliverable is defined as a master. If yes, // add it to the procedure activation for (int j = 0; j < count; ++j) { TRACE1("Master = %s\n", GetCombinationMaster(j)); TRACE1("Livrable = %s\n", pDeliverable->GetSymbolName()); // found a master? if (!GetCombinationMaster(j).IsEmpty() && GetCombinationMaster(j) == pDeliverable->GetSymbolName()) ProcedureActivation += pDeliverable->GetQuantity(); } } return ProcedureActivation; } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetRuleList() const { PSS_RuleListPropertiesBP* pProps = static_cast<PSS_RuleListPropertiesBP*>(GetProperty(ZS_BP_PROP_RULELIST)); if (!pProps) return _T(""); return pProps->GetRuleList(); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::SetRuleList(const CString& value) { PSS_RuleListPropertiesBP* pProps = static_cast<PSS_RuleListPropertiesBP*>(GetProperty(ZS_BP_PROP_RULELIST)); if (pProps) { PSS_RuleListPropertiesBP props(*pProps); props.SetRuleList(value); SetProperty(&props); } } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::RuleExist(const CString& value) { // initialize the token with the rule list and with the default ; as separator PSS_Tokenizer token(GetRuleList()); return token.TokenExist(value); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::AddRule(const CString& value) { // initialize the token with the rule list and with the default ; as separator PSS_Tokenizer token(GetRuleList()); // if the new rule was added successfully, update the rule list if (token.AddUniqueToken(value)) { // add the value to the history CString key; key.LoadString(IDS_ZS_BP_PROP_RULELST_TITLE); PSS_Global::GetHistoricValueManager().AddHistoryValue(key, value); // set the new rule string SetRuleList(token.GetString()); } } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::RemoveRule(const CString& value) { // initialize the token with the rule list and with the default ; as separator PSS_Tokenizer token(GetRuleList()); // if the rule was removed successfully, update the rule list if (token.RemoveToken(value)) SetRuleList(token.GetString()); } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetRuleAt(std::size_t index) { // initialize the token with the rule list and with the default ; as separator PSS_Tokenizer token(GetRuleList()); CString value; // get the token at index if (token.GetTokenAt(index, value)) return value; return _T(""); } //--------------------------------------------------------------------------- std::size_t PSS_ProcedureSymbolBP::GetRuleCount() const { // initialize the token with the rule list and with the default ; as separator PSS_Tokenizer token(GetRuleList()); return token.GetTokenCount(); } //--------------------------------------------------------------------------- BOOL PSS_ProcedureSymbolBP::ContainsRule(const CString& ruleName) const { const int ruleCount = m_Rules.GetRulesCount(); for (int i = 0; i < ruleCount; ++i) if (m_Rules.GetRuleName(i) == ruleName) return TRUE; return FALSE; } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::CheckRulesSync(CStringArray& rulesList) { CODModel* pModel = GetRootModel(); if (pModel) return; if (m_Rules.GetRulesCount() > 0) { PSS_ProcessGraphModelMdlBP* pOwnerModel = dynamic_cast<PSS_ProcessGraphModelMdlBP*>(GetOwnerModel()); PSS_LogicalRulesEntity* pMainRule = NULL; if (pOwnerModel) pMainRule = pOwnerModel->GetMainLogicalRules(); if (!pMainRule) return; const int ruleCount = m_Rules.GetRulesCount(); for (int i = 0; i < ruleCount; ++i) { const CString safeName = GetRuleNameByGUID(pMainRule, m_Rules.GetRuleGUID(i)); if (safeName.IsEmpty()) rulesList.Add(m_Rules.GetRuleName(i)); } } } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetTaskList() const { PSS_TaskListPropertiesBP* pProps = static_cast<PSS_TaskListPropertiesBP*>(GetProperty(ZS_BP_PROP_TASKLIST)); if (!pProps) return _T(""); return pProps->GetTaskList(); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::SetTaskList(const CString& value) { PSS_TaskListPropertiesBP* pProps = static_cast<PSS_TaskListPropertiesBP*>(GetProperty(ZS_BP_PROP_TASKLIST)); if (pProps) { PSS_TaskListPropertiesBP props(*pProps); props.SetTaskList(value); SetProperty(&props); } } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::TaskExist(const CString& value) { // initialize the token with the task list and with the default ; as separator PSS_Tokenizer token(GetTaskList()); return token.TokenExist(value); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::AddTask(const CString& value) { // initialize the token with the task list and with the default ; as separator PSS_Tokenizer token(GetTaskList()); // if the new task was added successfully, update the task list if (token.AddUniqueToken(value)) { // add the value to the history CString key; key.LoadString(IDS_ZS_BP_PROP_PROCEDURE_TSKLST_TITLE); PSS_Global::GetHistoricValueManager().AddHistoryValue(key, value); // set the new task string SetTaskList(token.GetString()); } } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::RemoveTask(const CString& value) { // initialize the token with the task list and with the default ; as separator PSS_Tokenizer token(GetTaskList()); // if the new task was removed successfully, update the task list if (token.RemoveToken(value)) SetTaskList(token.GetString()); } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetTaskAt(std::size_t index) { // Initialize the token with the task list and with the default ; as separator PSS_Tokenizer token(GetTaskList()); CString value; // get the token at index if (token.GetTokenAt(index, value)) return value; return _T(""); } //--------------------------------------------------------------------------- std::size_t PSS_ProcedureSymbolBP::GetTaskCount() const { // initialize the token with the task list and with the default ; as separator PSS_Tokenizer token(GetTaskList()); return token.GetTokenCount(); } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetDecisionList() const { PSS_DecisionListPropertiesBP* pProps = static_cast<PSS_DecisionListPropertiesBP*>(GetProperty(ZS_BP_PROP_DECISIONLIST)); if (!pProps) return _T(""); return pProps->GetDecisionList(); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::SetDecisionList(const CString& value) { PSS_DecisionListPropertiesBP* pProps = static_cast<PSS_DecisionListPropertiesBP*>(GetProperty(ZS_BP_PROP_DECISIONLIST)); if (pProps) { PSS_DecisionListPropertiesBP props(*pProps); props.SetDecisionList(value); SetProperty(&props); } } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::DecisionExist(const CString& value) { // initialize the token with the decision list and with the default ; as separator PSS_Tokenizer token(GetDecisionList()); return token.TokenExist(value); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::AddDecision(const CString& value) { // initialize the token with the decision list and with the default ; as separator PSS_Tokenizer token(GetDecisionList()); // if the new decision was added successfully, update the decision list if (token.AddUniqueToken(value)) { // add the value to the history CString key; key.LoadString(IDS_ZS_BP_PROP_PROCEDURE_DECLST_TITLE); PSS_Global::GetHistoricValueManager().AddHistoryValue(key, value); // set the new decision string SetDecisionList(token.GetString()); } } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::RemoveDecision(const CString& value) { // initialize the token with the decision list and with the default ; as separator PSS_Tokenizer token(GetDecisionList()); // if the new decision was removed successfully, update the decision list if (token.RemoveToken(value)) SetDecisionList(token.GetString()); } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetDecisionAt(std::size_t index) { // initialize the token with the decision list and with the default ; as separator PSS_Tokenizer token(GetDecisionList()); CString value; // get the decision at index if (token.GetTokenAt(index, value)) return value; return _T(""); } //--------------------------------------------------------------------------- std::size_t PSS_ProcedureSymbolBP::GetDecisionCount() const { // initialize the token with the decision list and with the default ; as separator PSS_Tokenizer token(GetDecisionList()); return token.GetTokenCount(); } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetRiskType(std::size_t index) const { PSS_Application* pApp = PSS_Application::Instance(); if (!pApp) return _T(""); PSS_MainForm* pMainForm = pApp->GetMainForm(); if (!pMainForm) return _T(""); PSS_RiskTypeContainer* pContainer = pMainForm->GetRiskTypeContainer(); if (!pContainer) return _T(""); const int count = pContainer->GetElementCount(); const CString riskType = m_Risks.GetRiskType(index); for (int i = 0; i < count; ++i) if (riskType == pContainer->GetElementAt(i)) return m_Risks.GetRiskType(index); return _T(""); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::Serialize(CArchive& ar) { PSS_Symbol::Serialize(ar); // only if the object is serialized from or to a document if (ar.m_pDocument) { // serialize the combinations m_Combinations.Serialize(ar); m_SimulationProperties.Serialize(ar); PSS_BaseDocument* pDocument = dynamic_cast<PSS_BaseDocument*>(ar.m_pDocument); // serialize the risks if (pDocument && pDocument->GetDocumentStamp().GetInternalVersion() >= 27) m_Risks.Serialize(ar); // serialize the rules if (ar.IsStoring()) m_Rules.Serialize(ar); else if (pDocument && pDocument->GetDocumentStamp().GetInternalVersion() >= 26) m_Rules.Serialize(ar); if (ar.IsStoring() || (pDocument && pDocument->GetDocumentStamp().GetInternalVersion() >= 19)) { m_UnitProp.Serialize(ar); m_CostProcedureProp.Serialize(ar); } else { TRACE("PSS_ProcedureSymbolBP::Serialize - Start read\n"); // transfer the properties to new format PSS_CostPropertiesProcedureBP_Beta1* pCostProps = static_cast<PSS_CostPropertiesProcedureBP_Beta1*>(GetProperty(ZS_BP_PROP_PROCEDURE_COST)); if (pCostProps) { SetMultiplier(pCostProps->GetMultiplier()); SetProcessingTime(pCostProps->GetProcessingTime()); SetUnitaryCost(pCostProps->GetUnitaryCost()); } PSS_UnitPropertiesBP_Beta1* pUnitProps = static_cast<PSS_UnitPropertiesBP_Beta1*>(GetProperty(ZS_BP_PROP_UNIT)); if (pUnitProps) { SetUnitName(pUnitProps->GetUnitName()); SetUnitCost(pUnitProps->GetUnitCost()); } // set the master if only one deliverable was found for the combination const int count = GetCombinationCount(); for (int i = 0; i < count; ++i) { const CString deliverables = GetCombinationDeliverables(i); // if no separator, only one deliverable, so set this deliverable as the master one if (deliverables.Find(';') == -1) SetCombinationMaster(i, deliverables); } TRACE("PSS_ProcedureSymbolBP::Serialize - End read\n"); } } } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnSymbolNameChanged(CODComponent& comp, const CString& oldName) { PSS_LinkSymbol* pSymbol = dynamic_cast<PSS_LinkSymbol*>(&comp); if (pSymbol) ReplaceDeliverable(oldName, pSymbol->GetSymbolName()); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::OnPostPropertyChanged(PSS_Property& prop, PSS_Properties::IPropertySet& props, bool& refresh) { // only local symbol may access to properties if (!IsLocal()) return false; bool result = false; if (prop.GetCategoryID() >= ZS_BP_PROP_COMBINATION && prop.GetCategoryID() <= ZS_BP_PROP_COMBINATION + GetCombinationCount()) { const int i = prop.GetCategoryID() - ZS_BP_PROP_COMBINATION; switch (prop.GetItemID() - (i * g_MaxCombinationListSize)) { case M_Combination_Deliverables_ID: { const float maxPercent = GetMaxActivationPerc(GetCombinationMaster(prop.GetCategoryID() - ZS_BP_PROP_COMBINATION)); PSS_Properties::IPropertyIterator it(&props); bool found = false; // set the value to the property for (PSS_Property* pProp = it.GetFirst(); pProp && !found; pProp = it.GetNext()) { if (!pProp || ((pProp->GetCategoryID() - ZS_BP_PROP_COMBINATION) != i)) continue; if (pProp->GetItemID() - (i * g_MaxCombinationListSize) == M_Combination_Activation_Perc_ID) { pProp->SetValueFloat(maxPercent); found = true; } } // change the return value if found if (found) result = true; break; } default: break; } } else if (prop.GetCategoryID() == ZS_BP_PROP_UNIT && prop.GetItemID() == M_Unit_Name_ID) { PSS_Properties::IPropertyIterator it(&props); CString guid; // iterate through the properties and change the unit cost to the property value for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_UNIT && pProp->GetItemID() == M_Unit_GUID_ID) { guid = pProp->GetValueString(); break; } if (!guid.IsEmpty()) for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_UNIT && pProp->GetItemID() == M_Unit_Cost_ID) { bool error; float unitCost = RetrieveUnitCost(guid, error); if (!error) { pProp->SetValueFloat(unitCost); result = true; } break; } } else if (prop.GetCategoryID() == ZS_BP_PROP_RULELIST) { // change the return value to reload the properties. Need to reload since the rule list has an empty rule. // If the user fills it, need to enable a new empty one. And if the user remove one rule, need also to // disable one from the property list PSS_Properties::IPropertyIterator it(&props); std::size_t counterEnableEmpty = 0; // iterate through the properties and change their enabled flag. To change it, need to check if it is a new // property that need to be enabled or not, then need to ensure that only an empty property is enable for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_RULELIST) { // if the string is not empty, set its enabled flag to true if (!pProp->GetValueString().IsEmpty()) pProp->SetEnabled(true); // if the string is empty, check if its enabled flag is set and add it to the counter. // Enable or disable it according to if the counter is equal or not to 1 if (pProp->GetValueString().IsEmpty()) { if (pProp->GetEnabled()) ++counterEnableEmpty; else // if not at least one empty element if (counterEnableEmpty < 1) { pProp->SetEnabled(true); ++counterEnableEmpty; } // if the counter is greater than 1, need to disable the empty element if (counterEnableEmpty > 1) { --counterEnableEmpty; pProp->SetEnabled(false); } } } result = true; } else if (prop.GetCategoryID() == ZS_BP_PROP_TASKLIST) { // change the return value to reload the properties. Need to reload since the rule list has an empty task. // If the user fills it, need to enable a new empty one. And if the user remove one task, need also to // disable one from the property list PSS_Properties::IPropertyIterator it(&props); std::size_t counterEnableEmpty = 0; // iterate through the properties and change their enabled flag. To change it, need to check if it is a new // property that need to be enabled or not, then need to ensure that only an empty property is enable for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_TASKLIST) { // if the string is not empty, set the enabled flag to true if (!pProp->GetValueString().IsEmpty()) pProp->SetEnabled(true); // if the string is empty, check if its enabled flag is set and add it to the counter. // Enable or disable it according to if the counter is equal or not to 1 if (pProp->GetValueString().IsEmpty()) { if (pProp->GetEnabled()) ++counterEnableEmpty; else // if not at least one empty element if (counterEnableEmpty < 1) { pProp->SetEnabled(true); ++counterEnableEmpty; } // if the counter is greater than 1, need to disable the empty element if (counterEnableEmpty > 1) { --counterEnableEmpty; pProp->SetEnabled(false); } } } result = true; } else if (prop.GetCategoryID() == ZS_BP_PROP_DECISIONLIST) { // change the return value to reload the properties. Need to reload since the decision list has an empty decision. // If the user fills it, need to enable a new empty one. And if the user remove one decision, need also to // disable one from the property list PSS_Properties::IPropertyIterator it(&props); std::size_t counterEnableEmpty = 0; // iterate through the properties and change their enabled flag. To change it, need to check if it is a new // property that need to be enabled or not, then need to ensure that only an empty property is enable for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_DECISIONLIST) { // if the string is not empty, set its enabled flag to true if (!pProp->GetValueString().IsEmpty()) pProp->SetEnabled(true); // if the string is empty, check if its enabled flag is set and add it to the counter. // Enable or disable it according to if the counter is equal or not to 1 if (pProp->GetValueString().IsEmpty()) { if (pProp->GetEnabled() == true) ++counterEnableEmpty; else // if not at least one empty element if (counterEnableEmpty < 1) { pProp->SetEnabled(true); ++counterEnableEmpty; } // if the counter is greater than 1, need to disable the empty element if (counterEnableEmpty > 1) { --counterEnableEmpty; pProp->SetEnabled(false); } } } result = true; } if (!result) return PSS_Symbol::OnPostPropertyChanged(prop, props, refresh); return result; } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::OnDropInternalPropertyItem(PSS_Property& srcProperty, PSS_Property& dstProperty, bool top2Down, PSS_Properties::IPropertySet& props) { bool result = ::SwapInternalPropertyItem(srcProperty, dstProperty, top2Down, props, ZS_BP_PROP_TASKLIST); if (result) return true; result = ::SwapInternalPropertyItem(srcProperty, dstProperty, top2Down, props, ZS_BP_PROP_RULELIST); if (result) return true; result = ::SwapInternalPropertyItem(srcProperty, dstProperty, top2Down, props, ZS_BP_PROP_RULES); if (result) { const int srcIndex = (srcProperty.GetItemID() - M_Rule_Name_ID) / g_MaxRulesSize; const int dstIndex = (dstProperty.GetItemID() - M_Rule_Name_ID) / g_MaxRulesSize; const CString srcRuleName = m_Rules.GetRuleName(srcIndex); const CString srcRuleDesc = m_Rules.GetRuleDescription(srcIndex); const CString srcRuleGUID = m_Rules.GetRuleGUID(srcIndex); const CString dstRuleName = m_Rules.GetRuleName(dstIndex); const CString dstRuleDesc = m_Rules.GetRuleDescription(dstIndex); const CString dstRuleGUID = m_Rules.GetRuleGUID(dstIndex); m_Rules.SetRuleName(srcIndex, dstRuleName); m_Rules.SetRuleDescription(srcIndex, dstRuleDesc); m_Rules.SetRuleGUID(srcIndex, dstRuleGUID); m_Rules.SetRuleName(dstIndex, srcRuleName); m_Rules.SetRuleDescription(dstIndex, srcRuleDesc); m_Rules.SetRuleGUID(dstIndex, srcRuleGUID); return true; } // otherwise, do it for decisions return ::SwapInternalPropertyItem(srcProperty, dstProperty, top2Down, props, ZS_BP_PROP_DECISIONLIST); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::OnFillDefaultAttributes(PSS_PropertyAttributes* pAttributes) { if (!pAttributes) return false; PSS_PropertyAttributes& attributes = PSS_ModelGlobal::GetGlobalPropertyAttributes(GetObjectTypeID()); // if global attributes were defined, copy them if (attributes.GetAttributeCount() > 0) *pAttributes = attributes; else { // add the reference number pAttributes->AddAttribute(ZS_BP_PROP_BASIC, M_Symbol_Number_ID); // add the unit name pAttributes->AddAttribute(ZS_BP_PROP_UNIT, M_Unit_Name_ID); // no item labels pAttributes->SetShowTitleText(false); } return PSS_Symbol::OnFillDefaultAttributes(pAttributes); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::OnChangeAttributes(PSS_PropertyAttributes* pAttributes) { return PSS_Symbol::OnChangeAttributes(pAttributes); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnConnect(CODConnection* pConnection) { PSS_Symbol::OnConnect(pConnection); CheckInitialCombination(); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnDisconnect(CODConnection* pConnection) { PSS_Symbol::OnDisconnect(pConnection); CheckInitialCombination(); } //--------------------------------------------------------------------------- BOOL PSS_ProcedureSymbolBP::OnConnectionMove(CODConnection* pConnection) { return PSS_Symbol::OnConnectionMove(pConnection); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnLinkDisconnect(CODLinkComponent* pLink) { PSS_LinkSymbol* pLinkSymbol = dynamic_cast<PSS_LinkSymbol*>(pLink); if (pLinkSymbol) DeleteDeliverableFromAllCombinations(pLinkSymbol->GetSymbolName()); } //--------------------------------------------------------------------------- BOOL PSS_ProcedureSymbolBP::OnDoubleClick() { return FALSE; } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnUpdate(PSS_Subject* pSubject, PSS_ObserverMsg* pMsg) { PSS_Symbol::OnUpdate(pSubject, pMsg); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnDraw(CDC* pDC) { PSS_Symbol::OnDraw(pDC); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::OnToolTip(CString& toolTipText, const CPoint& point, PSS_ToolTip::IEToolTipMode mode) { toolTipText.Format(IDS_FS_BPPROCEDURE_TOOLTIP, (const char*)GetSymbolName(), (const char*)GetSymbolComment(), (const char*)GetSymbolReferenceNumberStr()); if (mode == PSS_Symbol::IE_TT_Design) { // todo -cFeature -oJean: need to implement the result of the control checking } return true; } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::AdjustElementPosition() { PSS_Symbol::AdjustElementPosition(); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::CheckInitialCombination() { // check if only one combination. If it's the case, set all deliverables to the combination if (GetCombinationCount() == 1) { // get all deliverables CString enteringDeliverables; GetEnteringUpDeliverable(enteringDeliverables); // set it SetCombinationDeliverables(0, enteringDeliverables); // if no entering deliverables, remove the master if (enteringDeliverables.IsEmpty()) SetCombinationMaster(0, enteringDeliverables); else { // if there is only one deliverable, it's the master PSS_Tokenizer token(enteringDeliverables); if (token.GetTokenCount() == 1) { CString value; // get the token at index if (token.GetTokenAt(0, value)) SetCombinationMaster(0, value); } } SetCombinationActivationPerc(0, GetMaxActivationPerc(GetCombinationMaster(0))); } } //--------------------------------------------------------------------------- float PSS_ProcedureSymbolBP::GetMaxActivationPerc(const CString& master) { if (master.IsEmpty()) return 0.0f; double sum = 0; double masterQuantity = 0; CODEdgeArray edges; // get all procedures entering up edges if (GetEnteringUpDeliverable(edges) > 0) { const int edgeCount = edges.GetSize(); for (int i = 0; i < edgeCount; ++i) { IODEdge* pIEdge = edges.GetAt(i); PSS_DeliverableLinkSymbolBP* pComp = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge); // check if it's a local symbol if (!pComp->IsLocal()) // get the local symbol pComp = dynamic_cast<PSS_DeliverableLinkSymbolBP*>(pComp->GetLocalSymbol()); if (pComp) { // check if the component is the master if (pComp->GetSymbolName() == master) masterQuantity = (double)pComp->GetQuantity(); // iterate through combinations and check if the component is the combination master, // add its quantity to the sum const int combinationCount = GetCombinationCount(); for (int i = 0; i < combinationCount; ++i) if (pComp->GetSymbolName() == GetCombinationMaster(i)) sum += (double)pComp->GetQuantity(); } } } if (!sum) return 0.0f; return float(masterQuantity / sum); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnAddNewCombination(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh) { // add a new combination if (AddNewCombination() >= 0) { // set the refresh flag to true refresh = true; SetModifiedFlag(TRUE); } } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnDelCurrentCombination(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh) { const int count = GetCombinationCount(); if (count <= 1) { // cannot delete all combinations PSS_MsgBox mBox; mBox.Show(IDS_CANNOTDELETE_ALLCOMBINATIONS, MB_OK); return; } // otherwise, delete the currently selected combination const int index = prop.GetCategoryID() - ZS_BP_PROP_COMBINATION; if (DeleteCombination(index)) { // set the refresh flag to true refresh = true; SetModifiedFlag(TRUE); } } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnAddDeliverableCombination(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh) {} //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnDelDeliverableCombination(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh) {} //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnAddNewRisk(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh) { // sdd a new risk if (AddNewRisk() >= 0) { // set the refresh flag to true refresh = true; SetModifiedFlag(TRUE); } } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnDelCurrentRisk(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh) { const int count = GetRiskCount(); if (count <= 1) { // cannot delete all risks PSS_MsgBox mBox; mBox.Show(IDS_CANNOTDELETE_ALLRISKS, MB_OK); return; } // otherwise, delete the currently selected risk const int index = prop.GetCategoryID() - ZS_BP_PROP_RISK; if (DeleteRisk(index)) { // set the refresh flag to true refresh = true; SetModifiedFlag(TRUE); } } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetRuleNameByGUID(PSS_LogicalRulesEntity* pRule, const CString& ruleGUID) { if (!pRule) return _T(""); if (pRule->GetGUID() == ruleGUID) return pRule->GetEntityName(); if (pRule->ContainEntity()) { const int count = pRule->GetEntityCount(); for (int i = 0; i < count; ++i) { PSS_LogicalRulesEntity* pEntity = dynamic_cast<PSS_LogicalRulesEntity*>(pRule->GetEntityAt(i)); if (!pEntity) continue; const CString name = GetRuleNameByGUID(pEntity, ruleGUID); if (!name.IsEmpty()) return name; } } return _T(""); } //---------------------------------------------------------------------------
40.514943
158
0.526679
Jeanmilost
cc6570a655cda878517b2a27b4e4526d8a979028
3,614
cc
C++
o3d/compiler/puritan/main.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
11
2015-03-20T04:08:08.000Z
2021-11-15T15:51:36.000Z
o3d/compiler/puritan/main.cc
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
null
null
null
o3d/compiler/puritan/main.cc
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
1
2020-04-13T05:45:10.000Z
2020-04-13T05:45:10.000Z
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google 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. */ // This program demonstrates how to get test case information out of Puritan. #include <iostream> #include "test_gen.h" #include "knobs.h" static std::string name_of_size(Salem::Puritan::OutputInfo::ArgSize x) { switch (x) { case Salem::Puritan::OutputInfo::Float1: return "float"; case Salem::Puritan::OutputInfo::Float2: return "float2"; case Salem::Puritan::OutputInfo::Float4: return "float4"; default: break; } return "Impossible"; } static std::string comma(bool * need_comma) { if (*need_comma) { return ", "; } else { *need_comma = true; return ""; } } int main (int argc, char * const argv[]) { int j = 0; if (argc > 1) { sscanf(argv[1], "%d", &j); } Salem::Puritan::Knobs options; // Set up some options just the way we like options.block_count.set(2, 3); options.for_count.set(2, 3); options.for_nesting.set(2, 3); options.array_in_for_use.set(false); options.seed.set(j); Salem::Puritan::OutputInfo info; // Build a test case std::string test_case = Salem::Puritan::generate(&info, options); // Dump out the test information std::cout << "(Seed " << options.seed.get() << "), " << "(Samplers ("; bool need_comma = false; for (unsigned i = 0; i < info.n_samplers; i++) { std::cout << comma(&need_comma) << "in" << i; } std::cout << "))," << "(Uniforms ("; need_comma = false; for (std::list < std::pair < Salem::Puritan::OutputInfo::ArgSize, std::string > >::const_iterator i = info.uniforms.begin(); i != info.uniforms.end(); i++) { std::cout << comma(&need_comma) << name_of_size(i->first) << " " << i->second; } std::cout << ")), " << "(return struct {"; need_comma = false; for (std::list <Salem::Puritan::OutputInfo::ArgSize>::const_iterator i = info.returns.begin(); i != info.returns.end(); i++) { std::cout << comma(&need_comma) << name_of_size(*i); } std::cout << "})\n"; std::cout << test_case; return 1; }
27.8
77
0.666574
rwatson
cc678fb574dfe265aadd588c689b0d1efdba0f13
231
hpp
C++
Spiel/src/Graveyard/rendering/RenderBuffer.hpp
Ipotrick/CPP-2D-Game-Engine
9cd87c369d813904d76668fe6153c7c4e8686023
[ "MIT" ]
null
null
null
Spiel/src/Graveyard/rendering/RenderBuffer.hpp
Ipotrick/CPP-2D-Game-Engine
9cd87c369d813904d76668fe6153c7c4e8686023
[ "MIT" ]
null
null
null
Spiel/src/Graveyard/rendering/RenderBuffer.hpp
Ipotrick/CPP-2D-Game-Engine
9cd87c369d813904d76668fe6153c7c4e8686023
[ "MIT" ]
null
null
null
#pragma once #include "Layer.hpp" #include "Camera.hpp" struct RenderBuffer { std::vector<std::unique_ptr<RenderScript>> scriptDestructQueue; bool resetTextureCache{ false }; Camera camera; std::vector<RenderLayer> layers; };
21
64
0.761905
Ipotrick
cc68b57f65e3eda864d9e3ad0d92c028d9c624f7
1,900
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/CMediaFileType.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/CMediaFileType.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/CMediaFileType.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos 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 "elastos/droid/media/CMediaFileType.h" namespace Elastos { namespace Droid { namespace Media { CAR_INTERFACE_IMPL(CMediaFileType, Object, IMediaFileType) CAR_OBJECT_IMPL(CMediaFileType) CMediaFileType::CMediaFileType() : mFileType(0) { } CMediaFileType::~CMediaFileType() { } ECode CMediaFileType::constructor() { return NOERROR; } ECode CMediaFileType::constructor( /* [in] */ Int32 fileType, /* [in] */ const String& mimeType) { mFileType = fileType; mMimeType = mimeType; return NOERROR; } ECode CMediaFileType::SetFileType( /* [in] */ Int32 result) { mFileType = result; return NOERROR; } ECode CMediaFileType::SetMimeType( /* [in] */ const String& result) { mMimeType = result; return NOERROR; } ECode CMediaFileType::GetFileType( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mFileType; return NOERROR; } ECode CMediaFileType::GetMimeType( /* [out] */ String* result) { VALIDATE_NOT_NULL(result); *result = mMimeType; return NOERROR; } } // namespace Media } // namepsace Droid } // namespace Elastos
22.352941
75
0.645263
jingcao80
cc7097e3531cba3b13fb012eca8cbc5cc6a126fa
708
cpp
C++
CodeForces/Complete/700-799/791C-BearAndDifferentNames.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/700-799/791C-BearAndDifferentNames.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/700-799/791C-BearAndDifferentNames.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <iostream> #include <vector> int main(){ const int L = 26; const int N = 100; std::ios_base::sync_with_stdio(false); std::vector<std::string> a(N); for(long p = 0; p < N; p++){a[p] = ('A' + (p / L)); a[p] += ('a' + (p % L));} int n, k; std::cin >> n >> k; std::vector<bool> eff(n - k + 1, 0); for(long p = 0; p < n - k + 1; p++){std::string s; std::cin >> s; eff[p] = (s == "YES");} std::vector<std::string> v; for(long p = 0; p < k - 1; p++){v.push_back(a[p]);} for(long p = k - 1; p < n; p++){v.push_back(eff[p - k + 1] ? a[p] : v[p - k + 1]);} for(long p = 0; p < n; p++){std::cout << v[p] << " ";} std::cout << std::endl; return 0; }
29.5
93
0.457627
Ashwanigupta9125
cc731400e0ed1b202dead5e6b892b09477c244ca
2,843
hpp
C++
behavior_system/IBehavior.hpp
draghan/behavior_tree
e890c29f009e11e8120a861aa5515797a52d656a
[ "MIT" ]
7
2018-08-27T20:31:21.000Z
2021-11-22T05:57:18.000Z
behavior_system/IBehavior.hpp
draghan/behavior_tree
e890c29f009e11e8120a861aa5515797a52d656a
[ "MIT" ]
null
null
null
behavior_system/IBehavior.hpp
draghan/behavior_tree
e890c29f009e11e8120a861aa5515797a52d656a
[ "MIT" ]
null
null
null
/* This file is distributed under MIT License. Copyright (c) 2018 draghan 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. */ // // Created by draghan on 2017-10-14. // #pragma once #include <string> #include <vector> #ifndef __arm__ #include <ostream> #endif enum class BehaviorState: uint8_t { undefined, success, failure, running }; class IBehavior { public: using ptr = IBehavior *; using id_t = uint32_t; const static id_t undefined_id; #ifndef __arm__ // Decided to disable printing to the streams on ARM processors // in order to keep some bytes of compiled result file. // With stream library included, result files were unacceptable // oversized for Cortex M. void print_family(std::string indent, bool last, std::ostream &stream); void introduce_yourself(std::ostream &stream); #endif id_t get_id() const; void set_id(id_t id); bool add_child(ptr child); size_t get_number_of_children() const; ptr get_child(size_t index) const; ptr get_last_child() const; ptr get_parent() const; explicit IBehavior(ptr parent, uint32_t id = 0); IBehavior(const IBehavior&) = delete; void operator=(const IBehavior&) = delete; virtual ~IBehavior() = default; BehaviorState evaluate(); BehaviorState get_status() const; bool operator==(const IBehavior &); virtual std::string get_glyph() const; virtual bool can_have_children() const = 0; protected: std::vector<ptr> children; ptr parent; id_t id; BehaviorState status; id_t last_evaluated_child; ptr get_child_for_eval(id_t id); id_t get_last_evaluated_child_id(); virtual BehaviorState internal_evaluate(id_t id_child_for_evaluation) = 0; BehaviorState internal_evaluate(); };
26.820755
82
0.719311
draghan
cc733829dd43fe861230df5866fe3587e4342e0a
1,670
hh
C++
src/cpu/vpred/fcmvp.hh
surya00060/ece-565-course-project
cb96f9be0aa21b6e1a5e10fa62bbb119f3c3a1cd
[ "BSD-3-Clause" ]
null
null
null
src/cpu/vpred/fcmvp.hh
surya00060/ece-565-course-project
cb96f9be0aa21b6e1a5e10fa62bbb119f3c3a1cd
[ "BSD-3-Clause" ]
null
null
null
src/cpu/vpred/fcmvp.hh
surya00060/ece-565-course-project
cb96f9be0aa21b6e1a5e10fa62bbb119f3c3a1cd
[ "BSD-3-Clause" ]
1
2020-12-15T20:53:56.000Z
2020-12-15T20:53:56.000Z
#ifndef __CPU_VPRED_LVP_PRED_HH__ #define __CPU_VPRED_LVP_PRED_HH__ #include "cpu/vpred/vpred_unit.hh" #include <vector> #include "base/statistics.hh" #include "base/sat_counter.hh" #include "base/types.hh" #include "cpu/inst_seq.hh" #include "cpu/static_inst.hh" #include "params/FCMVP.hh" #include "sim/sim_object.hh" class FCMVP : public VPredUnit { public: FCMVP(const FCMVPParams *params); bool lookup(Addr inst_addr, RegVal &value); float getconf(Addr inst_addr, RegVal &value); void updateTable(Addr inst_addr, bool isValuePredicted, bool isValueTaken, RegVal &trueValue); static inline RegVal computeHash(RegVal data) { RegVal hash = 0; RegVal bits = 0; for (int i = 0; i < 8; ++i) { bits = ((1 << 8) - 1) & (data >> (8*i)); hash = hash ^ bits; } return hash; } private: /*Number of history values to track*/ const unsigned historyLength; /** Number of History Table Entries*/ const unsigned historyTableSize; /** Number of History Table Entries*/ const unsigned valuePredictorTableSize; /** Number of bits to control*/ const unsigned ctrBits; /*Array of counters*/ std::vector<SatCounter> classificationTable; /*Array of value predictions*/ std::vector<std::vector<RegVal>> valueHistoryTable; std::vector<RegVal> valuePredictionTable; /*Array of tag value*/ std::vector<Addr> tagTable; }; #endif // __CPU_VPRED_LVP_PRED_HH__
25.30303
102
0.601796
surya00060
cc73743ace3ec7c1299f05c623eb9e78e65b18a8
2,732
hpp
C++
test/estest/graphics/LibPngDecoderTest.hpp
eaglesakura/protoground
2cd7eaf93eaab9a34619b7ded91d3a2b89e9d5d6
[ "MIT" ]
null
null
null
test/estest/graphics/LibPngDecoderTest.hpp
eaglesakura/protoground
2cd7eaf93eaab9a34619b7ded91d3a2b89e9d5d6
[ "MIT" ]
1
2016-10-25T02:09:00.000Z
2016-11-10T02:07:59.000Z
test/estest/graphics/LibPngDecoderTest.hpp
eaglesakura/protoground
2cd7eaf93eaab9a34619b7ded91d3a2b89e9d5d6
[ "MIT" ]
null
null
null
#pragma once #include "estest/protoground-test.hpp" #include "es/graphics/image/png/PngFileDecoder.h" #include "es/graphics/image/IImageDecodeCallback.hpp" namespace es { namespace test { namespace internal { std::shared_ptr<IImageDecodeCallback> newSimpleImageListener() { class PngImageListener : public IImageDecodeCallback { ImageInfo info; bool infoReceived = false; int readedLines = 0; public: PngImageListener() { } virtual ~PngImageListener() { } /** * 画像情報を読み込んだ */ virtual void onImageInfoDecoded(const ImageInfo *info) { ASSERT_NE(info, nullptr); ASSERT_TRUE(info->srcWidth > 0); ASSERT_TRUE(info->srcHeight > 0); this->info = *info; infoReceived = true; } /** * 画像を指定行読み込んだ * * 引数lineは使いまわされる可能性があるため、内部的にテクスチャコピー等を行うこと。 */ virtual void onImageLineDecoded(const ImageInfo *info, const unsafe_array<uint8_t> pixels, const unsigned height) { ASSERT_TRUE(pixels.length > 0); ASSERT_TRUE(height > 0); ASSERT_TRUE(infoReceived); readedLines += height; ASSERT_TRUE(readedLines <= (int) info->srcHeight); } /** * 画像のデコードをキャンセルする場合はtrue */ virtual bool isImageDecodeCancel() { return false; } /** * デコードが完了した */ virtual void onImageDecodeFinished(const ImageInfo *info, const ImageDecodeResult_e result) { ASSERT_EQ(result, ImageDecodeResult_Success); ASSERT_EQ(info->srcHeight, readedLines); } }; sp<IImageDecodeCallback> result(new PngImageListener()); return result; } } /** * 正方形PowerOfTwo PNG画像を読み込む */ TEST(LibPngDecoderTest, DecodeSquarePot_dstRGB8) { sp<IAsset> asset = IProcessContext::getInstance()->getAssetManager()->load("png/square-pot.png"); ASSERT_TRUE((bool) asset); PngFileDecoder decoder; decoder.setOnceReadHeight(25); decoder.setConvertPixelFormat(PixelFormat_RGB888); ASSERT_TRUE(decoder.load(asset, internal::newSimpleImageListener())); } /** * 正方形PowerOfTwo PNG画像を読み込む */ TEST(LibPngDecoderTest, DecodeSquarePot_dstRGBA8) { sp<IAsset> asset = IProcessContext::getInstance()->getAssetManager()->load("png/square-pot.png"); ASSERT_TRUE((bool) asset); PngFileDecoder decoder; decoder.setOnceReadHeight(25); decoder.setConvertPixelFormat(PixelFormat_RGBA8888); ASSERT_TRUE(decoder.load(asset, internal::newSimpleImageListener())); } } }
27.877551
124
0.61896
eaglesakura
cc7424858b6c72272f73481c941b9e55475c869c
1,032
cpp
C++
uva/507.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
3
2018-01-08T02:52:51.000Z
2021-03-03T01:08:44.000Z
uva/507.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
null
null
null
uva/507.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
1
2020-08-13T18:07:35.000Z
2020-08-13T18:07:35.000Z
#include <bits/stdc++.h> using namespace std; vector<int> v; int main(){ //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); int t, co = 0, len, a; for(scanf("%d", &t); t--; ){ scanf("%d", &len); for(int i = 0; i < len - 1; scanf("%d", &a), v.push_back(a), i++); int g = v[0], m = v[0], sum = v[0]; pair<int, int> p = make_pair(1, 2); pair<int, int> q = make_pair(1, 2); for(int i = 1; i < v.size(); i++){ if(sum + v[i] >= v[i]){ sum += v[i]; q.second = i + 2; } else{ sum = v[i]; q = make_pair(i + 1, i + 2); } if(sum >= g){ if(sum > g) p = make_pair(q.first, q.second); else if(sum == g && (q.second - q.first) > (p.second - p.first)) p = make_pair(q.first, q.second); g = sum; } } if(g > 0) printf("The nicest part of route %d is between stops %d and %d\n", ++co, p.first, p.second, g); else printf("Route %d has no nice parts\n", ++co); v.clear(); } return 0; }
29.485714
109
0.471899
cosmicray001
cc789143c50ca56072bd50c685f65f77ede4ed74
413
cpp
C++
Projects/AnalizadorLexico/AnalizadorLexico/Est.cpp
JoaquinRMtz/Escuela
bdd0e902c1a836880c018845b7cac2cccbaa1bed
[ "MIT" ]
null
null
null
Projects/AnalizadorLexico/AnalizadorLexico/Est.cpp
JoaquinRMtz/Escuela
bdd0e902c1a836880c018845b7cac2cccbaa1bed
[ "MIT" ]
null
null
null
Projects/AnalizadorLexico/AnalizadorLexico/Est.cpp
JoaquinRMtz/Escuela
bdd0e902c1a836880c018845b7cac2cccbaa1bed
[ "MIT" ]
null
null
null
#include "Est.h" Est::Est(Id^ i, Expr^ x) { id = i; expr = x; if (comprobar(id->tipo, expr->tipo) == nullptr) error("Error de tipo"); } Tipo^ Est::comprobar(Tipo^ p1, Tipo^ p2){ if (Tipo::numerico(p1) && Tipo::numerico(p2))return p2; else if (p1 == Tipo::Bool && p2 == Tipo::Bool) return p2; else return nullptr; } void Est::gen(int b, int a){ emitir(id->toString() + " = " + expr->gen()->toString()); }
22.944444
72
0.598063
JoaquinRMtz
cc79f3ef2c2041b41a4897dd9196dab1851b8bfb
6,268
hpp
C++
cmdstan/stan/lib/stan_math/stan/math/rev/mat/functor/ode_system.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/rev/mat/functor/ode_system.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/rev/mat/functor/ode_system.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_REV_MAT_FUNCTOR_ODE_SYSTEM_HPP #define STAN_MATH_REV_MAT_FUNCTOR_ODE_SYSTEM_HPP #include <stan/math/rev/core.hpp> #include <stan/math/prim/arr/fun/value_of.hpp> #include <iostream> #include <sstream> #include <string> #include <vector> namespace stan { namespace math { /** * Internal representation of an ODE model object which provides * convenient Jacobian functions to obtain gradients wrt to states * and parameters. Can be used to provide analytic Jacobians via * partial template specialisation. * * @tparam F type of functor for the base ode system. */ template <typename F> class ode_system { private: const F& f_; const std::vector<double> theta_; const std::vector<double>& x_; const std::vector<int>& x_int_; std::ostream* msgs_; std::string error_msg(size_t y_size, size_t dy_dt_size) const { std::stringstream msg; msg << "ode_system: size of state vector y (" << y_size << ")" << " and derivative vector dy_dt (" << dy_dt_size << ")" << " in the ODE functor do not match in size."; return msg.str(); } public: /** * Construct an ODE model with the specified base ODE system, * parameters, data, and a message stream. * * @param[in] f the base ODE system functor. * @param[in] theta parameters of the ode. * @param[in] x real data. * @param[in] x_int integer data. * @param[in] msgs stream to which messages are printed. */ ode_system(const F& f, const std::vector<double> theta, const std::vector<double>& x, const std::vector<int>& x_int, std::ostream* msgs) : f_(f), theta_(theta), x_(x), x_int_(x_int), msgs_(msgs) { } /** * Calculate the RHS of the ODE * * @param[in] t time. * @param[in] y state of the ode system at time t. * @param[out] dy_dt ODE RHS */ template <typename Derived1> inline void operator()(double t, const std::vector<double>& y, Eigen::MatrixBase<Derived1>& dy_dt) const { const std::vector<double> dy_dt_vec = f_(t, y, theta_, x_, x_int_, msgs_); if (unlikely(y.size() != dy_dt_vec.size())) throw std::runtime_error(error_msg(y.size(), dy_dt_vec.size())); dy_dt = Eigen::Map<const Eigen::VectorXd>(&dy_dt_vec[0], y.size()); } /** * Calculate the Jacobian of the ODE RHS wrt to states y. The * function expects the output objects to have correct sizes, * i.e. dy_dt must be length N and Jy a NxN matrix (N states). * * @param[in] t time. * @param[in] y state of the ode system at time t. * @param[out] dy_dt ODE RHS * @param[out] Jy Jacobian of ODE RHS wrt to y. */ template <typename Derived1, typename Derived2> inline void jacobian(double t, const std::vector<double>& y, Eigen::MatrixBase<Derived1>& dy_dt, Eigen::MatrixBase<Derived2>& Jy) const { using Eigen::Matrix; using Eigen::Map; using Eigen::RowVectorXd; using std::vector; vector<double> grad(y.size()); Map<RowVectorXd> grad_eig(&grad[0], y.size()); try { start_nested(); vector<var> y_var(y.begin(), y.end()); vector<var> dy_dt_var = f_(t, y_var, theta_, x_, x_int_, msgs_); if (unlikely(y.size() != dy_dt_var.size())) throw std::runtime_error(error_msg(y.size(), dy_dt_var.size())); for (size_t i = 0; i < dy_dt_var.size(); ++i) { dy_dt(i) = dy_dt_var[i].val(); set_zero_all_adjoints_nested(); dy_dt_var[i].grad(y_var, grad); Jy.row(i) = grad_eig; } } catch (const std::exception& e) { recover_memory_nested(); throw; } recover_memory_nested(); } /** * Calculate the Jacobian of the ODE RHS wrt to states y and * parameters theta. The function expects the output objects to * have correct sizes, i.e. dy_dt must be length N, Jy a NxN * matrix and Jtheta a NxM matrix (N states, M parameters). * * @param[in] t time. * @param[in] y state of the ode system at time t. * @param[out] dy_dt ODE RHS * @param[out] Jy Jacobian of ODE RHS wrt to y. * @param[out] Jtheta Jacobian of ODE RHS wrt to theta. */ template <typename Derived1, typename Derived2> inline void jacobian(double t, const std::vector<double>& y, Eigen::MatrixBase<Derived1>& dy_dt, Eigen::MatrixBase<Derived2>& Jy, Eigen::MatrixBase<Derived2>& Jtheta) const { using Eigen::Dynamic; using Eigen::Map; using Eigen::Matrix; using Eigen::RowVectorXd; using std::vector; vector<double> grad(y.size() + theta_.size()); Map<RowVectorXd> grad_eig(&grad[0], y.size() + theta_.size()); try { start_nested(); vector<var> y_var(y.begin(), y.end()); vector<var> theta_var(theta_.begin(), theta_.end()); vector<var> z_var; z_var.reserve(y.size() + theta_.size()); z_var.insert(z_var.end(), y_var.begin(), y_var.end()); z_var.insert(z_var.end(), theta_var.begin(), theta_var.end()); vector<var> dy_dt_var = f_(t, y_var, theta_var, x_, x_int_, msgs_); if (unlikely(y.size() != dy_dt_var.size())) throw std::runtime_error(error_msg(y.size(), dy_dt_var.size())); for (size_t i = 0; i < dy_dt_var.size(); ++i) { dy_dt(i) = dy_dt_var[i].val(); set_zero_all_adjoints_nested(); dy_dt_var[i].grad(z_var, grad); Jy.row(i) = grad_eig.leftCols(y.size()); Jtheta.row(i) = grad_eig.rightCols(theta_.size()); } } catch (const std::exception& e) { recover_memory_nested(); throw; } recover_memory_nested(); } }; } } #endif
38.219512
77
0.565571
yizhang-cae
cc7fbe6860a7b75ff0ae6877e7a2427095c20a03
3,570
hpp
C++
Source/GameComponents/PhysicsObject.hpp
storm20200/WaterEngine
537910bc03e6d4016c9b22cf616d25afe40f77af
[ "MIT" ]
null
null
null
Source/GameComponents/PhysicsObject.hpp
storm20200/WaterEngine
537910bc03e6d4016c9b22cf616d25afe40f77af
[ "MIT" ]
2
2015-03-17T01:32:10.000Z
2015-03-19T18:58:28.000Z
Source/GameComponents/PhysicsObject.hpp
storm20200/WaterEngine
537910bc03e6d4016c9b22cf616d25afe40f77af
[ "MIT" ]
null
null
null
#if !defined WATER_PHYSICS_OBJECT_INCLUDED #define WATER_PHYSICS_OBJECT_INCLUDED // Engine headers. #include <GameComponents/Collider.hpp> #include <GameComponents/GameObject.hpp> // Engine namespace. namespace water { /// <summary> /// An abstract class for physics objects. Any object which the physics system manages must inherit from this class. /// PhysicsObject's can be added to a GameState's collection of managed objects which will be given to the physics /// system every physicUpdate(), this will apply collision detection as well as other features of the system. /// </summary> class PhysicsObject : public GameObject { public: /////////////////////////////////// /// Constructors and destructor /// /////////////////////////////////// PhysicsObject() = default; PhysicsObject (const PhysicsObject& copy) = default; PhysicsObject& operator= (const PhysicsObject& copy) = default; PhysicsObject (PhysicsObject&& move); PhysicsObject& operator= (PhysicsObject&& move); // Ensure destructor is virtual. virtual ~PhysicsObject() override {} ///////////////// /// Collision /// ///////////////// /// <summary> /// This function is called every time two collision objects intersect. This will be called AFTER the objects have been moved /// by the physics system and will be called on both objects. /// </summary> /// <param name="collision"> The object being collided with. </param> virtual void onCollision (PhysicsObject* const collision) = 0; /// <summary> /// The function called on trigger objects when either another trigger object or a collision object intersects the trigger zone. /// This will be called every frame until the object leaves. /// </summary> /// <param name="collision"> The object intersecting the trigger zone. </param> virtual void onTrigger (PhysicsObject* const collision) = 0; /////////////////////////// /// Getters and setters /// /////////////////////////// /// <summary> Indicates whether the PhysicsObject is static or not. </summary> bool isStatic() const { return m_isStatic; } /// <summary> /// Obtain a reference to the collider of the physics object. This contains information relating to how the physics /// object should be handled by the engine. /// </summary> /// <returns> A reference to the collider. </returns> const Collider& getCollider() const { return m_collider; } /// <summary> Sets whether the PhysicsObject is static. If they're static they will not be moved by the physics system. </summary> /// <param name="isStatic"> Whether it should be static. </param> void setStatic (const bool isStatic) { m_isStatic = isStatic; } protected: /////////////////////////// /// Implementation data /// /////////////////////////// Collider m_collider { }; //!< The collision information of the PhysicsObject. bool m_isStatic { true }; //!< Determines whether collision should cause this object to move or not. }; } #endif
41.511628
142
0.557983
storm20200
cc82da22e8b2c843ea0f15028e5f447aa29db572
49,995
cpp
C++
unalz-0.65/UnAlz.cpp
kippler/unalz
457884d21962caa12085bfb6ec5bd12f3eb93c00
[ "Zlib" ]
1
2021-04-13T04:49:58.000Z
2021-04-13T04:49:58.000Z
unalz-0.65/UnAlz.cpp
kippler/unalz
457884d21962caa12085bfb6ec5bd12f3eb93c00
[ "Zlib" ]
null
null
null
unalz-0.65/UnAlz.cpp
kippler/unalz
457884d21962caa12085bfb6ec5bd12f3eb93c00
[ "Zlib" ]
null
null
null
 #ifdef _WIN32 # include "zlib/zlib.h" # include "bzip2/bzlib.h" #else # include <zlib.h> # include <bzlib.h> #endif #include "UnAlz.h" #ifdef _WIN32 # pragma warning( disable : 4996 ) // crt secure warning #endif // utime 함수 처리 #if defined(_WIN32) || defined(__CYGWIN__) # include <time.h> # include <sys/utime.h> #endif #ifdef __GNUC__ # include <time.h> # include <utime.h> #endif // mkdir #ifdef _WIN32 # include <direct.h> #else # include <sys/stat.h> #endif #ifdef _UNALZ_ICONV // code page support # include <iconv.h> #endif #if defined(__linux__) || defined(__GLIBC__) || defined(__GNU__) || defined(__APPLE__) # include <errno.h> #endif #if defined(__NetBSD__) # include <sys/param.h> // __NetBSD_Version__ # include <errno.h> // iconv.h 때문에 필요 #endif #ifdef _WIN32 // safe string 처리 # include <strsafe.h> #endif // ENDIAN 처리 #ifdef _WIN32 // (L) # define swapint64(a) (UINT64) ( (((a)&0x00000000000000FFL) << 56) | (((a)&0x000000000000FF00L) << 40) | (((a)&0x0000000000FF0000L) << 24) | (((a)&0x00000000FF000000L) << 8) | (((a)&0x000000FF00000000L) >> 8) | (((a)&0x0000FF0000000000L) >> 24) | (((a)&0x00FF000000000000L) >> 40) | (((a)&0xFF00000000000000L) >> 56) ) #else // (LL) # define swapint64(a) (UINT64) ( (((a)&0x00000000000000FFLL) << 56) | (((a)&0x000000000000FF00LL) << 40) | (((a)&0x0000000000FF0000LL) << 24) | (((a)&0x00000000FF000000LL) << 8) | (((a)&0x000000FF00000000LL) >> 8) | (((a)&0x0000FF0000000000LL) >> 24) | (((a)&0x00FF000000000000LL) >> 40) | (((a)&0xFF00000000000000LL) >> 56) ) #endif #define swapint32(a) ((((a)&0xff)<<24)+(((a>>8)&0xff)<<16)+(((a>>16)&0xff)<<8)+(((a>>24)&0xff))) #define swapint16(a) (((a)&0xff)<<8)+(((a>>8)&0xff)) typedef UINT16 (*_unalz_le16toh)(UINT16 a); typedef UINT32 (*_unalz_le32toh)(UINT32 a); typedef UINT64 (*_unalz_le64toh)(UINT64 a); static _unalz_le16toh unalz_le16toh=NULL; static _unalz_le32toh unalz_le32toh=NULL; static _unalz_le64toh unalz_le64toh=NULL; static UINT16 le16tole(UINT16 a){return a;} static UINT32 le32tole(UINT32 a){return a;} static UINT64 le64tole(UINT64 a){return a;} static UINT16 le16tobe(UINT16 a){return swapint16(a);} static UINT32 le32tobe(UINT32 a){return swapint32(a);} static UINT64 le64tobe(UINT64 a){return swapint64(a);} #ifndef MAX_PATH # define MAX_PATH 260*6 // 그냥 .. 충분히.. #endif #ifdef _WIN32 # define PATHSEP "\\" # define PATHSEPC '\\' #else # define PATHSEP "/" # define PATHSEPC '/' #endif static time_t dosTime2TimeT(UINT32 dostime) // from INFO-ZIP src { struct tm t; t.tm_isdst = -1; t.tm_sec = (((int)dostime) << 1) & 0x3e; t.tm_min = (((int)dostime) >> 5) & 0x3f; t.tm_hour = (((int)dostime) >> 11) & 0x1f; t.tm_mday = (int)(dostime >> 16) & 0x1f; t.tm_mon = ((int)(dostime >> 21) & 0x0f) - 1; t.tm_year = ((int)(dostime >> 25) & 0x7f) + 80; return mktime(&t); } static BOOL IsBigEndian(void) { union { short a; char b[2]; } endian; endian.a = 0x0102; if(endian.b[0] == 0x02) return FALSE; return TRUE; } #ifdef _WIN32 # define safe_sprintf StringCbPrintfA #else # define safe_sprintf snprintf #endif // 64bit file handling support #if (_FILE_OFFSET_BITS==64) # define unalz_fseek fseeko # define unalz_ftell ftello #else # define unalz_fseek fseek # define unalz_ftell ftell #endif // error string table <- CUnAlz::ERR 의 번역 static const char* errorstrtable[]= { "no error", // ERR_NOERR "general error", // ERR_GENERAL "can't open archive file", // ERR_CANT_OPEN_FILE "can't open dest file or path", // ERR_CANT_OPEN_DEST_FILE // "can't create dest path", // ERR_CANT_CREATE_DEST_PATH "corrupted file", // ERR_CORRUPTED_FILE "not alz file", // ERR_NOT_ALZ_FILE "can't read signature", // ERR_CANT_READ_SIG "can't read file", // ERR_CANT_READ_FILE "error at read header", // ERR_AT_READ_HEADER "invalid filename length", // ERR_INVALID_FILENAME_LENGTH "invalid extrafield length", // ERR_INVALID_EXTRAFIELD_LENGTH, "can't read central directory structure head", // ERR_CANT_READ_CENTRAL_DIRECTORY_STRUCTURE_HEAD, "invalid filename size", // ERR_INVALID_FILENAME_SIZE, "invalid extrafield size", // ERR_INVALID_EXTRAFIELD_SIZE, "invalid filecomment size", // ERR_INVALID_FILECOMMENT_SIZE, "cant' read header", // ERR_CANT_READ_HEADER, "memory allocation failed", // ERR_MEM_ALLOC_FAILED, "file read error", // ERR_FILE_READ_ERROR, "inflate failed", // ERR_INFLATE_FAILED, "bzip2 decompress failed", // ERR_BZIP2_FAILED, "invalid file CRC", // ERR_INVALID_FILE_CRC "unknown compression method", // ERR_UNKNOWN_COMPRESSION_METHOD "iconv-can't open iconv", // ERR_ICONV_CANT_OPEN, "iconv-invalid multisequence of characters", // ERR_ICONV_INVALID_MULTISEQUENCE_OF_CHARACTERS, "iconv-incomplete multibyte sequence", // ERR_ICONV_INCOMPLETE_MULTIBYTE_SEQUENCE, "iconv-not enough space of buffer to convert", // ERR_ICONV_NOT_ENOUGH_SPACE_OF_BUFFER_TO_CONVERT, "iconv-etc", // ERR_ICONV_ETC, "password was not set", // ERR_PASSWD_NOT_SET, "invalid password", // ERR_INVALID_PASSWD, "user aborted", }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// ctor /// @date 2004-03-06 오후 11:19:49 //////////////////////////////////////////////////////////////////////////////////////////////////// CUnAlz::CUnAlz() { memset(m_files, 0, sizeof(m_files)); m_nErr = ERR_NOERR; m_posCur = m_fileList.end();//(FileList::iterator)NULL; m_pFuncCallBack = NULL; m_pCallbackParam = NULL; m_bHalt = FALSE; m_nFileCount = 0; m_nCurFile = -1; m_nVirtualFilePos = 0; m_nCurFilePos = 0; m_bIsEOF = FALSE; m_bIsEncrypted = FALSE; m_bIsDataDescr = FALSE; m_bPipeMode = FALSE; #ifdef _UNALZ_ICONV #ifdef _UNALZ_UTF8 safe_strcpy(m_szToCodepage, "UTF-8",UNALZ_LEN_CODEPAGE) ; // 기본적으로 utf-8 #else safe_strcpy(m_szToCodepage, "CP949",UNALZ_LEN_CODEPAGE) ; // 기본적으로 CP949 #endif // _UNALZ_UTF8 safe_strcpy(m_szFromCodepage, "CP949",UNALZ_LEN_CODEPAGE); // alz 는 949 만 지원 #endif // _UNALZ_ICONV // check endian if(unalz_le16toh==NULL) { if(IsBigEndian()) { unalz_le16toh = le16tobe; unalz_le32toh = le32tobe; unalz_le64toh = le64tobe; } else { unalz_le16toh = le16tole; unalz_le32toh = le32tole; unalz_le64toh = le64tole; } } } //////////////////////////////////////////////////////////////////////////////////////////////////// /// dtor /// @date 2004-03-06 오후 11:19:52 //////////////////////////////////////////////////////////////////////////////////////////////////// CUnAlz::~CUnAlz() { Close(); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// progress callback func setting /// @date 2004-03-01 오전 6:02:05 //////////////////////////////////////////////////////////////////////////////////////////////////// void CUnAlz::SetCallback(_UnAlzCallback* pFunc, void* param) { m_pFuncCallBack = pFunc; m_pCallbackParam = param; } #ifdef _WIN32 #if !defined(__GNUWIN32__) && !defined(__GNUC__) //////////////////////////////////////////////////////////////////////////////////////////////////// /// 파일 열기 /// @param szPathName /// @return /// @date 2004-03-06 오후 11:03:59 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::Open(LPCWSTR szPathName) { char szPathNameA[MAX_PATH]; ::WideCharToMultiByte(CP_ACP, 0, szPathName, -1, szPathNameA, MAX_PATH, NULL, NULL); return Open(szPathNameA); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 대상 파일 세팅하기. /// @param szFileName /// @return /// @date 2004-03-06 오후 11:06:20 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::SetCurrentFile(LPCWSTR szFileName) { char szFileNameA[MAX_PATH]; ::WideCharToMultiByte(CP_ACP, 0, szFileName, -1, szFileNameA, MAX_PATH, NULL, NULL); return SetCurrentFile(szFileNameA); } BOOL CUnAlz::IsFolder(LPCWSTR szPathName) { UINT32 dwRet; dwRet = GetFileAttributesW(szPathName); if(dwRet==0xffffffff) return FALSE; if(dwRet & FILE_ATTRIBUTE_DIRECTORY) return TRUE; return FALSE; } #endif // __GNUWIN32__ #endif // _WIN32 BOOL CUnAlz::Open(const char* szPathName) { if(FOpen(szPathName)==FALSE) { m_nErr = ERR_CANT_OPEN_FILE; return FALSE; } BOOL bValidAlzHeader = FALSE; // file 분석시작.. for(;;) { SIGNATURE sig; BOOL ret; if(FEof()) break; //int pos = unalz_ftell(m_fp); sig = ReadSignature(); if(sig==SIG_EOF) { break; } if(sig==SIG_ERROR) { if(bValidAlzHeader) m_nErr = ERR_CORRUPTED_FILE; // 손상된 파일 else m_nErr = ERR_NOT_ALZ_FILE; // alz 파일이 아니다. return FALSE; // 깨진 파일.. } if(sig==SIG_ALZ_FILE_HEADER) { ret = ReadAlzFileHeader(); bValidAlzHeader = TRUE; // alz 파일은 맞다. } else if(sig==SIG_LOCAL_FILE_HEADER) ret = ReadLocalFileheader(); else if(sig==SIG_CENTRAL_DIRECTORY_STRUCTURE) ret = ReadCentralDirectoryStructure(); else if(sig==SIG_ENDOF_CENTRAL_DIRECTORY_RECORD) ret = ReadEndofCentralDirectoryRecord(); else { // 미구현된 signature ? 깨진 파일 ? ASSERT(0); m_nErr = ERR_CORRUPTED_FILE; return FALSE; } if(ret==FALSE) { return FALSE; } if(FEof()) break; } return TRUE; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 파일 닫기.. /// @return /// @date 2004-03-06 오후 11:04:21 //////////////////////////////////////////////////////////////////////////////////////////////////// void CUnAlz::Close() { FClose(); // 목록 날리기.. FileList::iterator i; for(i=m_fileList.begin(); i<m_fileList.end(); i++) { i->Clear(); } m_posCur = m_fileList.end();//(FileList::iterator)NULL; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// FILE 내의 SIGNATURE 읽기 /// @return /// @date 2004-03-06 오후 11:04:47 //////////////////////////////////////////////////////////////////////////////////////////////////// CUnAlz::SIGNATURE CUnAlz::ReadSignature() { UINT32 dwSig; if(FRead(&dwSig, sizeof(dwSig))==FALSE) { if(FEof()) return SIG_EOF; m_nErr = ERR_CANT_READ_SIG; return SIG_ERROR; } return (SIGNATURE)unalz_le32toh(dwSig); // little to host; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// ALZ HEADER SIGNATURE 읽기 /// @return /// @date 2004-03-06 오후 11:05:11 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::ReadAlzFileHeader() { SAlzHeader header; if(FRead(&header, sizeof(header))==FALSE) { ASSERT(0); m_nErr = ERR_CANT_READ_FILE; return FALSE; } return TRUE; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 각각의 파일 헤더 읽기 /// @return /// @date 2004-03-06 오후 11:05:18 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::ReadLocalFileheader() { SAlzLocalFileHeader zipHeader; int ret; ret = FRead(&(zipHeader.head), sizeof(zipHeader.head)); if(ret==FALSE) { m_nErr = ERR_AT_READ_HEADER; return FALSE; } // ALZ 확장.. if( (zipHeader.head.fileDescriptor & (SHORT)1) != 0){ m_bIsEncrypted = TRUE; // 하나라도 암호 걸렸으면 세팅한다. } if( (zipHeader.head.fileDescriptor & (SHORT)8) != 0){ m_bIsDataDescr = TRUE; } int byteLen = zipHeader.head.fileDescriptor/0x10; if(byteLen) { FRead(&(zipHeader.compressionMethod), sizeof(zipHeader.compressionMethod)); FRead(&(zipHeader.unknown), sizeof(zipHeader.unknown)); FRead(&(zipHeader.fileCRC), sizeof(zipHeader.fileCRC)); FRead(&(zipHeader.compressedSize), byteLen); FRead(&(zipHeader.uncompressedSize), byteLen); // 압축 사이즈가 없다. } // little to system zipHeader.fileCRC = unalz_le32toh(zipHeader.fileCRC); zipHeader.head.fileNameLength = unalz_le16toh(zipHeader.head.fileNameLength); zipHeader.compressedSize = unalz_le64toh(zipHeader.compressedSize); zipHeader.uncompressedSize = unalz_le64toh(zipHeader.uncompressedSize); // FILE NAME zipHeader.fileName = (char*)malloc(zipHeader.head.fileNameLength+sizeof(char)); if(zipHeader.fileName==NULL) { m_nErr = ERR_INVALID_FILENAME_LENGTH; return FALSE; } FRead(zipHeader.fileName, zipHeader.head.fileNameLength); if(zipHeader.head.fileNameLength > MAX_PATH - 5) zipHeader.head.fileNameLength = MAX_PATH - 5; zipHeader.fileName[zipHeader.head.fileNameLength] = (CHAR)NULL; #ifdef _UNALZ_ICONV // codepage convert if(strlen(m_szToCodepage)) { #define ICONV_BUF_SIZE (260*6) // utf8 은 최대 6byte size_t ileft, oleft; iconv_t cd; size_t iconv_result; size_t size; char inbuf[ICONV_BUF_SIZE]; char outbuf[ICONV_BUF_SIZE]; #if defined(__FreeBSD__) || defined(__CYGWIN__) || defined(__NetBSD__) const char *inptr = inbuf; #else char *inptr = inbuf; #endif char *outptr = outbuf; size = strlen(zipHeader.fileName)+1; strncpy(inbuf, zipHeader.fileName, size); ileft = size; oleft = sizeof(outbuf); cd = iconv_open(m_szToCodepage, m_szFromCodepage); // 보통 "CP949" 에서 "UTF-8" 로 iconv(cd, NULL, NULL, NULL, NULL); if( cd == (iconv_t)(-1)) { m_nErr = ERR_ICONV_CANT_OPEN; // printf("Converting Error : Cannot open iconv"); return FALSE; } else { iconv_result = iconv(cd, &inptr, &ileft, &outptr, &oleft); if(iconv_result== (size_t)(-1)) // iconv 실패.. { if (errno == EILSEQ) m_nErr = ERR_ICONV_INVALID_MULTISEQUENCE_OF_CHARACTERS; // printf("Invalid Multibyte Sequence of Characters"); else if (errno == EINVAL) m_nErr = ERR_ICONV_INCOMPLETE_MULTIBYTE_SEQUENCE; //printf("Incomplete multibyte sequence"); else if (errno != E2BIG) m_nErr = ERR_ICONV_NOT_ENOUGH_SPACE_OF_BUFFER_TO_CONVERT; // printf("Not enough space of buffer to convert"); else m_nErr = ERR_ICONV_ETC; iconv_close(cd); return FALSE; } else { outbuf[ICONV_BUF_SIZE-oleft] = 0; if(zipHeader.fileName) free(zipHeader.fileName); zipHeader.fileName = strdup(outbuf); if (zipHeader.fileName == NULL) { m_nErr = ERR_ICONV_ETC; iconv_close(cd); return FALSE; } // printf("\n Converted File Name : %s", outbuf); } iconv_close(cd); } } #endif /* // EXTRA FIELD LENGTH if(zipHeader.head.extraFieldLength) { zipHeader.extraField = (BYTE*)malloc(zipHeader.head.extraFieldLength); if(zipHeader.extraField==NULL) { m_nErr = ERR_INVALID_EXTRAFIELD_LENGTH; return FALSE; } FRead(zipHeader.extraField, 1, zipHeader.head.extraFieldLength); } */ if(IsEncryptedFile(zipHeader.head.fileDescriptor)) FRead(zipHeader.encChk, ALZ_ENCR_HEADER_LEN); // xf86 // SKIP FILE DATA zipHeader.dwFileDataPos = FTell(); // data 의 위치 저장하기.. FSeek(FTell()+zipHeader.compressedSize); // DATA DESCRIPTOR /* if(zipHeader.head.generalPurposeBitFlag.bit1) { FRead(zipHeader.extraField, 1, sizeof(zipHeader.extraField),); } */ /* #ifdef _DEBUG printf("NAME:%s COMPRESSED SIZE:%d UNCOMPRESSED SIZE:%d COMP METHOD:%d\n", zipHeader.fileName, zipHeader.compressedSize, zipHeader.uncompressedSize, zipHeader.compressionMethod ); #endif */ // 파일을 목록에 추가한다.. m_fileList.push_back(zipHeader); return TRUE; } BOOL CUnAlz::ReadCentralDirectoryStructure() { SCentralDirectoryStructure header; if(FRead(&header, sizeof(header.head))==FALSE) { m_nErr = ERR_CANT_READ_CENTRAL_DIRECTORY_STRUCTURE_HEAD; return FALSE; } /* // read file name if(header.head.fileNameLength) { header.fileName = (char*)malloc(header.head.fileNameLength+1); if(header.fileName==NULL) { m_nErr = ERR_INVALID_FILENAME_SIZE; return FALSE; } FRead(header.fileName, 1, header.head.fileNameLength, m_fp); header.fileName[header.head.fileNameLength] = NULL; } // extra field; if(header.head.extraFieldLength) { header.extraField = (BYTE*)malloc(header.head.extraFieldLength); if(header.extraField==NULL) { m_nErr = ERR_INVALID_EXTRAFIELD_SIZE; return FALSE; } FRead(header.extraField, 1, header.head.extraFieldLength, m_fp); } // file comment; if(header.head.fileCommentLength) { header.fileComment = (char*)malloc(header.head.fileCommentLength+1); if(header.fileComment==NULL) { m_nErr = ERR_INVALID_FILECOMMENT_SIZE; return FALSE; } FRead(header.fileComment, 1, header.head.fileCommentLength, m_fp); header.fileComment[header.head.fileCommentLength] = NULL; } */ return TRUE; } BOOL CUnAlz::ReadEndofCentralDirectoryRecord() { /* SEndOfCentralDirectoryRecord header; if(FRead(&header, sizeof(header.head), 1, m_fp)!=1) { m_nErr = ERR_CANT_READ_HEADER; return FALSE; } if(header.head.zipFileCommentLength) { header.fileComment = (char*)malloc(header.head.zipFileCommentLength+1); if(header.fileComment==NULL) { m_nErr = ERR_INVALID_FILECOMMENT_SIZE; return FALSE; } FRead(header.fileComment, 1, header.head.zipFileCommentLength, m_fp); header.fileComment[header.head.zipFileCommentLength] = NULL; } */ return TRUE; } BOOL CUnAlz::SetCurrentFile(const char* szFileName) { FileList::iterator i; // 순차적으로 찾는다. for(i=m_fileList.begin(); i<m_fileList.end(); i++) { #ifdef _WIN32 if(stricmp(i->fileName, szFileName)==0) #else if(strcmp(i->fileName, szFileName)==0) #endif { m_posCur = i; return TRUE; } } m_posCur = m_fileList.end();//(FileList::iterator)NULL; return FALSE; } void CUnAlz::SetCurrentFile(FileList::iterator newPos) { m_posCur = newPos; } #ifndef MAX_WBITS # define MAX_WBITS 15 /* 32K LZ77 window */ #endif //////////////////////////////////////////////////////////////////////////////////////////////////// /// 버퍼에 압축 풀기. 버퍼는 당근 충분한 크기가 준비되어 있어야 한다. /// @param pDestBuf /// @return /// @date 2004-03-07 오전 12:26:13 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::ExtractCurrentFileToBuf(BYTE* pDestBuf, int nBufSize) { SExtractDest dest; dest.nType = ET_MEM; dest.buf = pDestBuf; dest.bufpos = 0; dest.bufsize = nBufSize; return ExtractTo(&dest); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 현재 파일 (SetCurrentFile로 지)을 대상 경로에 대상 파일로 푼다. /// @param szDestPathName - 대상 경로 /// @param szDestFileName - 대상 파일명, NULL 이면 원래 파일명 사용 /// @return /// @date 2004-03-06 오후 11:06:59 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::ExtractCurrentFile(const char* szDestPathName, const char* szDestFileName) { if(m_posCur==m_fileList.end()/*(FileList::iterator)NULL*/) {ASSERT(0); return FALSE;} BOOL ret=FALSE; SExtractDest dest; char szDestPathFileName[MAX_PATH]; if(chkValidPassword() == FALSE) { return FALSE; } if( szDestPathName==NULL|| strlen(szDestPathName) + (szDestFileName?strlen(szDestFileName):strlen(m_posCur->fileName))+1 > MAX_PATH ) // check buffer overflow { ASSERT(0); m_nErr = ERR_GENERAL; return FALSE; } // 경로명 safe_strcpy(szDestPathFileName, szDestPathName, MAX_PATH); if(szDestPathFileName[strlen(szDestPathFileName)]!=PATHSEPC) safe_strcat(szDestPathFileName, PATHSEP, MAX_PATH); // 파일명 if(szDestFileName) safe_strcat(szDestPathFileName, szDestFileName, MAX_PATH); else safe_strcat(szDestPathFileName, m_posCur->fileName, MAX_PATH); // ../../ 형식의 보안 버그 확인 if( strstr(szDestPathFileName, "../")|| strstr(szDestPathFileName, "..\\")) { ASSERT(0); m_nErr = ERR_GENERAL; return FALSE; } #ifndef _WIN32 { char* p = szDestPathFileName; // 경로 delimiter 바꾸기 while(*p) { if(*p=='\\') *p='/'; p++; } } #endif // 압축풀 대상 ( 파일 ) dest.nType = ET_FILE; if(m_bPipeMode) dest.fp = stdout; // pipe mode 일 경우 stdout 출력 else dest.fp = fopen(szDestPathFileName, "wb"); // 타입이 폴더일 경우.. if(m_bPipeMode==FALSE && (m_posCur->head.fileAttribute) & ALZ_FILEATTR_DIRECTORY ) { //printf("digpath:%s\n", szDestPathFileName); // 경로파기 DigPath(szDestPathFileName); return TRUE; // m_nErr = ERR_CANT_CREATE_DEST_PATH; // return FALSE; } // 파일 열기 실패시 - 경로를 파본다 if(dest.fp==NULL) { DigPath(szDestPathFileName); dest.fp = fopen(szDestPathFileName, "wb"); } // 그래도 파일열기 실패시. if(dest.fp==NULL) { // 대상 파일 열기 실패 m_nErr = ERR_CANT_OPEN_DEST_FILE; //printf("dest pathfilename:%s\n",szDestPathFileName); if(m_pFuncCallBack) { // CHAR buf[1024]; // sprintf(buf, "파일 열기 실패 : %s", szDestPathFileName); // m_pFuncCallBack(buf, 0,0,m_pCallbackParam, NULL); } return FALSE; } //#endif // CALLBACK 세팅 if(m_pFuncCallBack) m_pFuncCallBack(m_posCur->fileName, 0,m_posCur->uncompressedSize,m_pCallbackParam, NULL); ret = ExtractTo(&dest); if(dest.fp!=NULL) { fclose(dest.fp); // file time setting - from unalz_wcx_01i.zip utimbuf tmp; tmp.actime = 0; // 마지막 엑세스 타임 tmp.modtime = dosTime2TimeT(m_posCur->head.fileTimeDate); // 마지막 수정일자만 변경(만든 날자는 어떻게 바꾸지?) utime(m_posCur->fileName, &tmp); } return ret; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 대상에 압축 풀기.. /// @param dest /// @return /// @date 2004-03-07 오전 12:44:36 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::ExtractTo(SExtractDest* dest) { BOOL ret = FALSE; // 압축 방법에 따라서 압축 풀기 if(m_posCur->compressionMethod==COMP_NOCOMP) { ret = ExtractRawfile(dest, *m_posCur); } else if(m_posCur->compressionMethod==COMP_BZIP2) { ret = ExtractBzip2(dest, *m_posCur); // bzip2 } else if(m_posCur->compressionMethod==COMP_DEFLATE) { ret = ExtractDeflate2(dest, *m_posCur); // deflate } else // COMP_UNKNOWN { // alzip 5.6 부터 추가된 포맷(5.5 에서는 풀지 못한다. 영문 5.51 은 푼다 ) // 하지만 어떤 버전에서 이 포맷을 만들어 내는지 정확히 알 수 없다. // 공식으로 릴리즈된 알집은 이 포맷을 만들어내지 않는다. 비공식(베타?)으로 배포된 버전에서만 이 포맷을 만들어낸다. m_nErr = ERR_UNKNOWN_COMPRESSION_METHOD; ASSERT(0); ret = FALSE; } return ret; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// DEFLATE 로 풀기 - 테스트용 함수. 모든 파일을 한꺼번에 읽어서 푼다. 실제 사용 안함. /// @param fp - 대상 파일 /// @param file - 소스 파일 정보 /// @return /// @date 2004-03-06 오후 11:09:17 //////////////////////////////////////////////////////////////////////////////////////////////////// /* BOOL CUnAlz::ExtractDeflate(FILE* fp, SAlzLocalFileHeader& file) { z_stream stream; BYTE* pInBuf=NULL; BYTE* pOutBuf=NULL; int nInBufSize = file.compressedSize; int nOutBufSize = file.uncompressedSize; int err; int flush=Z_SYNC_FLUSH; BOOL ret = FALSE; memset(&stream, 0, sizeof(stream)); pInBuf = (BYTE*)malloc(nInBufSize); if(pInBuf==NULL) { m_nErr = ERR_MEM_ALLOC_FAILED; goto END; } pOutBuf = (BYTE*)malloc(nOutBufSize); if(pOutBuf==NULL) { m_nErr = ERR_MEM_ALLOC_FAILED; goto END; } // 한번에 읽어서 fseek(m_fp, file.dwFileDataPos, SEEK_SET); if(FRead(pInBuf, nInBufSize, 1, m_fp)!=1) { m_nErr = ERR_FILE_READ_ERROR; goto END; } // 초기화.. inflateInit2(&stream, -MAX_WBITS); stream.next_out = pOutBuf; stream.avail_out = nOutBufSize; stream.next_in = pInBuf; stream.avail_in = nInBufSize; err = inflate(&stream, flush); if(err!=Z_OK && err!=Z_STREAM_END ) { m_nErr = ERR_INFLATE_FAILED; goto END; } fwrite(pOutBuf, 1, nOutBufSize, fp); ret = TRUE; END : inflateEnd(&stream); if(pInBuf) free(pInBuf); if(pOutBuf) free(pOutBuf); return ret; } */ //////////////////////////////////////////////////////////////////////////////////////////////////// /// 대상 폴더에 현재 압축파일을 전부 풀기 /// @param szDestPathName - 대상 경로 /// @return /// @date 2004-03-06 오후 11:09:49 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::ExtractAll(const char* szDestPathName) { FileList::iterator i; for(i=m_fileList.begin(); i<m_fileList.end(); i++) { m_posCur = i; if(ExtractCurrentFile(szDestPathName)==FALSE) return FALSE; if(m_bHalt) break; // 멈추기.. } return TRUE; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 대상 경로 파기 - 압축 파일 내에 폴더 정보가 있을 경우, 다중 폴더를 판다(dig) /// @param szPathName /// @return /// @date 2004-03-06 오후 11:10:12 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::DigPath(const char* szPathName) { char* dup = strdup(szPathName); char seps[] = "/\\"; char* token; char path[MAX_PATH] = {0}; char* last; // 경로만 뽑기. last = dup + strlen(dup); while(last!=dup) { if(*last=='/' || *last=='\\') { *last = (char)NULL; break; } last --; } token = strtok( dup, seps ); while( token != NULL ) { if(strlen(path)==0) { if(szPathName[0]=='/') // is absolute path ? safe_strcpy(path,"/", MAX_PATH); else if(szPathName[0]=='\\' && szPathName[1]=='\\') // network drive ? safe_strcpy(path,"\\\\", MAX_PATH); safe_strcat(path, token, MAX_PATH); } else { safe_strcat(path, PATHSEP,MAX_PATH); safe_strcat(path, token,MAX_PATH); } if(IsFolder(path)==FALSE) #ifdef _WIN32 _mkdir(path); #else mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); #endif //printf("path:%s\n", path); token = strtok( NULL, seps ); } free(dup); if(IsFolder(szPathName)) return TRUE; return FALSE; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 제대로된 폴더 인가? /// @param szPathName /// @return /// @date 2004-03-06 오후 11:03:26 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::IsFolder(const CHAR* szPathName) { #ifdef _WIN32 UINT32 dwRet; dwRet = GetFileAttributesA(szPathName); if(dwRet==0xffffffff) return FALSE; if(dwRet & FILE_ATTRIBUTE_DIRECTORY) return TRUE; return FALSE; #else struct stat buf; int result; result = stat(szPathName, &buf); if(result!=0) return FALSE; //printf("isfolder:%s, %d,%d,%d\n", szPathName, buf.st_mode, S_IFDIR, buf.st_mode & S_IFDIR); if(buf.st_mode & S_IFDIR) return TRUE; return FALSE; #endif } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 압축을 풀 대상에 압축을 푼다. /// @param dest - 대상 OBJECT /// @param buf - 풀린 데이타 /// @param nSize - 데이타의 크기 /// @return 쓴 바이트수. 에러시 -1 리턴 /// @date 2004-03-07 오전 12:37:41 //////////////////////////////////////////////////////////////////////////////////////////////////// int CUnAlz::WriteToDest(SExtractDest* dest, BYTE* buf, int nSize) { if(dest->nType==ET_FILE) { return fwrite(buf, 1, nSize, dest->fp); } else if(dest->nType==ET_MEM) { if(dest->buf==NULL) return nSize; // 대상이 NULL 이다... 압축푸는 시늉만 한다.. if(dest->bufpos+nSize >dest->bufsize) // 에러.. 버퍼가 넘쳤다. { ASSERT(0); return -1; } // memcpy memcpy(dest->buf + dest->bufpos, buf, nSize); dest->bufpos += nSize; return nSize; } else { ASSERT(0); } return -1; } /* 실패한 방법.. 고생한게 아까워서 못지움. #define ALZDLZ_HEADER_SIZE 4 // alz 파일의 bzip2 헤더 크기 #define BZIP2_HEADER_SIZE 10 // bzip 파일의 헤더 크기 #define BZIP2_CRC_SIZE 4 // bzip2 의 crc #define BZIP2_TAIL_SIZE 10 // 대충 4+5 정도.? BYTE bzip2Header[BZIP2_HEADER_SIZE] = {0x42, 0x5a, 0x68, 0x39, 0x31, 0x41, 0x59, 0x26, 0x53, 0x59}; BOOL CUnAlz::ExtractBzip2_bak(FILE* fp, SAlzLocalFileHeader& file) { bz_stream stream; BYTE* pInBuf=NULL; BYTE* pOutBuf=NULL; int nInBufSize = file.compressedSize; int nOutBufSize = file.uncompressedSize; //int err; int flush=Z_SYNC_FLUSH; BOOL ret = FALSE; UINT32 crc = 0xffffffff; //BYTE temp[100]; memset(&stream, 0, sizeof(stream)); pInBuf = (BYTE*)malloc(nInBufSize + BZIP2_HEADER_SIZE + BZIP2_CRC_SIZE - ALZDLZ_HEADER_SIZE + BZIP2_TAIL_SIZE); if(pInBuf==NULL) { m_nErr = ERR_MEM_ALLOC_FAILED; goto END; } pOutBuf = (BYTE*)malloc(nOutBufSize); if(pOutBuf==NULL) { m_nErr = ERR_MEM_ALLOC_FAILED; goto END; } // ALZ 의 BZIP 헤더 ("DLZ.") 스킵하기. fseek(m_fp, ALZDLZ_HEADER_SIZE, SEEK_CUR); // BZIP2 헤더 삽입 memcpy(pInBuf, bzip2Header, BZIP2_HEADER_SIZE); // BZIP2 CRC memcpy(pInBuf+BZIP2_HEADER_SIZE, &(crc), BZIP2_CRC_SIZE); // 진짜 압축된 데이타를 한번에 읽어서 fseek(m_fp, file.dwFileDataPos+ALZDLZ_HEADER_SIZE, SEEK_SET); if(FRead(pInBuf+BZIP2_HEADER_SIZE+BZIP2_CRC_SIZE, nInBufSize-ALZDLZ_HEADER_SIZE, 1, m_fp)!=1) { m_nErr = ERR_FILE_READ_ERROR; goto END; } // 초기화.. stream.bzalloc = NULL; stream.bzfree = NULL; stream.opaque = NULL; ret = BZ2_bzDecompressInit ( &stream, 3,0 ); if (ret != BZ_OK) goto END; //memcpy(temp, pInBuf, 100); stream.next_in = (char*)pInBuf; stream.next_out = (char*)pOutBuf; stream.avail_in = nInBufSize+BZIP2_HEADER_SIZE+BZIP2_CRC_SIZE+BZIP2_TAIL_SIZE; stream.avail_out = nOutBufSize; ret = BZ2_bzDecompress ( &stream ); // BZ_DATA_ERROR 가 리턴될 수 있다.. //if (ret == BZ_OK) goto END; //if (ret != BZ_STREAM_END) goto END; BZ2_bzDecompressEnd(&stream); fwrite(pOutBuf, 1, nOutBufSize, fp); ret = TRUE; END : if(pInBuf) free(pInBuf); if(pOutBuf) free(pOutBuf); if(ret==FALSE) BZ2_bzDecompressEnd(&stream); return ret; } */ //////////////////////////////////////////////////////////////////////////////////////////////////// /// RAW 로 압축된 파일 풀기 /// @param fp - 대상 파일 /// @param file - 소스 파일 /// @return /// @date 2004-03-06 오후 11:10:53 //////////////////////////////////////////////////////////////////////////////////////////////////// #define BUF_LEN (4096*2) BOOL CUnAlz::ExtractRawfile(SExtractDest* dest, SAlzLocalFileHeader& file) { BOOL ret = FALSE; BYTE buf[BUF_LEN]; INT64 read; INT64 sizeToRead; INT64 bufLen = BUF_LEN; INT64 nWritten = 0; BOOL bHalt = FALSE; BOOL bIsEncrypted = IsEncryptedFile(); // 암호걸린 파일인가? UINT32 dwCRC32= 0; // 위치 잡고. FSeek(file.dwFileDataPos); sizeToRead = file.compressedSize; // 읽을 크기. m_nErr = ERR_NOERR; while(sizeToRead) { read = min(sizeToRead, bufLen); if(FRead(buf, (int)read)==FALSE) { break; } if(bIsEncrypted) DecryptingData((int)read, buf); // xf86 dwCRC32 = crc32(dwCRC32, buf, (UINT)(read)); WriteToDest(dest, buf, (int)read); //fwrite(buf, read, 1, fp); sizeToRead -= read; nWritten+=read; // progress callback if(m_pFuncCallBack) { m_pFuncCallBack(NULL, nWritten, file.uncompressedSize, m_pCallbackParam, &bHalt); if(bHalt) { break; } } } m_bHalt = bHalt; if(m_nErr==ERR_NOERR) // 성공적으로 압축을 풀었다.. CRC 검사하기.. { if(file.fileCRC==dwCRC32) { ret = TRUE; } else { m_nErr = ERR_INVALID_FILE_CRC; } } return ret; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// BZIP2 압축 풀기.. /// @param fp_w - 대상 파일 /// @param file - 소스 파일 정보 /// @return /// @date 2004-03-01 오전 5:47:36 //////////////////////////////////////////////////////////////////////////////////////////////////// #define BZIP2_EXTRACT_BUF_SIZE 0x2000 BOOL CUnAlz::ExtractBzip2(SExtractDest* dest, SAlzLocalFileHeader& file) { BZFILE *bzfp = NULL; int smallMode = 0; int verbosity = 1; int bzerr; INT64 len; BYTE buff[BZIP2_EXTRACT_BUF_SIZE]; INT64 nWritten = 0; BOOL bHalt = FALSE; UINT32 dwCRC32= 0; BOOL ret = FALSE; FSeek(file.dwFileDataPos); bzfp = BZ2_bzReadOpen(&bzerr,this,verbosity,smallMode,0,0); if(bzfp==NULL){ASSERT(0); return FALSE;} m_nErr = ERR_NOERR; while((len=BZ2_bzread(bzfp,buff,BZIP2_EXTRACT_BUF_SIZE))>0) { WriteToDest(dest, (BYTE*)buff, (int)len); //fwrite(buff,1,len,fp_w); dwCRC32 = crc32(dwCRC32,buff, (UINT)(len)); nWritten+=len; // progress callback if(m_pFuncCallBack) { m_pFuncCallBack(NULL, nWritten, file.uncompressedSize, m_pCallbackParam, &bHalt); if(bHalt) { break; } } } if(len<0) // 에러 상황.. { m_nErr = ERR_INFLATE_FAILED; } BZ2_bzReadClose( &bzerr, bzfp); m_bHalt = bHalt; if(m_nErr==ERR_NOERR) // 성공적으로 압축을 풀었다.. CRC 검사하기.. { if(file.fileCRC==dwCRC32) { ret = TRUE; } else { m_nErr = ERR_INVALID_FILE_CRC; } } /* // FILE* 를 사용할경우 사용하던 코드. - 멀티 볼륨 지원 안함.. BZFILE *bzfp = NULL; int smallMode = 0; int verbosity = 1; int bzerr; int len; char buff[BZIP2_EXTRACT_BUF_SIZE]; INT64 nWritten = 0; BOOL bHalt = FALSE; FSeek(file.dwFileDataPos, SEEK_SET); bzfp = BZ2_bzReadOpen(&bzerr,m_fp,verbosity,smallMode,0,0); while((len=BZ2_bzread(bzfp,buff,BZIP2_EXTRACT_BUF_SIZE))>0) { WriteToDest(dest, (BYTE*)buff, len); //fwrite(buff,1,len,fp_w); nWritten+=len; // progress callback if(m_pFuncCallBack) { m_pFuncCallBack(NULL, nWritten, file.uncompressedSize, m_pCallbackParam, &bHalt); if(bHalt) { break; } } } BZ2_bzReadClose( &bzerr, bzfp); m_bHalt = bHalt; */ return ret; } #ifndef UNZ_BUFSIZE #define UNZ_BUFSIZE 0x1000 // (16384) #endif #define IN_BUF_SIZE UNZ_BUFSIZE #define OUT_BUF_SIZE 0x1000 //IN_BUF_SIZE //////////////////////////////////////////////////////////////////////////////////////////////////// /// deflate 로 압축 풀기. ExtractDeflate() 와 달리 조금씩 읽어서 푼다. /// @param fp /// @param file /// @return /// @date 2004-03-06 오후 11:11:36 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::ExtractDeflate2(SExtractDest* dest, SAlzLocalFileHeader& file) { z_stream stream; BYTE pInBuf[IN_BUF_SIZE]; BYTE pOutBuf[OUT_BUF_SIZE]; int nInBufSize = IN_BUF_SIZE; int nOutBufSize = OUT_BUF_SIZE; int err; int flush=Z_SYNC_FLUSH; BOOL ret = FALSE; INT64 nRestReadCompressed; UINT32 dwCRC32= 0; INT64 rest_read_uncompressed; UINT iRead = 0; INT64 nWritten = 0; BOOL bHalt = FALSE; BOOL bIsEncrypted = IsEncryptedFile(); // 암호걸린 파일인가? memset(&stream, 0, sizeof(stream)); FSeek(file.dwFileDataPos); inflateInit2(&stream, -MAX_WBITS); nRestReadCompressed = file.compressedSize; rest_read_uncompressed = file.uncompressedSize; // 출력 부분. stream.next_out = pOutBuf; stream.avail_out = OUT_BUF_SIZE; m_nErr = ERR_NOERR; while(stream.avail_out>0) { if(stream.avail_in==0 && nRestReadCompressed>0) { UINT uReadThis = UNZ_BUFSIZE; if (nRestReadCompressed<(int)uReadThis) uReadThis = (UINT)nRestReadCompressed; // 읽을 크기. if (uReadThis == 0) break; // 중지 if(FRead(pInBuf, uReadThis)==FALSE) { m_nErr = ERR_CANT_READ_FILE; goto END; } if(bIsEncrypted) DecryptingData(uReadThis, pInBuf); // xf86 // dwCRC32 = crc32(dwCRC32,pInBuf, (UINT)(uReadThis)); nRestReadCompressed -= uReadThis; stream.next_in = pInBuf; stream.avail_in = uReadThis; } UINT uTotalOutBefore,uTotalOutAfter; const BYTE *bufBefore; UINT uOutThis; int flush=Z_SYNC_FLUSH; uTotalOutBefore = stream.total_out; bufBefore = stream.next_out; err=inflate(&stream,flush); uTotalOutAfter = stream.total_out; uOutThis = uTotalOutAfter-uTotalOutBefore; dwCRC32 = crc32(dwCRC32,bufBefore, (UINT)(uOutThis)); rest_read_uncompressed -= uOutThis; iRead += (UINT)(uTotalOutAfter - uTotalOutBefore); WriteToDest(dest, pOutBuf, uOutThis); //fwrite(pOutBuf, uOutThis, 1, fp); // file 에 쓰기. stream.next_out = pOutBuf; stream.avail_out = OUT_BUF_SIZE; nWritten+=uOutThis; // progress callback if(m_pFuncCallBack) { m_pFuncCallBack(NULL, nWritten, file.uncompressedSize, m_pCallbackParam, &bHalt); if(bHalt) { m_nErr = ERR_USER_ABORTED; break; } } if (err==Z_STREAM_END) break; //if(iRead==0) break; // UNZ_EOF; if (err!=Z_OK) { m_nErr = ERR_INFLATE_FAILED; goto END; } } m_bHalt = bHalt; if(m_nErr==ERR_NOERR) // 성공적으로 압축을 풀었다.. CRC 검사하기.. { if(file.fileCRC==dwCRC32) { ret = TRUE; } else { m_nErr = ERR_INVALID_FILE_CRC; } } END : inflateEnd(&stream); return ret; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 파일 열기 /// @param szPathName /// @return /// @date 2004-10-02 오후 11:47:14 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::FOpen(const char* szPathName) { char* temp = strdup(szPathName); // 파일명 복사.. int i; int nLen = strlen(szPathName); UINT64 nFileSizeLow; UINT32 dwFileSizeHigh; m_nFileCount = 0; m_nCurFile = 0; m_nVirtualFilePos = 0; m_nCurFilePos = 0; m_bIsEOF = FALSE; for(i=0;i<MAX_FILES;i++) // aa.alz 파일명을 가지고 aa.a00 aa.a01 aa.a02 .. 만들기 { if(i>0) safe_sprintf(temp+nLen-3, 4, "%c%02d", (i-1)/100+'a', (i-1)%100); #ifdef _WIN32 m_files[i].fp = CreateFileA(temp, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL); if(m_files[i].fp==INVALID_HANDLE_VALUE) break; nFileSizeLow = GetFileSize(m_files[i].fp, (DWORD*)&dwFileSizeHigh); #else m_files[i].fp = fopen(temp, "rb"); if(m_files[i].fp==NULL) break; dwFileSizeHigh=0; unalz_fseek(m_files[i].fp,0,SEEK_END); nFileSizeLow=unalz_ftell(m_files[i].fp); unalz_fseek(m_files[i].fp,0,SEEK_SET); #endif m_nFileCount++; m_files[i].nFileSize = ((INT64)nFileSizeLow) + (((INT64)dwFileSizeHigh)<<32); if(i==0) m_files[i].nMultivolHeaderSize = 0; else m_files[i].nMultivolHeaderSize = MULTIVOL_HEAD_SIZE; m_files[i].nMultivolTailSize = MULTIVOL_TAIL_SIZE; } free(temp); if(m_nFileCount==0) return FALSE; m_files[m_nFileCount-1].nMultivolTailSize = 0; // 마지막 파일은 꼴랑지가 없다.. return TRUE; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 파일 닫기 /// @return /// @date 2004-10-02 오후 11:48:53 //////////////////////////////////////////////////////////////////////////////////////////////////// void CUnAlz::FClose() { int i; #ifdef _WIN32 for(i=0;i<m_nFileCount;i++) CloseHandle(m_files[i].fp); #else for(i=0;i<m_nFileCount;i++) fclose(m_files[i].fp); #endif memset(m_files, 0, sizeof(m_files)); m_nFileCount = 0; m_nCurFile = -1; m_nVirtualFilePos = 0; m_nCurFilePos = 0; m_bIsEOF = FALSE; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 파일의 끝인가? /// @return /// @date 2004-10-02 오후 11:48:21 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::FEof() { return m_bIsEOF; /* if(m_fp==NULL){ASSERT(0); return TRUE;} if(feof(m_fp)) return TRUE; return FALSE; */ } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 현재 파일 위치 /// @return /// @date 2004-10-02 오후 11:50:50 //////////////////////////////////////////////////////////////////////////////////////////////////// INT64 CUnAlz::FTell() { return m_nVirtualFilePos; // return ftell(m_fp); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 파일 위치 세팅 /// @param offset /// @param origin /// @return /// @date 2004-10-02 오후 11:51:53 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::FSeek(INT64 offset) { m_nVirtualFilePos = offset; int i; INT64 remain=offset; LONG remainHigh; m_bIsEOF = FALSE; for(i=0;i<m_nFileCount;i++) // 앞에서 루프를 돌면서 위치 선정하기.. { if(remain<=m_files[i].nFileSize-m_files[i].nMultivolHeaderSize-m_files[i].nMultivolTailSize) { m_nCurFile = i; m_nCurFilePos = remain+m_files[i].nMultivolHeaderSize; // 물리적 위치. remainHigh = (LONG)((m_nCurFilePos>>32)&0xffffffff); #ifdef _WIN32 SetFilePointer(m_files[i].fp, LONG(m_nCurFilePos), &remainHigh, FILE_BEGIN); #else unalz_fseek(m_files[i].fp, m_nCurFilePos, SEEK_SET); #endif return TRUE; } remain -= (m_files[i].nFileSize-m_files[i].nMultivolHeaderSize-m_files[i].nMultivolTailSize); } // 실패..? ASSERT(0); return FALSE; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 파일 읽기 /// @param buffer /// @param size /// @param count /// @return /// @date 2004-10-02 오후 11:44:05 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::FRead(void* buffer, UINT32 nBytesToRead, int* pTotRead ) { BOOL ret; UINT32 nNumOfBytesRead; INT64 dwRemain; UINT32 dwRead; UINT32 dwTotRead; dwRemain = nBytesToRead; dwTotRead = 0; if(pTotRead) *pTotRead=0; while(dwRemain) { dwRead = (UINT32)min(dwRemain, (m_files[m_nCurFile].nFileSize-m_nCurFilePos-m_files[m_nCurFile].nMultivolTailSize)); if(dwRead==0) { m_bIsEOF = TRUE;return FALSE; } #ifdef _WIN32 ret = ReadFile(m_files[m_nCurFile].fp, ((BYTE*)buffer)+dwTotRead, dwRead, (DWORD*)&nNumOfBytesRead, NULL); if(ret==FALSE && GetLastError()==ERROR_HANDLE_EOF) { m_bIsEOF = TRUE;return FALSE; } #else nNumOfBytesRead = fread(((BYTE*)buffer)+dwTotRead, 1,dwRead ,m_files[m_nCurFile].fp); if(nNumOfBytesRead<=0) { m_bIsEOF = TRUE;return FALSE; } ret=TRUE; #endif if(dwRead!=nNumOfBytesRead) // 발생하면 안된다.. { ASSERT(0); return FALSE; } m_nVirtualFilePos += nNumOfBytesRead; // virtual 파일 위치.. m_nCurFilePos+=nNumOfBytesRead; // 물리적 파일 위치. dwRemain-=nNumOfBytesRead; dwTotRead+=nNumOfBytesRead; if(pTotRead) *pTotRead=dwTotRead; if(m_nCurFilePos==m_files[m_nCurFile].nFileSize-m_files[m_nCurFile].nMultivolTailSize) // overflow { m_nCurFile++; #ifdef _WIN32 if(m_files[m_nCurFile].fp==INVALID_HANDLE_VALUE) #else if(m_files[m_nCurFile].fp==NULL) #endif { m_bIsEOF = TRUE; if(dwRemain==0) return TRUE; // 완전히 끝까지 읽었다.. return FALSE; } m_nCurFilePos = m_files[m_nCurFile].nMultivolHeaderSize; // header skip #ifdef _WIN32 SetFilePointer(m_files[m_nCurFile].fp, (int)m_nCurFilePos, NULL, FILE_BEGIN); #else unalz_fseek(m_files[m_nCurFile].fp, m_nCurFilePos, SEEK_SET); #endif } else if(m_nCurFilePos>m_files[m_nCurFile].nFileSize-m_files[m_nCurFile].nMultivolTailSize) ASSERT(0); } return ret; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// error code 를 스트링으로 바꿔 준다. /// @param nERR /// @return /// @date 2004-10-24 오후 3:28:39 //////////////////////////////////////////////////////////////////////////////////////////////////// const char* CUnAlz::LastErrToStr(ERR nERR) { if(nERR>= sizeof(errorstrtable)/sizeof(errorstrtable[0])) {ASSERT(0); return NULL; } return errorstrtable[nERR]; } // by xf86 BOOL CUnAlz::chkValidPassword() { if(IsEncryptedFile()==FALSE) {return TRUE;} if (getPasswordLen() == 0){ m_nErr = ERR_PASSWD_NOT_SET; return FALSE; } InitCryptKeys(m_szPasswd); if(CryptCheck(m_posCur->encChk) == FALSE){ m_nErr = ERR_INVALID_PASSWD; return FALSE; } return TRUE; } /* //////////////////////////////////////////////////////////////////////////////////////////////////// // from CZipArchive // Copyright (C) 2000 - 2004 Tadeusz Dracz // // http://www.artpol-software.com // // it's under GPL. //////////////////////////////////////////////////////////////////////////////////////////////////// void CUnAlz::CryptDecodeBuffer(UINT32 uCount, CHAR *buf) { if (IsEncrypted()) for (UINT32 i = 0; i < uCount; i++) CryptDecode(buf[i]); } void CUnAlz::CryptInitKeys() { m_keys[0] = 305419896L; m_keys[1] = 591751049L; m_keys[2] = 878082192L; for (int i = 0; i < strlen(m_szPasswd); i++) CryptUpdateKeys(m_szPasswd[i]); } void CUnAlz::CryptUpdateKeys(CHAR c) { m_keys[0] = CryptCRC32(m_keys[0], c); m_keys[1] += m_keys[0] & 0xff; m_keys[1] = m_keys[1] * 134775813L + 1; c = CHAR(m_keys[1] >> 24); m_keys[2] = CryptCRC32(m_keys[2], c); } BOOL CUnAlz::CryptCheck(CHAR *buf) { CHAR b = 0; for (int i = 0; i < ALZ_ENCR_HEADER_LEN; i++) { b = buf[i]; CryptDecode((CHAR&)b); } if (IsDataDescr()) // Data descriptor present return CHAR(m_posCur->head.fileTimeDate >> 8) == b; else return CHAR(m_posCur->maybeCRC >> 24) == b; } CHAR CUnAlz::CryptDecryptCHAR() { int temp = (m_keys[2] & 0xffff) | 2; return (CHAR)(((temp * (temp ^ 1)) >> 8) & 0xff); } void CUnAlz::CryptDecode(CHAR &c) { c ^= CryptDecryptCHAR(); CryptUpdateKeys(c); } UINT32 CUnAlz::CryptCRC32(UINT32 l, CHAR c) { const ULONG *CRC_TABLE = get_crc_table(); return CRC_TABLE[(l ^ c) & 0xff] ^ (l >> 8); } */ //////////////////////////////////////////////////////////////////////////////////////////////////// /// 암호걸린 파일인지 여부 /// @param fileDescriptor /// @return /// @date 2004-11-27 오후 11:25:32 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::IsEncryptedFile(BYTE fileDescriptor) { return fileDescriptor&0x01; } BOOL CUnAlz::IsEncryptedFile() { return m_posCur->head.fileDescriptor&0x01; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 암호로 키 초기화 /// @param szPassword /// @return /// @date 2004-11-27 오후 11:04:01 //////////////////////////////////////////////////////////////////////////////////////////////////// void CUnAlz::InitCryptKeys(const CHAR* szPassword) { m_key[0] = 305419896; m_key[1] = 591751049; m_key[2] = 878082192; int i; for(i=0;i<(int)strlen(szPassword);i++) { UpdateKeys(szPassword[i]); } } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 데이타로 키 업데이트하기 /// @param c /// @return /// @date 2004-11-27 오후 11:04:09 //////////////////////////////////////////////////////////////////////////////////////////////////// void CUnAlz::UpdateKeys(BYTE c) { m_key[0] = CRC32(m_key[0], c); m_key[1] = m_key[1]+(m_key[0]&0x000000ff); m_key[1] = m_key[1]*134775813+1; m_key[2] = CRC32(m_key[2],m_key[1]>>24); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 암호가 맞는지 헤더 체크하기 /// @param buf /// @return /// @date 2004-11-27 오후 11:04:24 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::CryptCheck(const BYTE* buf) { int i; BYTE c; BYTE temp[ALZ_ENCR_HEADER_LEN]; memcpy(temp, buf, ALZ_ENCR_HEADER_LEN); // 임시 복사. for(i=0;i<ALZ_ENCR_HEADER_LEN;i++) { c = temp[i] ^ DecryptByte(); UpdateKeys(c); temp[i] = c; } if (IsDataDescr()) // Data descriptor present return (m_posCur->head.fileTimeDate >> 8) == c; else return ( ((m_posCur->fileCRC)>>24) ) == c; // 파일 crc 의 최상위 byte } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 키에서 데이타 추출 /// @return /// @date 2004-11-27 오후 11:05:36 //////////////////////////////////////////////////////////////////////////////////////////////////// BYTE CUnAlz::DecryptByte() { UINT16 temp; temp = m_key[2] | 2; return (temp * (temp^1))>>8; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 데이타 압축 풀기 /// @param nSize /// @param data /// @return /// @date 2004-11-27 오후 11:03:30 //////////////////////////////////////////////////////////////////////////////////////////////////// void CUnAlz::DecryptingData(int nSize, BYTE* data) { BYTE* p = data; BYTE temp; while(nSize) { temp = *p ^ DecryptByte(); UpdateKeys(temp); *p = temp; nSize--; p++; } } //////////////////////////////////////////////////////////////////////////////////////////////////// /// CRC 테이블 참조 /// @param l /// @param c /// @return /// @date 2004-11-27 오후 11:14:16 //////////////////////////////////////////////////////////////////////////////////////////////////// UINT32 CUnAlz::CRC32(UINT32 l, BYTE c) { const z_crc_t *CRC_TABLE = get_crc_table(); return CRC_TABLE[(l ^ c) & 0xff] ^ (l >> 8); } void CUnAlz::SetPassword(char *passwd) { if(strlen(passwd) == 0) return; safe_strcpy(m_szPasswd, passwd, UNALZ_LEN_PASSWORD); } #ifdef _UNALZ_ICONV void CUnAlz::SetDestCodepage(const char* szToCodepage) { safe_strcpy(m_szToCodepage, szToCodepage, UNALZ_LEN_CODEPAGE); } #endif //////////////////////////////////////////////////////////////////////////////////////////////////// /// 문자열 처리 함수들 /// @param l /// @param c /// @return /// @date 2007-02 //////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int CUnAlz::_strlcpy (char *dest, const char *src, unsigned int size) { register unsigned int i = 0; if (size > 0) { size--; for (i=0; size > 0 && src[i] != '\0'; ++i, size--) dest[i] = src[i]; dest[i] = '\0'; } while (src[i++]); return i; } unsigned int CUnAlz::_strlcat (char *dest, const char *src, unsigned int size) { register char *d = dest; for (; size > 0 && *d != '\0'; size--, d++); return (d - dest) + _strlcpy(d, src, size); } // 안전한 strcpy void CUnAlz::safe_strcpy(char* dst, const char* src, size_t dst_size) { #ifdef _WIN32 lstrcpynA(dst, src, dst_size); #else _strlcpy(dst, src, dst_size); #endif } void CUnAlz::safe_strcat(char* dst, const char* src, size_t dst_size) { #ifdef _WIN32 StringCchCatExA(dst, dst_size, src, NULL, NULL, STRSAFE_FILL_BEHIND_NULL); //lstrcatA(dst, src); // not safe!! #else _strlcat(dst, src, dst_size); #endif }
25.288316
328
0.566417
kippler
cc845d41a4cda951e0c2a35a8a448fb72c79ac7d
2,767
cpp
C++
popcnt-harley-seal.cpp
kimwalisch/sse-popcount
8f7441afb60847088aac9566d711969c48a03387
[ "BSD-2-Clause" ]
275
2015-04-06T19:49:18.000Z
2022-03-19T06:23:47.000Z
popcnt-harley-seal.cpp
kimwalisch/sse-popcount
8f7441afb60847088aac9566d711969c48a03387
[ "BSD-2-Clause" ]
20
2015-09-02T04:41:15.000Z
2021-02-24T17:48:51.000Z
popcnt-harley-seal.cpp
kimwalisch/sse-popcount
8f7441afb60847088aac9566d711969c48a03387
[ "BSD-2-Clause" ]
57
2015-06-01T01:08:02.000Z
2022-01-02T12:49:43.000Z
namespace { /// This uses fewer arithmetic operations than any other known /// implementation on machines with fast multiplication. /// It uses 12 arithmetic operations, one of which is a multiply. /// http://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation /// uint64_t popcount_mul(uint64_t x) { const uint64_t m1 = UINT64_C(0x5555555555555555); const uint64_t m2 = UINT64_C(0x3333333333333333); const uint64_t m4 = UINT64_C(0x0F0F0F0F0F0F0F0F); const uint64_t h01 = UINT64_C(0x0101010101010101); x -= (x >> 1) & m1; x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; return (x * h01) >> 56; } /// Carry-save adder (CSA). /// @see Chapter 5 in "Hacker's Delight". /// void CSA(uint64_t& h, uint64_t& l, uint64_t a, uint64_t b, uint64_t c) { uint64_t u = a ^ b; h = (a & b) | (u & c); l = u ^ c; } /// Harley-Seal popcount (4th iteration). /// The Harley-Seal popcount algorithm is one of the fastest algorithms /// for counting 1 bits in an array using only integer operations. /// This implementation uses only 5.69 instructions per 64-bit word. /// @see Chapter 5 in "Hacker's Delight" 2nd edition. /// uint64_t popcnt_harley_seal_64bit(const uint64_t* data, const uint64_t size) { uint64_t total = 0; uint64_t ones = 0, twos = 0, fours = 0, eights = 0, sixteens = 0; uint64_t twosA, twosB, foursA, foursB, eightsA, eightsB; uint64_t limit = size - size % 16; uint64_t i = 0; for(; i < limit; i += 16) { CSA(twosA, ones, ones, data[i+0], data[i+1]); CSA(twosB, ones, ones, data[i+2], data[i+3]); CSA(foursA, twos, twos, twosA, twosB); CSA(twosA, ones, ones, data[i+4], data[i+5]); CSA(twosB, ones, ones, data[i+6], data[i+7]); CSA(foursB, twos, twos, twosA, twosB); CSA(eightsA,fours, fours, foursA, foursB); CSA(twosA, ones, ones, data[i+8], data[i+9]); CSA(twosB, ones, ones, data[i+10], data[i+11]); CSA(foursA, twos, twos, twosA, twosB); CSA(twosA, ones, ones, data[i+12], data[i+13]); CSA(twosB, ones, ones, data[i+14], data[i+15]); CSA(foursB, twos, twos, twosA, twosB); CSA(eightsB, fours, fours, foursA, foursB); CSA(sixteens, eights, eights, eightsA, eightsB); total += popcount_mul(sixteens); } total *= 16; total += 8 * popcount_mul(eights); total += 4 * popcount_mul(fours); total += 2 * popcount_mul(twos); total += 1 * popcount_mul(ones); for(; i < size; i++) total += popcount_mul(data[i]); return total; } } // namespace uint64_t popcnt_harley_seal(const uint8_t* data, const size_t size) { uint64_t total = popcnt_harley_seal_64bit((const uint64_t*) data, size / 8); for (size_t i = size - size % 8; i < size; i++) total += lookup8bit[data[i]]; return total; }
31.089888
78
0.64185
kimwalisch
cc8f25f095ffc1960712df69e506be135c3cfb4c
10,244
cpp
C++
Libs/Visualization/VTK/Widgets/ctkVTKSurfaceMaterialPropertyWidget.cpp
ebrahimebrahim/CTK
c506a0227777b55fc06dd22d74a11c5a9d4247b1
[ "Apache-2.0" ]
null
null
null
Libs/Visualization/VTK/Widgets/ctkVTKSurfaceMaterialPropertyWidget.cpp
ebrahimebrahim/CTK
c506a0227777b55fc06dd22d74a11c5a9d4247b1
[ "Apache-2.0" ]
null
null
null
Libs/Visualization/VTK/Widgets/ctkVTKSurfaceMaterialPropertyWidget.cpp
ebrahimebrahim/CTK
c506a0227777b55fc06dd22d74a11c5a9d4247b1
[ "Apache-2.0" ]
null
null
null
/*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // Qt includes #include <QDebug> // CTK includes #include "ctkVTKSurfaceMaterialPropertyWidget.h" // VTK includes #include <vtkSmartPointer.h> #include <vtkProperty.h> //----------------------------------------------------------------------------- class ctkVTKSurfaceMaterialPropertyWidgetPrivate { Q_DECLARE_PUBLIC(ctkVTKSurfaceMaterialPropertyWidget); protected: ctkVTKSurfaceMaterialPropertyWidget* const q_ptr; public: ctkVTKSurfaceMaterialPropertyWidgetPrivate(ctkVTKSurfaceMaterialPropertyWidget& object); vtkSmartPointer<vtkProperty> Property; double SettingColor; // Flag that indicates that the GUI is being updated from the VTK property, // therefore GUI changes should not trigger VTK property update. bool IsUpdatingGUI; }; //----------------------------------------------------------------------------- ctkVTKSurfaceMaterialPropertyWidgetPrivate::ctkVTKSurfaceMaterialPropertyWidgetPrivate(ctkVTKSurfaceMaterialPropertyWidget& object) :q_ptr(&object) { this->SettingColor = false; this->IsUpdatingGUI = false; } //----------------------------------------------------------------------------- ctkVTKSurfaceMaterialPropertyWidget::~ctkVTKSurfaceMaterialPropertyWidget() { } //----------------------------------------------------------------------------- ctkVTKSurfaceMaterialPropertyWidget::ctkVTKSurfaceMaterialPropertyWidget(QWidget* parentWidget) : Superclass(parentWidget) , d_ptr(new ctkVTKSurfaceMaterialPropertyWidgetPrivate(*this)) { this->updateFromProperty(); } //----------------------------------------------------------------------------- ctkVTKSurfaceMaterialPropertyWidget::ctkVTKSurfaceMaterialPropertyWidget(vtkProperty* property, QWidget* parentWidget) : Superclass(parentWidget) , d_ptr(new ctkVTKSurfaceMaterialPropertyWidgetPrivate(*this)) { this->setProperty(property); } //----------------------------------------------------------------------------- void ctkVTKSurfaceMaterialPropertyWidget::setProperty(vtkProperty* property) { Q_D(ctkVTKSurfaceMaterialPropertyWidget); if (d->Property.GetPointer() == property) { return; } qvtkReconnect(d->Property, property, vtkCommand::ModifiedEvent, this, SLOT(updateFromProperty())); d->Property = property; this->updateFromProperty(); } //----------------------------------------------------------------------------- vtkProperty* ctkVTKSurfaceMaterialPropertyWidget::property()const { Q_D(const ctkVTKSurfaceMaterialPropertyWidget); return d->Property.GetPointer(); } //----------------------------------------------------------------------------- void ctkVTKSurfaceMaterialPropertyWidget::updateFromProperty() { Q_D(ctkVTKSurfaceMaterialPropertyWidget); this->setEnabled(d->Property.GetPointer() != 0); if (d->Property.GetPointer() == 0 || d->SettingColor) { return; } if (d->IsUpdatingGUI) { // Update is already in progress return; } d->IsUpdatingGUI = true; double* c = d->Property->GetColor(); this->setColor(QColor::fromRgbF(qMin(c[0],1.), qMin(c[1], 1.), qMin(c[2],1.))); this->setOpacity(d->Property->GetOpacity()); switch (d->Property->GetInterpolation()) { case VTK_FLAT: this->setInterpolationMode(InterpolationFlat); break; case VTK_GOURAUD: this->setInterpolationMode(InterpolationGouraud); break; case VTK_PHONG: this->setInterpolationMode(InterpolationPhong); break; case VTK_PBR: this->setInterpolationMode(InterpolationPBR); break; } this->setAmbient(d->Property->GetAmbient()); this->setDiffuse(d->Property->GetDiffuse()); this->setSpecular(d->Property->GetSpecular()); this->setSpecularPower(d->Property->GetSpecularPower()); this->setMetallic(d->Property->GetMetallic()); this->setRoughness(d->Property->GetRoughness()); d->IsUpdatingGUI = false; } // -------------------------------------------------------------------------- void ctkVTKSurfaceMaterialPropertyWidget::onColorChanged(const QColor& newColor) { Q_D(ctkVTKSurfaceMaterialPropertyWidget); this->Superclass::onColorChanged(newColor); if (d->Property.GetPointer() != 0) { // the value might have changed since we fired the signal, use the current // up-to-date value then. const QColor c = this->color(); // Need to work around a VTK bug of SetColor() that fires event // in an unstable state: // d->Property->SetColor(c.redF(), c.greenF(), c.blueF()); d->SettingColor = true; d->Property->SetAmbientColor(c.redF(), c.greenF(), c.blueF()); d->Property->SetDiffuseColor(c.redF(), c.greenF(), c.blueF()); d->Property->SetSpecularColor(c.redF(), c.greenF(), c.blueF()); d->SettingColor = false; // update just in case something connected to the modified event of the // vtkProperty modified any attribute this->updateFromProperty(); } } // -------------------------------------------------------------------------- void ctkVTKSurfaceMaterialPropertyWidget::onOpacityChanged(double newOpacity) { Q_D(ctkVTKSurfaceMaterialPropertyWidget); this->Superclass::onOpacityChanged(newOpacity); if (d->Property.GetPointer() != 0) { // the value might have changed since we fired the signal, use the current // up-to-date value then. d->Property->SetOpacity(this->opacity()); } } // -------------------------------------------------------------------------- void ctkVTKSurfaceMaterialPropertyWidget::onInterpolationModeChanged( ctkMaterialPropertyWidget::InterpolationMode newInterpolationMode) { Q_D(ctkVTKSurfaceMaterialPropertyWidget); this->Superclass::onInterpolationModeChanged(newInterpolationMode); if (d->Property.GetPointer() != 0) { // the value might have changed since we fired the signal, use the current // up-to-date value then. switch (this->interpolationMode()) { case InterpolationFlat: d->Property->SetInterpolationToFlat(); break; case InterpolationGouraud: d->Property->SetInterpolationToGouraud(); break; case InterpolationPhong: d->Property->SetInterpolationToPhong(); break; case InterpolationPBR: d->Property->SetInterpolationToPBR(); break; } } } // -------------------------------------------------------------------------- void ctkVTKSurfaceMaterialPropertyWidget::onAmbientChanged(double newAmbient) { Q_D(ctkVTKSurfaceMaterialPropertyWidget); this->Superclass::onAmbientChanged(newAmbient); if (d->Property.GetPointer() != 0) { // the value might have changed since we fired the signal, use the current // up-to-date value then. d->Property->SetAmbient(this->ambient()); } } // -------------------------------------------------------------------------- void ctkVTKSurfaceMaterialPropertyWidget::onDiffuseChanged(double newDiffuse) { Q_D(ctkVTKSurfaceMaterialPropertyWidget); this->Superclass::onDiffuseChanged(newDiffuse); if (d->Property.GetPointer() != 0) { // the value might have changed since we fired the signal, use the current // up-to-date value then. d->Property->SetDiffuse(this->diffuse()); } } // -------------------------------------------------------------------------- void ctkVTKSurfaceMaterialPropertyWidget::onSpecularChanged(double newSpecular) { Q_D(ctkVTKSurfaceMaterialPropertyWidget); this->Superclass::onSpecularChanged(newSpecular); if (d->Property.GetPointer() != 0) { // the value might have changed since we fired the signal, use the current // up-to-date value then. d->Property->SetSpecular(this->specular()); } } // -------------------------------------------------------------------------- void ctkVTKSurfaceMaterialPropertyWidget::onSpecularPowerChanged(double newSpecularPower) { Q_D(ctkVTKSurfaceMaterialPropertyWidget); this->Superclass::onSpecularPowerChanged(newSpecularPower); if (d->Property.GetPointer() != 0) { // the value might have changed since we fired the signal, use the current // up-to-date value then. d->Property->SetSpecularPower(this->specularPower()); } } // -------------------------------------------------------------------------- void ctkVTKSurfaceMaterialPropertyWidget::onMetallicChanged(double newMetallic) { Q_D(ctkVTKSurfaceMaterialPropertyWidget); this->Superclass::onMetallicChanged(newMetallic); if (d->Property.GetPointer() != 0) { // the value might have changed since we fired the signal, use the current // up-to-date value then. d->Property->SetMetallic(this->metallic()); } } // -------------------------------------------------------------------------- void ctkVTKSurfaceMaterialPropertyWidget::onRoughnessChanged(double newRoughness) { Q_D(ctkVTKSurfaceMaterialPropertyWidget); this->Superclass::onRoughnessChanged(newRoughness); if (d->Property.GetPointer() != 0) { // the value might have changed since we fired the signal, use the current // up-to-date value then. d->Property->SetRoughness(this->roughness()); } } // -------------------------------------------------------------------------- void ctkVTKSurfaceMaterialPropertyWidget::onBackfaceCullingChanged(bool newBackfaceCulling) { Q_D(ctkVTKSurfaceMaterialPropertyWidget); this->Superclass::onBackfaceCullingChanged(newBackfaceCulling); if (d->Property.GetPointer() != 0) { // the value might have changed since we fired the signal, use the current // up-to-date value then. d->Property->SetBackfaceCulling(this->backfaceCulling()); } }
36.455516
131
0.625439
ebrahimebrahim
cc92133cf6216aed3081d7ee820e775f80d84589
814
cpp
C++
HackerRank/Algorithms/Easy/E0088.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
54
2019-05-13T12:13:09.000Z
2022-02-27T02:59:00.000Z
HackerRank/Algorithms/Easy/E0088.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
2
2020-10-02T07:16:43.000Z
2020-10-19T04:36:19.000Z
HackerRank/Algorithms/Easy/E0088.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
20
2020-05-26T09:48:13.000Z
2022-03-18T15:18:27.000Z
/* Problem Statement: https://www.hackerrank.com/challenges/acm-icpc-team/problem */ #include <iostream> #include <string> #include <vector> #include <bitset> #define M 500 using namespace std; vector<int> acmTeam(vector<string> topic) { int known; vector<int> ans(2); for (int i = 0; i < topic.size() - 1; i++) { bitset<M> b1(topic[i]); for (int j = i + 1; j < topic.size(); j++) { bitset<M> b2(topic[j]); known = (b1 | b2).count(); if (known > ans[0]) { ans[0] = known; ans[1] = 1; } else if (known == ans[0]) ans[1]++; } } return ans; } int main() { int n, m; cin >> n >> m; vector<int> ans; vector<string> topic(n); for (int i = 0; i < n; i++) cin >> topic[i]; ans = acmTeam(topic); for (int i = 0; i < ans.size(); i++) cout << ans[i] << endl; return 0; }
18.930233
78
0.558968
Mohammed-Shoaib
cc92e631f99cd32b1e9c3eee1a2ee8e50332cb88
1,867
cpp
C++
Controller/FileController.cpp
SAarronB/Vector
225342800beff75e19513bbb6d68a0dcd3eab1e2
[ "MIT" ]
null
null
null
Controller/FileController.cpp
SAarronB/Vector
225342800beff75e19513bbb6d68a0dcd3eab1e2
[ "MIT" ]
null
null
null
Controller/FileController.cpp
SAarronB/Vector
225342800beff75e19513bbb6d68a0dcd3eab1e2
[ "MIT" ]
null
null
null
// // FileController.cpp // Vector // // Created by Bonilla, Sean on 2/5/19. // Copyright © 2019 CTEC. All rights reserved. // #include "FileController.hpp" using namespace std; vector<CrimeData> FileController :: readCrimeDataToVector(string filename){ vector<CrimeData> crimes; string currentCSVLine; int rowCount = 0; ifstream dataFile(filename); //if the file exists at that path. if(dataFile.is_open()){ //Keep Reading Until you are at the end of the file while(!dataFile.eof()){ //Grab each line from the VSV separated by the carriage return character. getline(dataFile, currentCSVLine, '\r'); if(rowCount != 0){ //Create a CrimeData instace forom the line. exclude a black line (usually if opened separeately if(currentCSVLine.length() != 0){ CrimeData row(currentCSVLine); crimes.push_back(row); } } rowCount++; } dataFile.close(); }else{ cerr << "No File" << endl; } return crimes; } vector<Music> FileController :: musicDataToVector(string fileName){ vector<Music> musicList; string currentCSVLine; int rowCount = 0; ifstream dataFile(fileName); //if the file exists at that path if(dataFile.is_open()){ //keepreading until you are tat the end of the file while(!dataFile.eof()){ getline(dataFile, currentCSVLine, '\r'); if(rowCount != 0){ if(currentCSVLine.length() !=0){ Music row(currentCSVLine); musicList.push_back(row); } } rowCount++; } dataFile.close(); }else{ cerr <<"No File"<< endl; } return musicList; }
28.723077
112
0.561864
SAarronB
cc94c1ed84af0a8037617af724c7a2a7fa0f4d9d
728
hpp
C++
source/tm/evaluate/move_scores.hpp
davidstone/technical-machine
fea3306e58cd026846b8f6c71d51ffe7bab05034
[ "BSL-1.0" ]
7
2021-03-05T16:50:19.000Z
2022-02-02T04:30:07.000Z
source/tm/evaluate/move_scores.hpp
davidstone/technical-machine
fea3306e58cd026846b8f6c71d51ffe7bab05034
[ "BSL-1.0" ]
47
2021-02-01T18:54:23.000Z
2022-03-06T19:06:16.000Z
source/tm/evaluate/move_scores.hpp
davidstone/technical-machine
fea3306e58cd026846b8f6c71d51ffe7bab05034
[ "BSL-1.0" ]
1
2021-01-28T13:10:41.000Z
2021-01-28T13:10:41.000Z
// Copyright David Stone 2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <tm/move/max_moves_per_pokemon.hpp> #include <containers/static_vector.hpp> #include <tm/generation.hpp> namespace technicalmachine { struct MoveScores { MoveScores(Generation, StaticVectorMove legal_selections, bool ai); void set(Moves move_name, double score); auto ordered_moves(bool ai) const -> StaticVectorMove; private: struct value_type { Moves move_name; double score; }; containers::static_vector<value_type, bounded::builtin_max_value<MoveSize>> m_scores; }; } // namespace technicalmachine
25.103448
86
0.774725
davidstone
cc99ab560d85ebc58e9b118b30a650a1cbbb73fe
18,447
cc
C++
project4/mariadb/server/storage/tokudb/PerconaFT/src/tests/recovery_fileops_unit.cc
jiunbae/ITE4065
3b9fcf9317e93ca7c829f1438b85f0f5ea2885db
[ "MIT" ]
11
2017-10-28T08:41:08.000Z
2021-06-24T07:24:21.000Z
project4/mariadb/server/storage/tokudb/PerconaFT/src/tests/recovery_fileops_unit.cc
jiunbae/ITE4065
3b9fcf9317e93ca7c829f1438b85f0f5ea2885db
[ "MIT" ]
null
null
null
project4/mariadb/server/storage/tokudb/PerconaFT/src/tests/recovery_fileops_unit.cc
jiunbae/ITE4065
3b9fcf9317e93ca7c829f1438b85f0f5ea2885db
[ "MIT" ]
4
2017-09-07T09:33:26.000Z
2021-02-19T07:45:08.000Z
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" /*====== This file is part of PerconaFT. Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved. PerconaFT is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. PerconaFT 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 PerconaFT. If not, see <http://www.gnu.org/licenses/>. ---------------------------------------- PerconaFT is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. PerconaFT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with PerconaFT. If not, see <http://www.gnu.org/licenses/>. ======= */ #ident "Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved." #include <db.h> #include <stdlib.h> #include <sys/stat.h> #include "ft/logger/logger.h" #include "test.h" #include "toku_pthread.h" static int do_recover; static int do_crash; static char fileop; static int choices['J' - 'A' + 1]; const int num_choices = sizeof(choices)/sizeof(choices[0]); static DB_TXN *txn; const char *oldname = "oldfoo"; const char *newname = "newfoo"; DB_ENV *env; DB *db; static int crash_during_checkpoint; static char *cmd; static void usage(void) { fprintf(stderr, "Usage:\n%s [-v|-q]* [-h] (-c|-r) -O fileop -A# -B# -C# -D# -E# " "-F# -G# [-H# -I# -J#]\n" " fileop = c/r/d (create/rename/delete)\n" " Where # is a single digit number > 0.\n" " A-G are required for fileop=create\n" " A-I are required for fileop=delete, fileop=rename\n", cmd); exit(1); } enum { CLOSE_TXN_COMMIT, CLOSE_TXN_ABORT, CLOSE_TXN_NONE }; enum {CREATE_CREATE, CREATE_CHECKPOINT, CREATE_COMMIT_NEW, CREATE_COMMIT_NEW_CHECKPOINT, CREATE_COMMIT_CHECKPOINT_NEW, CREATE_CHECKPOINT_COMMIT_NEW}; static int fileop_did_commit(void); static void close_txn(int type); static int get_x_choice(char c, int possibilities) { assert(c < 'A' + num_choices); assert(c >= 'A'); int choice = choices[c-'A']; if (choice >= possibilities) usage(); return choice; } //return 0 or 1 static int get_bool_choice(char c) { return get_x_choice(c, 2); } static int get_choice_first_create_unrelated_txn(void) { return get_bool_choice('A'); } static int get_choice_do_checkpoint_after_fileop(void) { return get_bool_choice('B'); } static int get_choice_txn_close_type(void) { return get_x_choice('C', 3); } static int get_choice_close_txn_before_checkpoint(void) { int choice = get_bool_choice('D'); //Can't do checkpoint related thing without checkpoint if (choice) assert(get_choice_do_checkpoint_after_fileop()); return choice; } static int get_choice_crash_checkpoint_in_callback(void) { int choice = get_bool_choice('E'); //Can't do checkpoint related thing without checkpoint if (choice) assert(get_choice_do_checkpoint_after_fileop()); return choice; } static int get_choice_flush_log_before_crash(void) { return get_bool_choice('F'); } static int get_choice_dir_per_db(void) { return get_bool_choice('G'); } static int get_choice_create_type(void) { return get_x_choice('H', 6); } static int get_choice_txn_does_open_close_before_fileop(void) { return get_bool_choice('I'); } static int get_choice_lock_table_split_fcreate(void) { int choice = get_bool_choice('J'); if (choice) assert(fileop_did_commit()); return choice; } static void do_args(int argc, char * const argv[]) { cmd = argv[0]; int i; //Clear for (i = 0; i < num_choices; i++) { choices[i] = -1; } char c; while ((c = getopt(argc, argv, "vqhcrO:A:B:C:D:E:F:G:H:I:J:X:")) != -1) { switch (c) { case 'v': verbose++; break; case 'q': verbose--; if (verbose < 0) verbose = 0; break; case 'h': case '?': usage(); break; case 'c': do_crash = 1; break; case 'r': do_recover = 1; break; case 'O': if (fileop != '\0') usage(); fileop = optarg[0]; switch (fileop) { case 'c': case 'r': case 'd': break; default: usage(); break; } break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': if (fileop == '\0') usage(); int num; num = atoi(optarg); if (num < 0 || num > 9) usage(); choices[c - 'A'] = num; break; case 'X': if (strcmp(optarg, "novalgrind") == 0) { // provide a way for the shell script runner to pass an // arg that suppresses valgrind on this child process break; } // otherwise, fall through to an error default: usage(); break; } } if (argc!=optind) { usage(); exit(1); } for (i = 0; i < num_choices; i++) { if (i >= 'H' - 'A' && fileop == 'c') break; if (choices[i] == -1) usage(); } assert(!do_recover || !do_crash); assert(do_recover || do_crash); } static void UU() crash_it(void) { int r; if (get_choice_flush_log_before_crash()) { r = env->log_flush(env, NULL); //TODO: USe a real DB_LSN* instead of NULL CKERR(r); } fprintf(stderr, "HAPPY CRASH\n"); fflush(stdout); fflush(stderr); toku_hard_crash_on_purpose(); printf("This line should never be printed\n"); fflush(stdout); } static void checkpoint_callback_maybe_crash(void * UU(extra)) { if (crash_during_checkpoint) crash_it(); } static void env_startup(void) { int r; int recover_flag = do_crash ? 0 : DB_RECOVER; if (do_crash) { db_env_set_checkpoint_callback(checkpoint_callback_maybe_crash, NULL); toku_os_recursive_delete(TOKU_TEST_FILENAME); r = toku_os_mkdir(TOKU_TEST_FILENAME, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); } int envflags = DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN | DB_CREATE | DB_PRIVATE | recover_flag; r = db_env_create(&env, 0); CKERR(r); r = env->set_dir_per_db(env, get_choice_dir_per_db()); CKERR(r); env->set_errfile(env, stderr); r = env->open(env, TOKU_TEST_FILENAME, envflags, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); //Disable auto-checkpointing. r = env->checkpointing_set_period(env, 0); CKERR(r); } static void env_shutdown(void) { int r; r = env->close(env, 0); CKERR(r); toku_os_recursive_delete(TOKU_TEST_FILENAME); } static void checkpoint(void) { int r; r = env->txn_checkpoint(env, 0, 0, 0); CKERR(r); } static void maybe_make_oldest_living_txn(void) { if (get_choice_first_create_unrelated_txn()) { // create a txn that never closes, forcing recovery to run from the beginning of the log DB_TXN *oldest_living_txn; int r; r = env->txn_begin(env, NULL, &oldest_living_txn, 0); CKERR(r); checkpoint(); } } static void make_txn(void) { int r; assert(!txn); r = env->txn_begin(env, NULL, &txn, 0); CKERR(r); } static void fcreate(void) { int r; r = db_create(&db, env, 0); CKERR(r); r = db->open(db, txn, oldname, NULL, DB_BTREE, DB_CREATE|DB_EXCL, 0666); CKERR(r); if (fileop!='c' && get_choice_lock_table_split_fcreate()) { r = db->close(db, 0); CKERR(r); close_txn(CLOSE_TXN_COMMIT); make_txn(); r = db_create(&db, env, 0); CKERR(r); r = db->open(db, txn, oldname, NULL, DB_BTREE, 0, 0666); CKERR(r); r = db->pre_acquire_table_lock(db, txn); CKERR(r); } DBT key, val; dbt_init(&key, choices, sizeof(choices)); dbt_init(&val, NULL, 0); r = db->put(db, txn, &key, &val, 0); CKERR(r); dbt_init(&key, "name", sizeof("name")); dbt_init(&val, (void*)oldname, strlen(oldname)+1); r = db->put(db, txn, &key, &val, 0); CKERR(r); dbt_init(&key, "to_delete", sizeof("to_delete")); dbt_init(&val, "delete_me", sizeof("delete_me")); r = db->put(db, txn, &key, &val, 0); CKERR(r); r = db->del(db, txn, &key, DB_DELETE_ANY); CKERR(r); dbt_init(&key, "to_delete2", sizeof("to_delete2")); dbt_init(&val, "delete_me2", sizeof("delete_me2")); r = db->put(db, txn, &key, &val, 0); CKERR(r); r = db->del(db, txn, &key, 0); CKERR(r); r = db->close(db, 0); CKERR(r); } static void fdelete(void) { int r; r = env->dbremove(env, txn, oldname, NULL, 0); CKERR(r); } static void frename(void) { int r; { //Rename in 'key/val' pair. DBT key,val; r = db_create(&db, env, 0); CKERR(r); r = db->open(db, txn, oldname, NULL, DB_BTREE, 0, 0666); CKERR(r); dbt_init(&key, "name", sizeof("name")); dbt_init(&val, (void*)newname, strlen(newname)+1); r = db->put(db, txn, &key, &val, 0); CKERR(r); r = db->close(db, 0); CKERR(r); } r = env->dbrename(env, txn, oldname, NULL, newname, 0); CKERR(r); } static void close_txn(int type) { int r; assert(txn); if (type==CLOSE_TXN_COMMIT) { //commit r = txn->commit(txn, 0); CKERR(r); txn = NULL; } else if (type == CLOSE_TXN_ABORT) { //abort r = txn->abort(txn); CKERR(r); txn = NULL; } else assert(type == CLOSE_TXN_NONE); } static void create_and_crash(void) { //Make txn make_txn(); //fcreate fcreate(); if (get_choice_do_checkpoint_after_fileop()) { crash_during_checkpoint = get_choice_crash_checkpoint_in_callback(); if (get_choice_close_txn_before_checkpoint()) close_txn(get_choice_txn_close_type()); checkpoint(); if (!get_choice_close_txn_before_checkpoint()) close_txn(get_choice_txn_close_type()); } else { crash_during_checkpoint = get_choice_crash_checkpoint_in_callback(); assert(!crash_during_checkpoint); close_txn(get_choice_txn_close_type()); } } static void create_and_maybe_checkpoint_and_or_close_after_create(void) { fcreate(); switch (get_choice_create_type()) { case (CREATE_CREATE): //Just create break; case (CREATE_CHECKPOINT): //Create then checkpoint checkpoint(); break; case (CREATE_COMMIT_NEW): //Create then commit close_txn(CLOSE_TXN_COMMIT); make_txn(); break; case (CREATE_COMMIT_NEW_CHECKPOINT): //Create then commit then create new txn then checkpoint close_txn(CLOSE_TXN_COMMIT); make_txn(); checkpoint(); break; case (CREATE_COMMIT_CHECKPOINT_NEW): //Create then commit then checkpoint then create new txn close_txn(CLOSE_TXN_COMMIT); checkpoint(); make_txn(); break; case (CREATE_CHECKPOINT_COMMIT_NEW): //Create then checkpoint then commit then create new txn checkpoint(); close_txn(CLOSE_TXN_COMMIT); make_txn(); break; default: assert(false); break; } } static void maybe_open_and_close_file_again_before_fileop(void) { if (get_choice_txn_does_open_close_before_fileop()) { int r; r = db_create(&db, env, 0); CKERR(r); r = db->open(db, txn, oldname, NULL, DB_BTREE, 0, 0666); CKERR(r); r = db->close(db, 0); CKERR(r); } } static void delete_and_crash(void) { //Make txn make_txn(); //fcreate create_and_maybe_checkpoint_and_or_close_after_create(); maybe_open_and_close_file_again_before_fileop(); fdelete(); if (get_choice_do_checkpoint_after_fileop()) { crash_during_checkpoint = get_choice_crash_checkpoint_in_callback(); if (get_choice_close_txn_before_checkpoint()) close_txn(get_choice_txn_close_type()); checkpoint(); if (!get_choice_close_txn_before_checkpoint()) close_txn(get_choice_txn_close_type()); } else { crash_during_checkpoint = get_choice_crash_checkpoint_in_callback(); assert(!crash_during_checkpoint); close_txn(get_choice_txn_close_type()); } } static void rename_and_crash(void) { //Make txn make_txn(); //fcreate create_and_maybe_checkpoint_and_or_close_after_create(); maybe_open_and_close_file_again_before_fileop(); frename(); if (get_choice_do_checkpoint_after_fileop()) { crash_during_checkpoint = get_choice_crash_checkpoint_in_callback(); if (get_choice_close_txn_before_checkpoint()) close_txn(get_choice_txn_close_type()); checkpoint(); if (!get_choice_close_txn_before_checkpoint()) close_txn(get_choice_txn_close_type()); } else { crash_during_checkpoint = get_choice_crash_checkpoint_in_callback(); assert(!crash_during_checkpoint); close_txn(get_choice_txn_close_type()); } } static void execute_and_crash(void) { maybe_make_oldest_living_txn(); //split into create/delete/rename if (fileop=='c') create_and_crash(); else if (fileop == 'd') delete_and_crash(); else { assert(fileop == 'r'); rename_and_crash(); } crash_it(); } static int did_create_commit_early(void) { int r; switch (get_choice_create_type()) { case (CREATE_CREATE): //Just create case (CREATE_CHECKPOINT): //Create then checkpoint r = 0; break; case (CREATE_COMMIT_NEW): //Create then commit case (CREATE_COMMIT_NEW_CHECKPOINT): //Create then commit then create new txn then checkpoint case (CREATE_COMMIT_CHECKPOINT_NEW): //Create then commit then checkpoint then create new txn case (CREATE_CHECKPOINT_COMMIT_NEW): //Create then checkpoint then commit then create new txn r = 1; break; default: assert(false); } return r; } static int getf_do_nothing(DBT const* UU(key), DBT const* UU(val), void* UU(extra)) { return 0; } static void verify_file_exists(const char *name, int should_exist) { int r; make_txn(); r = db_create(&db, env, 0); CKERR(r); r = db->open(db, txn, name, NULL, DB_BTREE, 0, 0666); if (should_exist) { CKERR(r); DBT key, val; dbt_init(&key, choices, sizeof(choices)); dbt_init(&val, NULL, 0); r = db->get(db, txn, &key, &val, 0); r = db->getf_set(db, txn, 0, &key, getf_do_nothing, NULL); CKERR(r); dbt_init(&key, "name", sizeof("name")); dbt_init(&val, (void*)name, strlen(name)+1); r = db->getf_set(db, txn, 0, &key, getf_do_nothing, NULL); CKERR(r); DBC *c; r = db->cursor(db, txn, &c, 0); CKERR(r); int num_found = 0; while ((r = c->c_getf_next(c, 0, getf_do_nothing, NULL)) == 0) { num_found++; } CKERR2(r, DB_NOTFOUND); assert(num_found == 2); //name and choices array. r = c->c_close(c); CKERR(r); } else CKERR2(r, ENOENT); r = db->close(db, 0); CKERR(r); close_txn(CLOSE_TXN_COMMIT); } static int fileop_did_commit(void) { return get_choice_txn_close_type() == CLOSE_TXN_COMMIT && (!get_choice_do_checkpoint_after_fileop() || !get_choice_crash_checkpoint_in_callback() || get_choice_close_txn_before_checkpoint()); } static void recover_and_verify(void) { //Recovery was done during env_startup int expect_old_name = 0; int expect_new_name = 0; if (fileop=='c') { expect_old_name = fileop_did_commit(); } else if (fileop == 'd') { expect_old_name = did_create_commit_early() && !fileop_did_commit(); } else { //Wrong? if checkpoint AND crash during checkpoint if (fileop_did_commit()) expect_new_name = 1; else if (did_create_commit_early()) expect_old_name = 1; } // We can't expect files existence until recovery log was not flushed if ((get_choice_flush_log_before_crash())) { verify_file_exists(oldname, expect_old_name); verify_file_exists(newname, expect_new_name); } env_shutdown(); } int test_main(int argc, char * const argv[]) { crash_during_checkpoint = 0; //Do not crash during checkpoint (possibly during recovery). do_args(argc, argv); env_startup(); if (do_crash) execute_and_crash(); else recover_and_verify(); return 0; }
28.249617
127
0.587521
jiunbae
cc9b313ca44aac7dbcd9df1dcb229f9587977680
10,473
cc
C++
hwy/tests/float_test.cc
clayne/highway
af2cd99390a5bdfeb3fe7b2acc59acbe413943e9
[ "Apache-2.0" ]
null
null
null
hwy/tests/float_test.cc
clayne/highway
af2cd99390a5bdfeb3fe7b2acc59acbe413943e9
[ "Apache-2.0" ]
null
null
null
hwy/tests/float_test.cc
clayne/highway
af2cd99390a5bdfeb3fe7b2acc59acbe413943e9
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Google LLC // SPDX-License-Identifier: Apache-2.0 // // 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. // Tests some ops specific to floating-point types (Div, Round etc.) #include <inttypes.h> #include <stddef.h> #include <stdint.h> #include <algorithm> #include <limits> #undef HWY_TARGET_INCLUDE #define HWY_TARGET_INCLUDE "tests/float_test.cc" #include "hwy/foreach_target.h" #include "hwy/highway.h" #include "hwy/tests/test_util-inl.h" HWY_BEFORE_NAMESPACE(); namespace hwy { namespace HWY_NAMESPACE { struct TestDiv { template <typename T, class D> HWY_NOINLINE void operator()(T /*unused*/, D d) { const auto v = Iota(d, T(-2)); const auto v1 = Set(d, T(1)); // Unchanged after division by 1. HWY_ASSERT_VEC_EQ(d, v, Div(v, v1)); const size_t N = Lanes(d); auto expected = AllocateAligned<T>(N); for (size_t i = 0; i < N; ++i) { expected[i] = (T(i) - 2) / T(2); } HWY_ASSERT_VEC_EQ(d, expected.get(), Div(v, Set(d, T(2)))); } }; HWY_NOINLINE void TestAllDiv() { ForFloatTypes(ForPartialVectors<TestDiv>()); } struct TestApproximateReciprocal { template <typename T, class D> HWY_NOINLINE void operator()(T /*unused*/, D d) { const auto v = Iota(d, T(-2)); const auto nonzero = IfThenElse(Eq(v, Zero(d)), Set(d, T(1)), v); const size_t N = Lanes(d); auto input = AllocateAligned<T>(N); Store(nonzero, d, input.get()); auto actual = AllocateAligned<T>(N); Store(ApproximateReciprocal(nonzero), d, actual.get()); double max_l1 = 0.0; double worst_expected = 0.0; double worst_actual = 0.0; for (size_t i = 0; i < N; ++i) { const double expected = 1.0 / input[i]; const double l1 = std::abs(expected - actual[i]); if (l1 > max_l1) { max_l1 = l1; worst_expected = expected; worst_actual = actual[i]; } } const double abs_worst_expected = std::abs(worst_expected); if (abs_worst_expected > 1E-5) { const double max_rel = max_l1 / abs_worst_expected; fprintf(stderr, "max l1 %f rel %f (%f vs %f)\n", max_l1, max_rel, worst_expected, worst_actual); HWY_ASSERT(max_rel < 0.004); } } }; HWY_NOINLINE void TestAllApproximateReciprocal() { ForPartialVectors<TestApproximateReciprocal>()(float()); } struct TestSquareRoot { template <typename T, class D> HWY_NOINLINE void operator()(T /*unused*/, D d) { const auto vi = Iota(d, 0); HWY_ASSERT_VEC_EQ(d, vi, Sqrt(Mul(vi, vi))); } }; HWY_NOINLINE void TestAllSquareRoot() { ForFloatTypes(ForPartialVectors<TestSquareRoot>()); } struct TestReciprocalSquareRoot { template <typename T, class D> HWY_NOINLINE void operator()(T /*unused*/, D d) { const auto v = Set(d, 123.0f); const size_t N = Lanes(d); auto lanes = AllocateAligned<T>(N); Store(ApproximateReciprocalSqrt(v), d, lanes.get()); for (size_t i = 0; i < N; ++i) { float err = lanes[i] - 0.090166f; if (err < 0.0f) err = -err; if (err >= 4E-4f) { HWY_ABORT("Lane %" PRIu64 "(%" PRIu64 "): actual %f err %f\n", static_cast<uint64_t>(i), static_cast<uint64_t>(N), lanes[i], err); } } } }; HWY_NOINLINE void TestAllReciprocalSquareRoot() { ForPartialVectors<TestReciprocalSquareRoot>()(float()); } template <typename T, class D> AlignedFreeUniquePtr<T[]> RoundTestCases(T /*unused*/, D d, size_t& padded) { const T eps = std::numeric_limits<T>::epsilon(); const T test_cases[] = { // +/- 1 T(1), T(-1), // +/- 0 T(0), T(-0), // near 0 T(0.4), T(-0.4), // +/- integer T(4), T(-32), // positive near limit MantissaEnd<T>() - T(1.5), MantissaEnd<T>() + T(1.5), // negative near limit -MantissaEnd<T>() - T(1.5), -MantissaEnd<T>() + T(1.5), // positive tiebreak T(1.5), T(2.5), // negative tiebreak T(-1.5), T(-2.5), // positive +/- delta T(2.0001), T(3.9999), // negative +/- delta T(-999.9999), T(-998.0001), // positive +/- epsilon T(1) + eps, T(1) - eps, // negative +/- epsilon T(-1) + eps, T(-1) - eps, // +/- huge (but still fits in float) T(1E34), T(-1E35), // +/- infinity std::numeric_limits<T>::infinity(), -std::numeric_limits<T>::infinity(), // qNaN GetLane(NaN(d)) }; const size_t kNumTestCases = sizeof(test_cases) / sizeof(test_cases[0]); const size_t N = Lanes(d); padded = RoundUpTo(kNumTestCases, N); // allow loading whole vectors auto in = AllocateAligned<T>(padded); auto expected = AllocateAligned<T>(padded); std::copy(test_cases, test_cases + kNumTestCases, in.get()); std::fill(in.get() + kNumTestCases, in.get() + padded, T(0)); return in; } struct TestRound { template <typename T, class D> HWY_NOINLINE void operator()(T t, D d) { size_t padded; auto in = RoundTestCases(t, d, padded); auto expected = AllocateAligned<T>(padded); for (size_t i = 0; i < padded; ++i) { // Avoid [std::]round, which does not round to nearest *even*. // NOTE: std:: version from C++11 cmath is not defined in RVV GCC, see // https://lists.freebsd.org/pipermail/freebsd-current/2014-January/048130.html expected[i] = static_cast<T>(nearbyint(in[i])); } for (size_t i = 0; i < padded; i += Lanes(d)) { HWY_ASSERT_VEC_EQ(d, &expected[i], Round(Load(d, &in[i]))); } } }; HWY_NOINLINE void TestAllRound() { ForFloatTypes(ForPartialVectors<TestRound>()); } struct TestNearestInt { template <typename TF, class DF> HWY_NOINLINE void operator()(TF tf, const DF df) { using TI = MakeSigned<TF>; const RebindToSigned<DF> di; size_t padded; auto in = RoundTestCases(tf, df, padded); auto expected = AllocateAligned<TI>(padded); constexpr double max = static_cast<double>(LimitsMax<TI>()); for (size_t i = 0; i < padded; ++i) { if (std::isnan(in[i])) { // We replace NaN with 0 below (no_nan) expected[i] = 0; } else if (std::isinf(in[i]) || double(std::abs(in[i])) >= max) { // Avoid undefined result for lrintf expected[i] = std::signbit(in[i]) ? LimitsMin<TI>() : LimitsMax<TI>(); } else { expected[i] = static_cast<TI>(lrintf(in[i])); } } for (size_t i = 0; i < padded; i += Lanes(df)) { const auto v = Load(df, &in[i]); const auto no_nan = IfThenElse(Eq(v, v), v, Zero(df)); HWY_ASSERT_VEC_EQ(di, &expected[i], NearestInt(no_nan)); } } }; HWY_NOINLINE void TestAllNearestInt() { ForPartialVectors<TestNearestInt>()(float()); } struct TestTrunc { template <typename T, class D> HWY_NOINLINE void operator()(T t, D d) { size_t padded; auto in = RoundTestCases(t, d, padded); auto expected = AllocateAligned<T>(padded); for (size_t i = 0; i < padded; ++i) { // NOTE: std:: version from C++11 cmath is not defined in RVV GCC, see // https://lists.freebsd.org/pipermail/freebsd-current/2014-January/048130.html expected[i] = static_cast<T>(trunc(in[i])); } for (size_t i = 0; i < padded; i += Lanes(d)) { HWY_ASSERT_VEC_EQ(d, &expected[i], Trunc(Load(d, &in[i]))); } } }; HWY_NOINLINE void TestAllTrunc() { ForFloatTypes(ForPartialVectors<TestTrunc>()); } struct TestCeil { template <typename T, class D> HWY_NOINLINE void operator()(T t, D d) { size_t padded; auto in = RoundTestCases(t, d, padded); auto expected = AllocateAligned<T>(padded); for (size_t i = 0; i < padded; ++i) { expected[i] = std::ceil(in[i]); } for (size_t i = 0; i < padded; i += Lanes(d)) { HWY_ASSERT_VEC_EQ(d, &expected[i], Ceil(Load(d, &in[i]))); } } }; HWY_NOINLINE void TestAllCeil() { ForFloatTypes(ForPartialVectors<TestCeil>()); } struct TestFloor { template <typename T, class D> HWY_NOINLINE void operator()(T t, D d) { size_t padded; auto in = RoundTestCases(t, d, padded); auto expected = AllocateAligned<T>(padded); for (size_t i = 0; i < padded; ++i) { expected[i] = std::floor(in[i]); } for (size_t i = 0; i < padded; i += Lanes(d)) { HWY_ASSERT_VEC_EQ(d, &expected[i], Floor(Load(d, &in[i]))); } } }; HWY_NOINLINE void TestAllFloor() { ForFloatTypes(ForPartialVectors<TestFloor>()); } struct TestAbsDiff { template <typename T, class D> HWY_NOINLINE void operator()(T /*unused*/, D d) { const size_t N = Lanes(d); auto in_lanes_a = AllocateAligned<T>(N); auto in_lanes_b = AllocateAligned<T>(N); auto out_lanes = AllocateAligned<T>(N); for (size_t i = 0; i < N; ++i) { in_lanes_a[i] = static_cast<T>((i ^ 1u) << i); in_lanes_b[i] = static_cast<T>(i << i); out_lanes[i] = std::abs(in_lanes_a[i] - in_lanes_b[i]); } const auto a = Load(d, in_lanes_a.get()); const auto b = Load(d, in_lanes_b.get()); const auto expected = Load(d, out_lanes.get()); HWY_ASSERT_VEC_EQ(d, expected, AbsDiff(a, b)); HWY_ASSERT_VEC_EQ(d, expected, AbsDiff(b, a)); } }; HWY_NOINLINE void TestAllAbsDiff() { ForPartialVectors<TestAbsDiff>()(float()); } // NOLINTNEXTLINE(google-readability-namespace-comments) } // namespace HWY_NAMESPACE } // namespace hwy HWY_AFTER_NAMESPACE(); #if HWY_ONCE namespace hwy { HWY_BEFORE_TEST(HwyFloatTest); HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllDiv); HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllApproximateReciprocal); HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllSquareRoot); HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllReciprocalSquareRoot); HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllRound); HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllNearestInt); HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllTrunc); HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllCeil); HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllFloor); HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllAbsDiff); } // namespace hwy #endif
29.752841
85
0.634107
clayne
cca1994074eed5734a9fbc22fbe4099d5f9fc42f
2,075
hpp
C++
src/Module/Modem/SCMA/Modem_SCMA.hpp
OlivierHartmann/aff3ct
58c66228b24e09463bd43ea6453ef18bcacd4d8f
[ "MIT" ]
null
null
null
src/Module/Modem/SCMA/Modem_SCMA.hpp
OlivierHartmann/aff3ct
58c66228b24e09463bd43ea6453ef18bcacd4d8f
[ "MIT" ]
4
2018-09-27T16:46:31.000Z
2018-11-22T11:10:41.000Z
src/Module/Modem/SCMA/Modem_SCMA.hpp
OlivierHartmann/aff3ct
58c66228b24e09463bd43ea6453ef18bcacd4d8f
[ "MIT" ]
null
null
null
#ifndef MODEM_SCMA_HPP_ #define MODEM_SCMA_HPP_ #include <complex> #include <vector> #include "Tools/Code/SCMA/modem_SCMA_functions.hpp" #include "../Modem.hpp" namespace aff3ct { namespace module { template <typename B = int, typename R = float, typename Q = R, tools::proto_psi<Q> PSI = tools::psi_0> class Modem_SCMA : public Modem<B,R,Q> { private: const static std::complex<float> CB[6][4][4]; const int re_user[4][3] = {{1,2,4},{0,2,5},{1,3,5},{0,3,4}}; Q arr_phi[4][4][4][4] = {}; // probability functions const bool disable_sig2; R n0; // 1 / n0 = 179.856115108 const int n_ite; public: Modem_SCMA(const int N, const tools::Noise<R>& noise = tools::Sigma<R>(), const int bps = 3, const bool disable_sig2 = false, const int n_ite = 1, const int n_frames = 6); virtual ~Modem_SCMA() = default; virtual void set_noise(const tools::Noise<R>& noise); virtual void modulate ( const B* X_N1, R *X_N2, const int frame_id = -1); using Modem<B,R,Q>::modulate; virtual void demodulate ( const Q *Y_N1, Q *Y_N2, const int frame_id = -1); using Modem<B,R,Q>::demodulate; virtual void demodulate_wg(const R *H_N, const Q *Y_N1, Q *Y_N2, const int frame_id = -1); using Modem<B,R,Q>::demodulate_wg; virtual void filter ( const R *Y_N1, R *Y_N2, const int frame_id = -1); using Modem<B,R,Q>::filter; static bool is_complex_mod() { return true; } static bool is_complex_fil() { return true; } static int size_mod(const int N, const int bps) { return ((int)std::pow(2,bps) * ((N +1) / 2)); } static int size_fil(const int N, const int bps) { return size_mod(N, bps); } private: Q phi(const Q* Y_N1, int i, int j, int k, int re, int batch); Q phi(const Q* Y_N1, int i, int j, int k, int re, int batch, const R* H_N); void demodulate_batch(const Q* Y_N1, Q* Y_N2, int batch); }; } } #include "Modem_SCMA.hxx" #endif /* MODEM_SCMA_HPP_ */
30.072464
126
0.61012
OlivierHartmann
cca36cc4b702dcbc13369012d2af07499411556b
1,180
cpp
C++
core/optimization/Variable.cpp
metalicn20/charge
038bbfa14d8f08ffc359d877419b6b984c60ab85
[ "MIT" ]
null
null
null
core/optimization/Variable.cpp
metalicn20/charge
038bbfa14d8f08ffc359d877419b6b984c60ab85
[ "MIT" ]
null
null
null
core/optimization/Variable.cpp
metalicn20/charge
038bbfa14d8f08ffc359d877419b6b984c60ab85
[ "MIT" ]
null
null
null
#include "Variable.h" using namespace std; Variable::Variable(Alloymaker &alloymaker) { setAlloymaker(alloymaker); } void Variable::setAlloymaker(Alloymaker &value) { alloymaker = &value; } Alloymaker &Variable::getAlloymaker() { return *alloymaker; } double Variable::composition(Standard &std) { vector<string> &symbols = std.getSymbols(); size_t length = symbols.size(); double sum = 0; for (size_t i = 0; i < length; i++) { string element = symbols[i]; auto &cmp = getAlloymaker().getCompositions().get(element); sum += cmp.getPercentage(); } return sum * amount(); } double Variable::goal() { return alloymaker->getPrice(); } double Variable::amount() { return 1 - alloymaker->getLossPercentage() / 100; } double Variable::capacity() { return 1; } double Variable::lowerBound() { return alloymaker->getLowerBound(); } double Variable::upperBound() { return alloymaker->getUpperBound(); } bool Variable::isInteger() { return alloymaker->getIsQuantified(); } void Variable::setAnswer(double value) { answer = value; } double Variable::getAnswer() { return answer; }
15.733333
67
0.659322
metalicn20
ccb2eda4b66331f8b88bdf846cb6e661b814ea75
1,107
hpp
C++
include/service_log.hpp
magicmoremagic/bengine-core
fc9e1c309e62f5b2d7d4797d4b537ecfb3350d19
[ "MIT" ]
null
null
null
include/service_log.hpp
magicmoremagic/bengine-core
fc9e1c309e62f5b2d7d4797d4b537ecfb3350d19
[ "MIT" ]
null
null
null
include/service_log.hpp
magicmoremagic/bengine-core
fc9e1c309e62f5b2d7d4797d4b537ecfb3350d19
[ "MIT" ]
null
null
null
#pragma once #ifndef BE_CORE_SERVICE_LOG_HPP_ #define BE_CORE_SERVICE_LOG_HPP_ #include "service.hpp" #include "service_ids.hpp" #include "console_log_sink.hpp" #include "log.hpp" namespace be { /////////////////////////////////////////////////////////////////////////////// template <> struct SuppressUndefinedService<Log> : True { }; /////////////////////////////////////////////////////////////////////////////// template <> struct ServiceTraits<Log> : ServiceTraits<> { using lazy_ids = yes; }; /////////////////////////////////////////////////////////////////////////////// template <> struct ServiceName<Log> { const char* operator()() { return "Log"; } }; /////////////////////////////////////////////////////////////////////////////// template <> struct ServiceFactory<Log> { std::unique_ptr<Log> operator()(Id id) { std::unique_ptr<Log> ptr = std::make_unique<Log>(); if (id == Id()) { ptr->sink(ConsoleLogSink()); } else if (id == ids::core_service_log_void) { ptr->verbosity_mask(0); } return ptr; } }; } // be #endif
23.0625
79
0.455285
magicmoremagic
ccb46faba940aeba89adb75ed17c2ba62fc87e42
365
cpp
C++
src/messages/CountMessage.cpp
Wolkabout/offset-printing-machine-simulator-lib
673c45692b7f12c189e7d6d6007d01913bf868b7
[ "Apache-2.0" ]
null
null
null
src/messages/CountMessage.cpp
Wolkabout/offset-printing-machine-simulator-lib
673c45692b7f12c189e7d6d6007d01913bf868b7
[ "Apache-2.0" ]
null
null
null
src/messages/CountMessage.cpp
Wolkabout/offset-printing-machine-simulator-lib
673c45692b7f12c189e7d6d6007d01913bf868b7
[ "Apache-2.0" ]
null
null
null
// // Created by nvuletic on 8.8.19.. // #include "CountMessage.h" namespace simulator { CountMessage::CountMessage(int count, double percentage) : m_count(count), m_percentage(percentage) {} int CountMessage::getCount() const { return m_count; } double CountMessage::getPercentage() const { return m_percentage; } }
17.380952
106
0.652055
Wolkabout
ccbb82240f83480c1dff283a2e241ccafbe73505
2,169
cc
C++
2015/day16.cc
triglav/advent_of_code
e96bd0aea417076d997eeb4e49bf6e1cc04b31e0
[ "MIT" ]
null
null
null
2015/day16.cc
triglav/advent_of_code
e96bd0aea417076d997eeb4e49bf6e1cc04b31e0
[ "MIT" ]
null
null
null
2015/day16.cc
triglav/advent_of_code
e96bd0aea417076d997eeb4e49bf6e1cc04b31e0
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <unordered_map> #include "string_utils.h" bool Check(std::unordered_map<std::string_view, int> const &known_facts, std::vector<std::string_view> const &tokens) { for (int i = 2; i < tokens.size(); i += 2) { auto const thing = Trim(tokens[i], ":,"); auto const it = known_facts.find(thing); if (it == known_facts.end()) { continue; } auto const count = sv2number<int>(Trim(tokens[i + 1], ":,")); if (it->second != count) { return false; } } return true; } bool Check2(std::unordered_map<std::string_view, int> const &known_facts, std::vector<std::string_view> const &tokens) { for (int i = 2; i < tokens.size(); i += 2) { auto const thing = Trim(tokens[i], ":,"); auto const it = known_facts.find(thing); if (it == known_facts.end()) { continue; } auto const count = sv2number<int>(Trim(tokens[i + 1], ":,")); if (thing == "cats" || thing == "trees") { if (it->second >= count) { return false; } continue; } if (thing == "pomeranians" || thing == "goldfish") { if (it->second <= count) { return false; } continue; } if (it->second != count) { return false; } } return true; } int main() { std::unordered_map<std::string_view, int> known_facts; known_facts.emplace("children", 3); known_facts.emplace("cats", 7); known_facts.emplace("samoyeds", 2); known_facts.emplace("pomeranians", 3); known_facts.emplace("akitas", 0); known_facts.emplace("vizslas", 0); known_facts.emplace("goldfish", 5); known_facts.emplace("trees", 3); known_facts.emplace("cars", 2); known_facts.emplace("perfumes", 1); int idx1 = 0; int idx2 = 0; std::string line; while (std::getline(std::cin, line)) { auto const t = SplitString(line); if (Check(known_facts, t)) { assert(idx1 == 0); idx1 = sv2number<int>(Trim(t[1], ":,")); } if (Check2(known_facts, t)) { assert(idx2 == 0); idx2 = sv2number<int>(Trim(t[1], ":,")); } } std::cout << idx1 << "\n" << idx2 << "\n"; return 0; }
25.821429
73
0.573997
triglav
ccbf07113c9d9e04ac7ea016896648451d095958
404
cpp
C++
libi3/path_exists.cpp
andreatulimiero/i3pp
3e1268ec690bce1821d47df11a985145c289573c
[ "BSD-3-Clause" ]
null
null
null
libi3/path_exists.cpp
andreatulimiero/i3pp
3e1268ec690bce1821d47df11a985145c289573c
[ "BSD-3-Clause" ]
null
null
null
libi3/path_exists.cpp
andreatulimiero/i3pp
3e1268ec690bce1821d47df11a985145c289573c
[ "BSD-3-Clause" ]
null
null
null
/* * vim:ts=4:sw=4:expandtab * * i3 - an improved dynamic tiling window manager * © 2009 Michael Stapelberg and contributors (see also: LICENSE) * */ #include "libi3.hpp" #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> /* * Checks if the given path exists by calling stat(). * */ bool path_exists(const char *path) { struct stat buf; return (stat(path, &buf) == 0); }
18.363636
65
0.653465
andreatulimiero
ccbfb66b552f44a9321a1a584ac12c9fcc48c154
1,590
cpp
C++
aws-cpp-sdk-iotsitewise/source/model/CreateAccessPolicyRequest.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-iotsitewise/source/model/CreateAccessPolicyRequest.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-iotsitewise/source/model/CreateAccessPolicyRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/iotsitewise/model/CreateAccessPolicyRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::IoTSiteWise::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; CreateAccessPolicyRequest::CreateAccessPolicyRequest() : m_accessPolicyIdentityHasBeenSet(false), m_accessPolicyResourceHasBeenSet(false), m_accessPolicyPermission(Permission::NOT_SET), m_accessPolicyPermissionHasBeenSet(false), m_clientToken(Aws::Utils::UUID::RandomUUID()), m_clientTokenHasBeenSet(true), m_tagsHasBeenSet(false) { } Aws::String CreateAccessPolicyRequest::SerializePayload() const { JsonValue payload; if(m_accessPolicyIdentityHasBeenSet) { payload.WithObject("accessPolicyIdentity", m_accessPolicyIdentity.Jsonize()); } if(m_accessPolicyResourceHasBeenSet) { payload.WithObject("accessPolicyResource", m_accessPolicyResource.Jsonize()); } if(m_accessPolicyPermissionHasBeenSet) { payload.WithString("accessPolicyPermission", PermissionMapper::GetNameForPermission(m_accessPolicyPermission)); } if(m_clientTokenHasBeenSet) { payload.WithString("clientToken", m_clientToken); } if(m_tagsHasBeenSet) { JsonValue tagsJsonMap; for(auto& tagsItem : m_tags) { tagsJsonMap.WithString(tagsItem.first, tagsItem.second); } payload.WithObject("tags", std::move(tagsJsonMap)); } return payload.View().WriteReadable(); }
22.714286
114
0.755975
lintonv
ccbff3113c7f71866afd884399212a87286ec115
875
hpp
C++
src/ofxSwizzle/detail/functional/increment_decrement.hpp
t6tn4k/ofxSwizzle
7d5841e738d0f08cb5456b040c5f827be7775131
[ "MIT" ]
null
null
null
src/ofxSwizzle/detail/functional/increment_decrement.hpp
t6tn4k/ofxSwizzle
7d5841e738d0f08cb5456b040c5f827be7775131
[ "MIT" ]
null
null
null
src/ofxSwizzle/detail/functional/increment_decrement.hpp
t6tn4k/ofxSwizzle
7d5841e738d0f08cb5456b040c5f827be7775131
[ "MIT" ]
null
null
null
#ifndef OFX_SWIZZLE_DETAIL_FUNCTIONAL_INCREMENT_DECREMENT_HPP #define OFX_SWIZZLE_DETAIL_FUNCTIONAL_INCREMENT_DECREMENT_HPP #include <utility> namespace ofxSwizzle { namespace detail { struct pre_increment { template <typename T> constexpr auto operator()(T& t) const -> decltype(++t) { return ++t; } }; struct post_increment { template <typename T> constexpr auto operator()(T& t) const -> decltype(t++) { return t++; } }; struct pre_decrement { template <typename T> constexpr auto operator()(T& t) const -> decltype(--t) { return --t; } }; struct post_decrement { template <typename T> constexpr auto operator()(T& t) const -> decltype(t--) { return t--; } }; } } // namespace ofxSwizzle::detail #endif // #ifndef OFX_SWIZZLE_DETAIL_FUNCTIONAL_INCREMENT_DECREMENT_HPP
18.617021
71
0.659429
t6tn4k
ccc12c1372e0e0c2f549742135a4899726092225
1,172
cpp
C++
bench/bench_message.cpp
motion-workshop/shadowmocap-sdk-cpp
2df32936bbfb82b17401734ee850a7b710aa3806
[ "BSD-2-Clause" ]
null
null
null
bench/bench_message.cpp
motion-workshop/shadowmocap-sdk-cpp
2df32936bbfb82b17401734ee850a7b710aa3806
[ "BSD-2-Clause" ]
null
null
null
bench/bench_message.cpp
motion-workshop/shadowmocap-sdk-cpp
2df32936bbfb82b17401734ee850a7b710aa3806
[ "BSD-2-Clause" ]
null
null
null
#include <benchmark/benchmark.h> #include <shadowmocap/message.hpp> #include <algorithm> #include <random> #include <vector> std::vector<char> make_random_bytes(std::size_t n) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<int> dis(-128, 127); std::vector<char> buf(n); std::generate(std::begin(buf), std::end(buf), [&]() { return dis(gen); }); return buf; } template <int N> void BM_MessageViewCreation(benchmark::State &state) { using namespace shadowmocap; using item_type = message_view_item<N>; auto data = make_random_bytes(state.range(0) * sizeof(item_type)); for (auto _ : state) { auto v = make_message_view<N>(data); benchmark::DoNotOptimize(v); } state.SetBytesProcessed( static_cast<int64_t>(state.iterations()) * state.range(0) * sizeof(item_type)); } BENCHMARK_TEMPLATE(BM_MessageViewCreation, 8)->Range(1 << 3, 1 << 7); BENCHMARK_TEMPLATE(BM_MessageViewCreation, 16)->Range(1 << 2, 1 << 8); BENCHMARK_TEMPLATE(BM_MessageViewCreation, 32)->Range(1 << 1, 1 << 9); BENCHMARK_TEMPLATE(BM_MessageViewCreation, 64)->Range(1 << 0, 1 << 10);
26.636364
78
0.674061
motion-workshop
ccc7cd504f578562c05f68a24fb31a246c31de29
1,221
cpp
C++
algorithms/cpp/632.cpp
viing937/leetcode
e21ca52c98bddf59e43522c0aace5e8cf84350eb
[ "MIT" ]
3
2016-10-01T10:15:09.000Z
2017-07-09T02:53:36.000Z
algorithms/cpp/632.cpp
viing937/leetcode
e21ca52c98bddf59e43522c0aace5e8cf84350eb
[ "MIT" ]
null
null
null
algorithms/cpp/632.cpp
viing937/leetcode
e21ca52c98bddf59e43522c0aace5e8cf84350eb
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <queue> using namespace std; class Solution { private: struct Element { int val; int idx; int row; Element(int val, int idx, int row): val(val), idx(idx), row(row) {} bool operator <(const Element &a) const { return val > a.val; } }; public: vector<int> smallestRange(vector<vector<int>> &nums) { int maxVal = INT_MIN; priority_queue<Element> pq; for (int i = 0; i < nums.size(); i++) { maxVal = max(maxVal, nums[i][0]); pq.push(Element(nums[i][0], 0, i)); } int range = INT_MAX; vector<int> result(2); while (pq.size() == nums.size()) { Element e = pq.top(); pq.pop(); if (maxVal - e.val < range) { range = maxVal - e.val; result[0] = e.val; result[1] = maxVal; } if (e.idx+1 < nums[e.row].size()) { pq.emplace(nums[e.row][e.idx+1], e.idx+1, e.row); maxVal = max(maxVal, nums[e.row][e.idx+1]); } } return result; } }; int main() { return 0; }
25.978723
75
0.465192
viing937
cccb113e383cab85bb0427179ecb4cbe2936ba12
1,485
cpp
C++
dvdinfo/detect.cpp
XULPlayer/XULPlayer-legacy
1ab0ad2a196373d81d350bf45c03f690a0bfb8a2
[ "MIT" ]
3
2017-11-29T07:11:24.000Z
2020-03-03T19:23:33.000Z
dvdinfo/detect.cpp
XULPlayer/XULPlayer-legacy
1ab0ad2a196373d81d350bf45c03f690a0bfb8a2
[ "MIT" ]
null
null
null
dvdinfo/detect.cpp
XULPlayer/XULPlayer-legacy
1ab0ad2a196373d81d350bf45c03f690a0bfb8a2
[ "MIT" ]
1
2018-07-12T12:48:52.000Z
2018-07-12T12:48:52.000Z
#include "dvd_reader.h" #include "ifo_types.h" #include "ifo_read.h" #include "nav_read.h" #include "cdrom.h" #include "dvdinfo.h" int detect_media_type(const char *psz_path) { int i_type; char *psz_dup; char psz_tmp[20]; dvd_reader_t *dvd; vcddev_t* p_cddev; WIN32_FIND_DATA FindFileData; HANDLE hFind; if (psz_path == NULL) return TYPE_UNKNOWN; psz_dup = _strdup(psz_path); if( psz_path[0] && psz_path[1] == ':' && psz_path[2] == '\\' && psz_path[3] == '\0' ) { psz_dup[2] = '\0'; } sprintf(psz_tmp, "%c:\\*", psz_path[0]); hFind = FindFirstFile(psz_tmp, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { free(psz_dup); return TYPE_NOMEDIA; } do { /*CD?*/ sprintf(psz_tmp, "%c:\\Track*.cda", psz_path[0]); hFind = FindFirstFile(psz_tmp, &FindFileData); if (hFind != INVALID_HANDLE_VALUE) { i_type = TYPE_CD; } else { /*VCD?*/ sprintf(psz_tmp, "%c:\\MPEGAV", psz_path[0]); hFind = FindFirstFile(psz_tmp, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) break; i_type = TYPE_VCD; } /*go deeper*/ p_cddev = ioctl_Open(psz_dup); if(p_cddev == NULL) break; ioctl_Close(p_cddev); free(psz_dup); return i_type; } while (0); i_type = TYPE_UNKNOWN; /*DVD?*/ dvd = DVDOpen(psz_dup); if(dvd != NULL) { /*go deeper*/ ifo_handle_t *vmg_file; vmg_file = ifoOpen(dvd, 0); if(vmg_file != NULL) { ifoClose(vmg_file); i_type = TYPE_DVD; } DVDClose(dvd); } free(psz_dup); return i_type; }
19.038462
51
0.642424
XULPlayer
ccce06e6b4fdbb371e2d9d97416f8c732c9fff2c
1,540
cpp
C++
Aoba/src/Core/TaskRunner/TimeoutTaskManager.cpp
KondoA9/OpenSiv3d-GUIKit
355b2e7940bf00a8ef5fc3001243e450dccdeab9
[ "MIT" ]
null
null
null
Aoba/src/Core/TaskRunner/TimeoutTaskManager.cpp
KondoA9/OpenSiv3d-GUIKit
355b2e7940bf00a8ef5fc3001243e450dccdeab9
[ "MIT" ]
32
2021-10-09T10:04:11.000Z
2022-02-25T06:10:13.000Z
Aoba/src/Core/TaskRunner/TimeoutTaskManager.cpp
athnomedical/Aoba
355b2e7940bf00a8ef5fc3001243e450dccdeab9
[ "MIT" ]
null
null
null
#include "TimeoutTaskManager.hpp" namespace s3d::aoba { size_t TimeoutTaskManager::addTask(const std::function<void()>& task, double ms, bool threading) { m_timeouts.emplace_back(task, ms, threading); return m_timeouts[m_timeouts.size() - 1].id(); } bool TimeoutTaskManager::isAlive(size_t id) const { for (const auto& timeout : m_timeouts) { if (timeout.id() == id) { return timeout.isAlive(); } } return false; } bool TimeoutTaskManager::isRunning(size_t id) const { for (const auto& timeout : m_timeouts) { if (timeout.id() == id) { return timeout.isRunning(); } } return false; } void TimeoutTaskManager::update() { bool timeoutDeletable = true; for (auto& timeout : m_timeouts) { timeout.update(); timeoutDeletable &= !timeout.isAlive(); } if (timeoutDeletable) { m_timeouts.clear(); m_timeouts.shrink_to_fit(); } } bool TimeoutTaskManager::stop(size_t id) { for (auto& timeout : m_timeouts) { if (timeout.id() == id) { return timeout.stop(); } } return false; } bool TimeoutTaskManager::restart(size_t id) { for (auto& timeout : m_timeouts) { if (timeout.id() == id) { return timeout.restart(); } } return false; } }
26.101695
102
0.521429
KondoA9
ccceb823ea5512a19cbef0aea09a9ecb142d1b44
1,577
cpp
C++
src/main/cpp/autonomous/AutoRightSideIntake.cpp
calcmogul/Robot-2020
b416c202794fb7deea0081beff2f986de7001ed9
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/autonomous/AutoRightSideIntake.cpp
calcmogul/Robot-2020
b416c202794fb7deea0081beff2f986de7001ed9
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/autonomous/AutoRightSideIntake.cpp
calcmogul/Robot-2020
b416c202794fb7deea0081beff2f986de7001ed9
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) FRC Team 3512. All Rights Reserved. #include <frc/trajectory/constraint/MaxVelocityConstraint.h> #include <frc/trajectory/constraint/RectangularRegionConstraint.h> #include <wpi/numbers> #include "Robot.hpp" namespace frc3512 { void Robot::AutoRightSideIntake() { // Initial Pose - Right in line with the three balls in the Trench Run const frc::Pose2d kInitialPose{12_m, 1.05_m, units::radian_t{wpi::numbers::pi}}; // End Pose - Second ball in the Trench Run const frc::Pose2d kEndPose{7.95_m, 1.05_m, units::radian_t{wpi::numbers::pi}}; drivetrain.Reset(kInitialPose); // Add a constraint to slow down the drivetrain while it's // approaching the balls frc::RectangularRegionConstraint regionConstraint{ frc::Translation2d{kEndPose.X(), kEndPose.Y() - 0.5 * Drivetrain::kLength}, // X: First/Closest ball in the trench run frc::Translation2d{9.82_m + 0.5 * Drivetrain::kLength, kInitialPose.Y() + 0.5 * Drivetrain::kLength}, frc::MaxVelocityConstraint{1_mps}}; auto config = Drivetrain::MakeTrajectoryConfig(); config.AddConstraint(regionConstraint); drivetrain.AddTrajectory(kInitialPose, {}, kEndPose, config); // Intake Balls x2 intake.Deploy(); intake.Start(); if (!m_autonChooser.Suspend([=] { return drivetrain.AtGoal(); })) { return; } intake.Stop(); EXPECT_TRUE(turret.AtGoal()); } } // namespace frc3512
32.183673
74
0.638554
calcmogul
cccebc6745a7bd1add73efc60d91d7422cab2683
3,915
cpp
C++
Testing/TestEnumConversions.cpp
ncorgan/PothosArrayFire
b2ce286827cefdc45507dbae65879a943e977479
[ "BSD-3-Clause" ]
2
2021-01-19T02:21:48.000Z
2022-03-26T23:05:49.000Z
Testing/TestEnumConversions.cpp
ncorgan/PothosArrayFire
b2ce286827cefdc45507dbae65879a943e977479
[ "BSD-3-Clause" ]
3
2020-07-26T18:48:21.000Z
2020-10-28T00:45:42.000Z
Testing/TestEnumConversions.cpp
pothosware/PothosArrayFire
b2ce286827cefdc45507dbae65879a943e977479
[ "BSD-3-Clause" ]
1
2022-03-24T06:22:20.000Z
2022-03-24T06:22:20.000Z
// Copyright (c) 2019-2020 Nicholas Corgan // SPDX-License-Identifier: BSD-3-Clause #include "Utility.hpp" #include <Pothos/Framework.hpp> #include <Pothos/Object.hpp> #include <Pothos/Testing.hpp> #include <arrayfire.h> #include <string> #include <typeinfo> namespace GPUTests { template <typename Type1, typename Type2> static void testTypesCanConvert() { POTHOS_TEST_TRUE(Pothos::Object::canConvert( typeid(Type1), typeid(Type2))); POTHOS_TEST_TRUE(Pothos::Object::canConvert( typeid(Type2), typeid(Type1))); } template <typename EnumType> static void testEnumValueConversion( const std::string& stringVal, EnumType enumVal) { POTHOS_TEST_EQUAL( enumVal, Pothos::Object(stringVal).convert<EnumType>()); POTHOS_TEST_EQUAL( stringVal, Pothos::Object(enumVal).convert<std::string>()); } static void testDTypeEnumUsage( const std::string& dtypeName, af::dtype afDType) { Pothos::DType dtype(dtypeName); POTHOS_TEST_EQUAL( afDType, Pothos::Object(dtype).convert<af::dtype>()); POTHOS_TEST_EQUAL(dtype.size(), af::getSizeOf(afDType)); auto dtypeFromAF = Pothos::Object(afDType).convert<Pothos::DType>(); POTHOS_TEST_EQUAL(dtypeName, dtypeFromAF.name()); testEnumValueConversion(dtypeName, afDType); } } POTHOS_TEST_BLOCK("/gpu/tests", test_af_backend_conversion) { GPUTests::testTypesCanConvert<std::string, af::Backend>(); GPUTests::testEnumValueConversion("CPU", ::AF_BACKEND_CPU); GPUTests::testEnumValueConversion("CUDA", ::AF_BACKEND_CUDA); GPUTests::testEnumValueConversion("OpenCL", ::AF_BACKEND_OPENCL); } POTHOS_TEST_BLOCK("/gpu/tests", test_af_convmode_conversion) { GPUTests::testTypesCanConvert<std::string, af::convMode>(); GPUTests::testEnumValueConversion("Default", ::AF_CONV_DEFAULT); GPUTests::testEnumValueConversion("Expand", ::AF_CONV_EXPAND); } POTHOS_TEST_BLOCK("/gpu/tests", test_af_convdomain_conversion) { GPUTests::testTypesCanConvert<std::string, af::convDomain>(); GPUTests::testEnumValueConversion("Auto", ::AF_CONV_AUTO); GPUTests::testEnumValueConversion("Spatial", ::AF_CONV_SPATIAL); GPUTests::testEnumValueConversion("Freq", ::AF_CONV_FREQ); } POTHOS_TEST_BLOCK("/gpu/tests", test_af_randomenginetype_conversion) { GPUTests::testTypesCanConvert<std::string, af::randomEngineType>(); GPUTests::testEnumValueConversion("Philox", ::AF_RANDOM_ENGINE_PHILOX); GPUTests::testEnumValueConversion("Threefry", ::AF_RANDOM_ENGINE_THREEFRY); GPUTests::testEnumValueConversion("Mersenne", ::AF_RANDOM_ENGINE_MERSENNE); } POTHOS_TEST_BLOCK("/gpu/tests", test_af_topkfunction_conversion) { GPUTests::testTypesCanConvert<std::string, af::topkFunction>(); GPUTests::testEnumValueConversion("Min", ::AF_TOPK_MIN); GPUTests::testEnumValueConversion("Max", ::AF_TOPK_MAX); GPUTests::testEnumValueConversion("Default", ::AF_TOPK_DEFAULT); } POTHOS_TEST_BLOCK("/gpu/tests", test_af_dtype_conversion) { GPUTests::testTypesCanConvert<Pothos::DType, af::dtype>(); GPUTests::testDTypeEnumUsage("int8", ::b8); GPUTests::testDTypeEnumUsage("int16", ::s16); GPUTests::testDTypeEnumUsage("int32", ::s32); GPUTests::testDTypeEnumUsage("int64", ::s64); GPUTests::testDTypeEnumUsage("uint8", ::u8); GPUTests::testDTypeEnumUsage("uint16", ::u16); GPUTests::testDTypeEnumUsage("uint32", ::u32); GPUTests::testDTypeEnumUsage("uint64", ::u64); GPUTests::testDTypeEnumUsage("float32", ::f32); GPUTests::testDTypeEnumUsage("float64", ::f64); GPUTests::testDTypeEnumUsage("complex_float32", ::c32); GPUTests::testDTypeEnumUsage("complex_float64", ::c64); }
34.043478
79
0.691699
ncorgan
ccd778c92e2ae07f2ba0502f88351f5c392bddca
28,491
hpp
C++
boost/graph/r_c_shortest_paths.hpp
cpp-pm/boost
38c6c8c07f2fcc42d573b10807fef27ec14930f8
[ "BSL-1.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
boost/graph/r_c_shortest_paths.hpp
cpp-pm/boost
38c6c8c07f2fcc42d573b10807fef27ec14930f8
[ "BSL-1.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
boost/graph/r_c_shortest_paths.hpp
cpp-pm/boost
38c6c8c07f2fcc42d573b10807fef27ec14930f8
[ "BSL-1.0" ]
892
2015-01-29T16:26:19.000Z
2022-03-20T07:44:30.000Z
// r_c_shortest_paths.hpp header file // Copyright Michael Drexl 2005, 2006. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://boost.org/LICENSE_1_0.txt) #ifndef BOOST_GRAPH_R_C_SHORTEST_PATHS_HPP #define BOOST_GRAPH_R_C_SHORTEST_PATHS_HPP #include <map> #include <queue> #include <vector> #include <list> #include <boost/make_shared.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/iteration_macros.hpp> #include <boost/property_map/property_map.hpp> namespace boost { // r_c_shortest_paths_label struct template<class Graph, class Resource_Container> struct r_c_shortest_paths_label : public boost::enable_shared_from_this<r_c_shortest_paths_label<Graph, Resource_Container> > { r_c_shortest_paths_label ( const unsigned long n, const Resource_Container& rc = Resource_Container(), const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > pl = boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> >(), const typename graph_traits<Graph>::edge_descriptor& ed = graph_traits<Graph>::edge_descriptor(), const typename graph_traits<Graph>::vertex_descriptor& vd = graph_traits<Graph>::vertex_descriptor() ) : num( n ), cumulated_resource_consumption( rc ), p_pred_label( pl ), pred_edge( ed ), resident_vertex( vd ), b_is_dominated( false ), b_is_processed( false ) {} r_c_shortest_paths_label& operator=( const r_c_shortest_paths_label& other ) { if( this == &other ) return *this; this->~r_c_shortest_paths_label(); new( this ) r_c_shortest_paths_label( other ); return *this; } const unsigned long num; Resource_Container cumulated_resource_consumption; const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > p_pred_label; const typename graph_traits<Graph>::edge_descriptor pred_edge; const typename graph_traits<Graph>::vertex_descriptor resident_vertex; bool b_is_dominated; bool b_is_processed; }; // r_c_shortest_paths_label template<class Graph, class Resource_Container> inline bool operator== ( const r_c_shortest_paths_label<Graph, Resource_Container>& l1, const r_c_shortest_paths_label<Graph, Resource_Container>& l2 ) { return l1.cumulated_resource_consumption == l2.cumulated_resource_consumption; } template<class Graph, class Resource_Container> inline bool operator!= ( const r_c_shortest_paths_label<Graph, Resource_Container>& l1, const r_c_shortest_paths_label<Graph, Resource_Container>& l2 ) { return !( l1 == l2 ); } template<class Graph, class Resource_Container> inline bool operator< ( const r_c_shortest_paths_label<Graph, Resource_Container>& l1, const r_c_shortest_paths_label<Graph, Resource_Container>& l2 ) { return l1.cumulated_resource_consumption < l2.cumulated_resource_consumption; } template<class Graph, class Resource_Container> inline bool operator> ( const r_c_shortest_paths_label<Graph, Resource_Container>& l1, const r_c_shortest_paths_label<Graph, Resource_Container>& l2 ) { return l2.cumulated_resource_consumption < l1.cumulated_resource_consumption; } template<class Graph, class Resource_Container> inline bool operator<= ( const r_c_shortest_paths_label<Graph, Resource_Container>& l1, const r_c_shortest_paths_label<Graph, Resource_Container>& l2 ) { return l1 < l2 || l1 == l2; } template<class Graph, class Resource_Container> inline bool operator>= ( const r_c_shortest_paths_label<Graph, Resource_Container>& l1, const r_c_shortest_paths_label<Graph, Resource_Container>& l2 ) { return l2 < l1 || l1 == l2; } template<typename Graph, typename Resource_Container> inline bool operator< ( const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &t, const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &u) { return *t < *u; } template<typename Graph, typename Resource_Container> inline bool operator<=( const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &t, const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &u ) { return *t <= *u; } template<typename Graph, typename Resource_Container> inline bool operator> ( const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &t, const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &u ) { return *t > *u; } template<typename Graph, typename Resource_Container> inline bool operator>= ( const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &t, const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &u) { return *t >= *u; } namespace detail { // r_c_shortest_paths_dispatch function (body/implementation) template<class Graph, class VertexIndexMap, class EdgeIndexMap, class Resource_Container, class Resource_Extension_Function, class Dominance_Function, class Label_Allocator, class Visitor> void r_c_shortest_paths_dispatch ( const Graph& g, const VertexIndexMap& vertex_index_map, const EdgeIndexMap& /*edge_index_map*/, typename graph_traits<Graph>::vertex_descriptor s, typename graph_traits<Graph>::vertex_descriptor t, // each inner vector corresponds to a pareto-optimal path std::vector <std::vector <typename graph_traits <Graph>::edge_descriptor> >& pareto_optimal_solutions, std::vector <Resource_Container>& pareto_optimal_resource_containers, bool b_all_pareto_optimal_solutions, // to initialize the first label/resource container // and to carry the type information const Resource_Container& rc, Resource_Extension_Function& ref, Dominance_Function& dominance, // to specify the memory management strategy for the labels Label_Allocator /*la*/, Visitor vis ) { pareto_optimal_resource_containers.clear(); pareto_optimal_solutions.clear(); size_t i_label_num = 0; #if defined(BOOST_NO_CXX11_ALLOCATOR) typedef typename Label_Allocator::template rebind <r_c_shortest_paths_label <Graph, Resource_Container> >::other LAlloc; #else typedef typename std::allocator_traits<Label_Allocator>::template rebind_alloc <r_c_shortest_paths_label <Graph, Resource_Container> > LAlloc; typedef std::allocator_traits<LAlloc> LTraits; #endif LAlloc l_alloc; typedef boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > Splabel; std::priority_queue<Splabel, std::vector<Splabel>, std::greater<Splabel> > unprocessed_labels; bool b_feasible = true; Splabel splabel_first_label = boost::allocate_shared<r_c_shortest_paths_label<Graph, Resource_Container> >( l_alloc, i_label_num++, rc, boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> >(), typename graph_traits<Graph>::edge_descriptor(), s ); unprocessed_labels.push( splabel_first_label ); std::vector<std::list<Splabel> > vec_vertex_labels_data( num_vertices( g ) ); iterator_property_map<typename std::vector<std::list<Splabel> >::iterator, VertexIndexMap> vec_vertex_labels(vec_vertex_labels_data.begin(), vertex_index_map); vec_vertex_labels[s].push_back( splabel_first_label ); typedef std::vector<typename std::list<Splabel>::iterator> vec_last_valid_positions_for_dominance_data_type; vec_last_valid_positions_for_dominance_data_type vec_last_valid_positions_for_dominance_data( num_vertices( g ) ); iterator_property_map< typename vec_last_valid_positions_for_dominance_data_type::iterator, VertexIndexMap> vec_last_valid_positions_for_dominance (vec_last_valid_positions_for_dominance_data.begin(), vertex_index_map); BGL_FORALL_VERTICES_T(v, g, Graph) { put(vec_last_valid_positions_for_dominance, v, vec_vertex_labels[v].begin()); } std::vector<size_t> vec_last_valid_index_for_dominance_data( num_vertices( g ), 0 ); iterator_property_map<std::vector<size_t>::iterator, VertexIndexMap> vec_last_valid_index_for_dominance (vec_last_valid_index_for_dominance_data.begin(), vertex_index_map); std::vector<bool> b_vec_vertex_already_checked_for_dominance_data( num_vertices( g ), false ); iterator_property_map<std::vector<bool>::iterator, VertexIndexMap> b_vec_vertex_already_checked_for_dominance (b_vec_vertex_already_checked_for_dominance_data.begin(), vertex_index_map); while( !unprocessed_labels.empty() && vis.on_enter_loop(unprocessed_labels, g) ) { Splabel cur_label = unprocessed_labels.top(); unprocessed_labels.pop(); vis.on_label_popped( *cur_label, g ); // an Splabel object in unprocessed_labels and the respective Splabel // object in the respective list<Splabel> of vec_vertex_labels share their // embedded r_c_shortest_paths_label object // to avoid memory leaks, dominated // r_c_shortest_paths_label objects are marked and deleted when popped // from unprocessed_labels, as they can no longer be deleted at the end of // the function; only the Splabel object in unprocessed_labels still // references the r_c_shortest_paths_label object // this is also for efficiency, because the else branch is executed only // if there is a chance that extending the // label leads to new undominated labels, which in turn is possible only // if the label to be extended is undominated if( !cur_label->b_is_dominated ) { typename boost::graph_traits<Graph>::vertex_descriptor i_cur_resident_vertex = cur_label->resident_vertex; std::list<Splabel>& list_labels_cur_vertex = get(vec_vertex_labels, i_cur_resident_vertex); if( list_labels_cur_vertex.size() >= 2 && vec_last_valid_index_for_dominance[i_cur_resident_vertex] < list_labels_cur_vertex.size() ) { typename std::list<Splabel>::iterator outer_iter = list_labels_cur_vertex.begin(); bool b_outer_iter_at_or_beyond_last_valid_pos_for_dominance = false; while( outer_iter != list_labels_cur_vertex.end() ) { Splabel cur_outer_splabel = *outer_iter; typename std::list<Splabel>::iterator inner_iter = outer_iter; if( !b_outer_iter_at_or_beyond_last_valid_pos_for_dominance && outer_iter == get(vec_last_valid_positions_for_dominance, i_cur_resident_vertex) ) b_outer_iter_at_or_beyond_last_valid_pos_for_dominance = true; if( !get(b_vec_vertex_already_checked_for_dominance, i_cur_resident_vertex) || b_outer_iter_at_or_beyond_last_valid_pos_for_dominance ) { ++inner_iter; } else { inner_iter = get(vec_last_valid_positions_for_dominance, i_cur_resident_vertex); ++inner_iter; } bool b_outer_iter_erased = false; while( inner_iter != list_labels_cur_vertex.end() ) { Splabel cur_inner_splabel = *inner_iter; if( dominance( cur_outer_splabel-> cumulated_resource_consumption, cur_inner_splabel-> cumulated_resource_consumption ) ) { typename std::list<Splabel>::iterator buf = inner_iter; ++inner_iter; list_labels_cur_vertex.erase( buf ); if( cur_inner_splabel->b_is_processed ) { cur_inner_splabel.reset(); } else cur_inner_splabel->b_is_dominated = true; continue; } else ++inner_iter; if( dominance( cur_inner_splabel-> cumulated_resource_consumption, cur_outer_splabel-> cumulated_resource_consumption ) ) { typename std::list<Splabel>::iterator buf = outer_iter; ++outer_iter; list_labels_cur_vertex.erase( buf ); b_outer_iter_erased = true; if( cur_outer_splabel->b_is_processed ) { cur_outer_splabel.reset(); } else cur_outer_splabel->b_is_dominated = true; break; } } if( !b_outer_iter_erased ) ++outer_iter; } if( list_labels_cur_vertex.size() > 1 ) put(vec_last_valid_positions_for_dominance, i_cur_resident_vertex, (--(list_labels_cur_vertex.end()))); else put(vec_last_valid_positions_for_dominance, i_cur_resident_vertex, list_labels_cur_vertex.begin()); put(b_vec_vertex_already_checked_for_dominance, i_cur_resident_vertex, true); put(vec_last_valid_index_for_dominance, i_cur_resident_vertex, list_labels_cur_vertex.size() - 1); } } if( !b_all_pareto_optimal_solutions && cur_label->resident_vertex == t ) { // the devil don't sleep if( cur_label->b_is_dominated ) { cur_label.reset(); } while( unprocessed_labels.size() ) { Splabel l = unprocessed_labels.top(); unprocessed_labels.pop(); // delete only dominated labels, because nondominated labels are // deleted at the end of the function if( l->b_is_dominated ) { l.reset(); } } break; } if( !cur_label->b_is_dominated ) { cur_label->b_is_processed = true; vis.on_label_not_dominated( *cur_label, g ); typename graph_traits<Graph>::vertex_descriptor cur_vertex = cur_label->resident_vertex; typename graph_traits<Graph>::out_edge_iterator oei, oei_end; for( boost::tie( oei, oei_end ) = out_edges( cur_vertex, g ); oei != oei_end; ++oei ) { b_feasible = true; Splabel new_label = boost::allocate_shared<r_c_shortest_paths_label<Graph, Resource_Container> >( l_alloc, i_label_num++, cur_label->cumulated_resource_consumption, cur_label, *oei, target( *oei, g ) ); b_feasible = ref( g, new_label->cumulated_resource_consumption, new_label->p_pred_label->cumulated_resource_consumption, new_label->pred_edge ); if( !b_feasible ) { vis.on_label_not_feasible( *new_label, g ); new_label.reset(); } else { vis.on_label_feasible( *new_label, g ); vec_vertex_labels[new_label->resident_vertex]. push_back( new_label ); unprocessed_labels.push( new_label ); } } } else { vis.on_label_dominated( *cur_label, g ); cur_label.reset(); } } std::list<Splabel> dsplabels = get(vec_vertex_labels, t); typename std::list<Splabel>::const_iterator csi = dsplabels.begin(); typename std::list<Splabel>::const_iterator csi_end = dsplabels.end(); // if d could be reached from o if( !dsplabels.empty() ) { for( ; csi != csi_end; ++csi ) { std::vector<typename graph_traits<Graph>::edge_descriptor> cur_pareto_optimal_path; boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > p_cur_label = *csi; pareto_optimal_resource_containers. push_back( p_cur_label->cumulated_resource_consumption ); while( p_cur_label->num != 0 ) { cur_pareto_optimal_path.push_back( p_cur_label->pred_edge ); p_cur_label = p_cur_label->p_pred_label; // assertion b_is_valid beyond this point is not correct if the domination function // requires resource levels to be strictly greater than existing values // // Example // Customers // id min_arrival max_departure // 2 0 974 // 3 0 972 // 4 0 964 // 5 678 801 // // Path A: 2-3-4-5 (times: 0-16-49-84-678) // Path B: 3-2-4-5 (times: 0-18-51-62-678) // The partial path 3-2-4 dominates the other partial path 2-3-4, // though the path 3-2-4-5 does not strictly dominate the path 2-3-4-5 } pareto_optimal_solutions.push_back( cur_pareto_optimal_path ); if( !b_all_pareto_optimal_solutions ) break; } } BGL_FORALL_VERTICES_T(i, g, Graph) { std::list<Splabel>& list_labels_cur_vertex = vec_vertex_labels[i]; typename std::list<Splabel>::iterator si = list_labels_cur_vertex.begin(); const typename std::list<Splabel>::iterator si_end = list_labels_cur_vertex.end(); for(; si != si_end; ++si ) { (*si).reset(); } } } // r_c_shortest_paths_dispatch } // detail // default_r_c_shortest_paths_visitor struct struct default_r_c_shortest_paths_visitor { template<class Label, class Graph> void on_label_popped( const Label&, const Graph& ) {} template<class Label, class Graph> void on_label_feasible( const Label&, const Graph& ) {} template<class Label, class Graph> void on_label_not_feasible( const Label&, const Graph& ) {} template<class Label, class Graph> void on_label_dominated( const Label&, const Graph& ) {} template<class Label, class Graph> void on_label_not_dominated( const Label&, const Graph& ) {} template<class Queue, class Graph> bool on_enter_loop(const Queue& queue, const Graph& graph) {return true;} }; // default_r_c_shortest_paths_visitor // default_r_c_shortest_paths_allocator typedef std::allocator<int> default_r_c_shortest_paths_allocator; // default_r_c_shortest_paths_allocator // r_c_shortest_paths functions (handle/interface) // first overload: // - return all pareto-optimal solutions // - specify Label_Allocator and Visitor arguments template<class Graph, class VertexIndexMap, class EdgeIndexMap, class Resource_Container, class Resource_Extension_Function, class Dominance_Function, class Label_Allocator, class Visitor> void r_c_shortest_paths ( const Graph& g, const VertexIndexMap& vertex_index_map, const EdgeIndexMap& edge_index_map, typename graph_traits<Graph>::vertex_descriptor s, typename graph_traits<Graph>::vertex_descriptor t, // each inner vector corresponds to a pareto-optimal path std::vector<std::vector<typename graph_traits<Graph>::edge_descriptor> >& pareto_optimal_solutions, std::vector<Resource_Container>& pareto_optimal_resource_containers, // to initialize the first label/resource container // and to carry the type information const Resource_Container& rc, const Resource_Extension_Function& ref, const Dominance_Function& dominance, // to specify the memory management strategy for the labels Label_Allocator la, Visitor vis ) { r_c_shortest_paths_dispatch( g, vertex_index_map, edge_index_map, s, t, pareto_optimal_solutions, pareto_optimal_resource_containers, true, rc, ref, dominance, la, vis ); } // second overload: // - return only one pareto-optimal solution // - specify Label_Allocator and Visitor arguments template<class Graph, class VertexIndexMap, class EdgeIndexMap, class Resource_Container, class Resource_Extension_Function, class Dominance_Function, class Label_Allocator, class Visitor> void r_c_shortest_paths ( const Graph& g, const VertexIndexMap& vertex_index_map, const EdgeIndexMap& edge_index_map, typename graph_traits<Graph>::vertex_descriptor s, typename graph_traits<Graph>::vertex_descriptor t, std::vector<typename graph_traits<Graph>::edge_descriptor>& pareto_optimal_solution, Resource_Container& pareto_optimal_resource_container, // to initialize the first label/resource container // and to carry the type information const Resource_Container& rc, const Resource_Extension_Function& ref, const Dominance_Function& dominance, // to specify the memory management strategy for the labels Label_Allocator la, Visitor vis ) { // each inner vector corresponds to a pareto-optimal path std::vector<std::vector<typename graph_traits<Graph>::edge_descriptor> > pareto_optimal_solutions; std::vector<Resource_Container> pareto_optimal_resource_containers; r_c_shortest_paths_dispatch( g, vertex_index_map, edge_index_map, s, t, pareto_optimal_solutions, pareto_optimal_resource_containers, false, rc, ref, dominance, la, vis ); if (!pareto_optimal_solutions.empty()) { pareto_optimal_solution = pareto_optimal_solutions[0]; pareto_optimal_resource_container = pareto_optimal_resource_containers[0]; } } // third overload: // - return all pareto-optimal solutions // - use default Label_Allocator and Visitor template<class Graph, class VertexIndexMap, class EdgeIndexMap, class Resource_Container, class Resource_Extension_Function, class Dominance_Function> void r_c_shortest_paths ( const Graph& g, const VertexIndexMap& vertex_index_map, const EdgeIndexMap& edge_index_map, typename graph_traits<Graph>::vertex_descriptor s, typename graph_traits<Graph>::vertex_descriptor t, // each inner vector corresponds to a pareto-optimal path std::vector<std::vector<typename graph_traits<Graph>::edge_descriptor> >& pareto_optimal_solutions, std::vector<Resource_Container>& pareto_optimal_resource_containers, // to initialize the first label/resource container // and to carry the type information const Resource_Container& rc, const Resource_Extension_Function& ref, const Dominance_Function& dominance ) { r_c_shortest_paths_dispatch( g, vertex_index_map, edge_index_map, s, t, pareto_optimal_solutions, pareto_optimal_resource_containers, true, rc, ref, dominance, default_r_c_shortest_paths_allocator(), default_r_c_shortest_paths_visitor() ); } // fourth overload: // - return only one pareto-optimal solution // - use default Label_Allocator and Visitor template<class Graph, class VertexIndexMap, class EdgeIndexMap, class Resource_Container, class Resource_Extension_Function, class Dominance_Function> void r_c_shortest_paths ( const Graph& g, const VertexIndexMap& vertex_index_map, const EdgeIndexMap& edge_index_map, typename graph_traits<Graph>::vertex_descriptor s, typename graph_traits<Graph>::vertex_descriptor t, std::vector<typename graph_traits<Graph>::edge_descriptor>& pareto_optimal_solution, Resource_Container& pareto_optimal_resource_container, // to initialize the first label/resource container // and to carry the type information const Resource_Container& rc, const Resource_Extension_Function& ref, const Dominance_Function& dominance ) { // each inner vector corresponds to a pareto-optimal path std::vector<std::vector<typename graph_traits<Graph>::edge_descriptor> > pareto_optimal_solutions; std::vector<Resource_Container> pareto_optimal_resource_containers; r_c_shortest_paths_dispatch( g, vertex_index_map, edge_index_map, s, t, pareto_optimal_solutions, pareto_optimal_resource_containers, false, rc, ref, dominance, default_r_c_shortest_paths_allocator(), default_r_c_shortest_paths_visitor() ); if (!pareto_optimal_solutions.empty()) { pareto_optimal_solution = pareto_optimal_solutions[0]; pareto_optimal_resource_container = pareto_optimal_resource_containers[0]; } } // r_c_shortest_paths // check_r_c_path function template<class Graph, class Resource_Container, class Resource_Extension_Function> void check_r_c_path( const Graph& g, const std::vector <typename graph_traits <Graph>::edge_descriptor>& ed_vec_path, const Resource_Container& initial_resource_levels, // if true, computed accumulated final resource levels must // be equal to desired_final_resource_levels // if false, computed accumulated final resource levels must // be less than or equal to desired_final_resource_levels bool b_result_must_be_equal_to_desired_final_resource_levels, const Resource_Container& desired_final_resource_levels, Resource_Container& actual_final_resource_levels, const Resource_Extension_Function& ref, bool& b_is_a_path_at_all, bool& b_feasible, bool& b_correctly_extended, typename graph_traits<Graph>::edge_descriptor& ed_last_extended_arc ) { size_t i_size_ed_vec_path = ed_vec_path.size(); std::vector<typename graph_traits<Graph>::edge_descriptor> buf_path; if( i_size_ed_vec_path == 0 ) b_feasible = true; else { if( i_size_ed_vec_path == 1 || target( ed_vec_path[0], g ) == source( ed_vec_path[1], g ) ) buf_path = ed_vec_path; else for( size_t i = i_size_ed_vec_path ; i > 0; --i ) buf_path.push_back( ed_vec_path[i - 1] ); for( size_t i = 0; i < i_size_ed_vec_path - 1; ++i ) { if( target( buf_path[i], g ) != source( buf_path[i + 1], g ) ) { b_is_a_path_at_all = false; b_feasible = false; b_correctly_extended = false; return; } } } b_is_a_path_at_all = true; b_feasible = true; b_correctly_extended = false; Resource_Container current_resource_levels = initial_resource_levels; actual_final_resource_levels = current_resource_levels; for( size_t i = 0; i < i_size_ed_vec_path; ++i ) { ed_last_extended_arc = buf_path[i]; b_feasible = ref( g, actual_final_resource_levels, current_resource_levels, buf_path[i] ); current_resource_levels = actual_final_resource_levels; if( !b_feasible ) return; } if( b_result_must_be_equal_to_desired_final_resource_levels ) b_correctly_extended = actual_final_resource_levels == desired_final_resource_levels ? true : false; else { if( actual_final_resource_levels < desired_final_resource_levels || actual_final_resource_levels == desired_final_resource_levels ) b_correctly_extended = true; } } // check_path } // namespace #endif // BOOST_GRAPH_R_C_SHORTEST_PATHS_HPP
37.886968
161
0.661226
cpp-pm
ccd893a9826c4837bd402bf73b06c52f897cfd8d
35,559
cpp
C++
kernel/src/kernelimpl.cpp
Euclideon/udshell
795e2d832429c8e5e47196742afc4b452aa23ec3
[ "MIT" ]
null
null
null
kernel/src/kernelimpl.cpp
Euclideon/udshell
795e2d832429c8e5e47196742afc4b452aa23ec3
[ "MIT" ]
null
null
null
kernel/src/kernelimpl.cpp
Euclideon/udshell
795e2d832429c8e5e47196742afc4b452aa23ec3
[ "MIT" ]
null
null
null
#include "ep/cpp/platform.h" #include "ep/cpp/plugin.h" #include "kernelimpl.h" #include "components/stdiostream.h" #include "components/lua.h" #include "components/logger.h" #include "components/timerimpl.h" #include "components/pluginmanager.h" #include "components/pluginloader.h" #include "components/nativepluginloader.h" #include "ep/cpp/component/resource/kvpstore.h" #include "components/datasources/imagesource.h" #include "components/datasources/geomsource.h" #include "components/datasources/udsource.h" #include "components/console.h" // Components that do the Impl dance #include "components/componentimpl.h" #include "components/viewimpl.h" #include "components/commandmanagerimpl.h" #include "components/resourcemanagerimpl.h" #include "components/activityimpl.h" #include "components/resources/metadataimpl.h" #include "components/resources/resourceimpl.h" #include "components/resources/udmodelimpl.h" #include "components/resources/bufferimpl.h" #include "components/resources/arraybufferimpl.h" #include "components/resources/materialimpl.h" #include "components/resources/shaderimpl.h" #include "components/resources/menuimpl.h" #include "components/resources/modelimpl.h" #include "components/resources/textimpl.h" #include "components/nodes/nodeimpl.h" #include "components/nodes/scenenodeimpl.h" #include "components/nodes/udnodeimpl.h" #include "components/nodes/cameraimpl.h" #include "components/nodes/simplecameraimpl.h" #include "components/nodes/geomnodeimpl.h" #include "components/nodes/textnodeimpl.h" #include "components/sceneimpl.h" #include "components/datasources/datasourceimpl.h" #include "components/broadcasterimpl.h" #include "components/streamimpl.h" #include "components/regeximpl.h" #include "components/primitivegeneratorimpl.h" #include "components/projectimpl.h" #include "components/settingsimpl.h" #include "components/freetype.h" #include "components/datasources/fontsource.h" #include "components/resources/fontimpl.h" #include "components/fileimpl.h" #include "components/memstreamimpl.h" #include "components/socketimpl.h" #include "components/dynamiccomponent.h" #include "components/varcomponent.h" #include "components/glue/componentglue.h" #include "renderscene.h" #include "eplua.h" #include "stdcapture.h" #include "hal/hal.h" #include "hal/directory.h" #include "udPlatformUtil.h" #include "helpers.h" #include "ep/cpp/filesystem.h" namespace ep { Array<const PropertyInfo> Kernel::getProperties() const { return Array<const PropertyInfo>{ EP_MAKE_PROPERTY_RO("resourceManager", getResourceManager, "Resource manager", nullptr, 0), EP_MAKE_PROPERTY_RO("commandManager", getCommandManager, "Command manager", nullptr, 0), EP_MAKE_PROPERTY_RO("stdOutBroadcaster", getStdOutBroadcaster, "stdout broadcaster", nullptr, 0), EP_MAKE_PROPERTY_RO("stdErrBroadcaster", getStdErrBroadcaster, "stderr broadcaster", nullptr, 0), }; } Array<const MethodInfo> Kernel::getMethods() const { return Array<const MethodInfo>{ EP_MAKE_METHOD(exec, "Execute Lua script") }; } Array<const EventInfo> Kernel::getEvents() const { return Array<const EventInfo>{ EP_MAKE_EVENT(updatePulse, "Periodic update signal") }; } Array<const StaticFuncInfo> Kernel::getStaticFuncs() const { return Array<const StaticFuncInfo>{ EP_MAKE_STATICFUNC(getEnvironmentVar, "Get an environment variable"), EP_MAKE_STATICFUNC(setEnvironmentVar, "Set an environment variable") }; } ComponentDescInl *Kernel::makeKernelDescriptor(ComponentDescInl *pType) { ComponentDescInl *pDesc = epNew(ComponentDescInl); EPTHROW_IF_NULL(pDesc, Result::AllocFailure, "Memory allocation failed"); pDesc->info = Kernel::componentInfo(); pDesc->info.flags = ComponentInfoFlags::Unregistered; pDesc->baseClass = Component::componentID(); pDesc->pInit = nullptr; pDesc->pCreateInstance = nullptr; pDesc->pCreateImpl = nullptr; pDesc->pSuperDesc = nullptr; // build search trees for (auto &p : Kernel::getPropertiesImpl()) pDesc->propertyTree.insert(p.id, { p, p.pGetterMethod, p.pSetterMethod }); for (auto &m : Kernel::getMethodsImpl()) pDesc->methodTree.insert(m.id, { m, m.pMethod }); for (auto &e : Kernel::getEventsImpl()) pDesc->eventTree.insert(e.id, { e, e.pSubscribe }); for (auto &f : Kernel::getStaticFuncsImpl()) pDesc->staticFuncTree.insert(f.id, { f, (void*)f.pCall }); if (pType) { pType->pSuperDesc = pDesc; // populate the derived kernel from the base pType->PopulateFromDesc(pDesc); pDesc = pType; } return pDesc; } Kernel::Kernel(ComponentDescInl *_pType, Variant::VarMap commandLine) : Component(Kernel::makeKernelDescriptor(_pType), nullptr, "ep.Kernel0", commandLine) { // alloc impl pImpl = UniquePtr<Impl>(epNew(KernelImpl, this, commandLine)); getImpl()->StartInit(commandLine); } Kernel::~Kernel() { // HACK: undo chicken/egg hacks Component::pImpl = nullptr; (Kernel*&)pKernel = nullptr; // Unhook the registered components from our stack before they get deleted const ComponentDesc *pDesc = pType; while (pDesc) { if (pDesc->pSuperDesc && !(pDesc->pSuperDesc->info.flags & ComponentInfoFlags::Unregistered)) { (const ComponentDesc*&)pDesc->pSuperDesc = nullptr; break; } pDesc = pDesc->pSuperDesc; } } // HACK !!! (GCC and Clang) // For the implementation of epInternalInit defined in globalinitialisers to override // the weak version in epplatform.cpp at least one symbol from that file must // be referenced externally. This has been implemented in below inside // createInstance(). namespace internal { void *getStaticImplRegistry(); } Kernel* Kernel::createInstance(Variant::VarMap commandLine, int renderThreadCount) { // HACK: create the KernelImplStatic instance here! ((HashMap<SharedString, UniquePtr<RefCounted>>*)internal::getStaticImplRegistry())->insert(componentID(), UniquePtr<KernelImplStatic>::create()); // set $(AppPath) to argv[0] String exe = commandLine[0].asString(); #if defined(EP_WINDOWS) Kernel::setEnvironmentVar("AppPath", exe.getLeftAtLast('\\', true)); #else Kernel::setEnvironmentVar("AppPath", exe.getLeftAtLast('/', true)); #endif if (!commandLine.get("renderThreadCount")) { auto map = commandLine.clone(); map.insert("renderThreadCount", renderThreadCount); commandLine = std::move(map); } return createInstanceInternal(commandLine); } KernelImpl::VarAVLTreeAllocator* KernelImpl::s_pVarAVLAllocator; KernelImpl::WeakRefRegistryMap* KernelImpl::s_pWeakRefRegistry; KernelImpl::StaticImplRegistryMap* KernelImpl::s_pStaticImplRegistry; KernelImpl::KernelImpl(Kernel *pInstance, Variant::VarMap initParams) : ImplSuper(pInstance) , componentRegistry(256) , glueRegistry(64) , instanceRegistry(8192) , namedInstanceRegistry(4096) , foreignInstanceRegistry(4096) , messageHandlers(64) , commandLineArgs(initParams) { s_pInstance->pKernelInstance = pInstance; } void KernelImpl::StartInit(Variant::VarMap initParams) { // init the kernel epscope(fail) { DebugFormat("Error creating Kernel\n"); }; renderThreadCount = initParams["renderThreadCount"].as<int>(); // register global environment vars WrangleEnvironmentVariables(); // register the base Component type pInstance->registerComponentType<Component, ComponentImpl, ComponentGlue>(); // HACK: update the descriptor with the base class (bootup chicken/egg) const ComponentDescInl *pComponentBase = componentRegistry.get(Component::componentID())->pDesc; ComponentDescInl *pDesc = (ComponentDescInl*)pInstance->pType; while (pDesc->pSuperDesc) { // make sure each component in the kernel hierarchy get all the component meta pDesc->PopulateFromDesc(pComponentBase); pDesc = (ComponentDescInl*)pDesc->pSuperDesc; } pDesc->pSuperDesc = pComponentBase; // HACK: fix up the base class since we have a kernel instance (bootup chicken/egg) (Kernel*&)pInstance->pKernel = pInstance; pInstance->Component::pImpl = pInstance->Component::createImpl(initParams); // register all the builtin component types pInstance->registerComponentType<DataSource, DataSourceImpl>(); pInstance->registerComponentType<Broadcaster, BroadcasterImpl>(); pInstance->registerComponentType<Stream, StreamImpl>(); pInstance->registerComponentType<File, FileImpl, void, FileImplStatic>(); pInstance->registerComponentType<StdIOStream>(); pInstance->registerComponentType<MemStream, MemStreamImpl>(); pInstance->registerComponentType<Socket, SocketImpl>(); pInstance->registerComponentType<Regex, RegexImpl>(); pInstance->registerComponentType<Logger>(); pInstance->registerComponentType<PluginManager>(); pInstance->registerComponentType<PluginLoader>(); pInstance->registerComponentType<NativePluginLoader>(); pInstance->registerComponentType<ResourceManager, ResourceManagerImpl>(); pInstance->registerComponentType<CommandManager, CommandManagerImpl>(); pInstance->registerComponentType<Project, ProjectImpl>(); pInstance->registerComponentType<Timer, TimerImpl>(); pInstance->registerComponentType<Settings, SettingsImpl>(); pInstance->registerComponentType<FreeType>(); pInstance->registerComponentType<Lua>(); pInstance->registerComponentType<View, ViewImpl>(); pInstance->registerComponentType<Activity, ActivityImpl>(); pInstance->registerComponentType<Console>(); pInstance->registerComponentType<PrimitiveGenerator, PrimitiveGeneratorImpl, void, PrimitiveGeneratorImplStatic>(); // resources pInstance->registerComponentType<Resource, ResourceImpl>(); pInstance->registerComponentType<Buffer, BufferImpl>(); pInstance->registerComponentType<ArrayBuffer, ArrayBufferImpl>(); pInstance->registerComponentType<UDModel, UDModelImpl>(); pInstance->registerComponentType<Shader, ShaderImpl>(); pInstance->registerComponentType<Material, MaterialImpl>(); pInstance->registerComponentType<Model, ModelImpl>(); pInstance->registerComponentType<Text, TextImpl, void, TextImplStatic>(); pInstance->registerComponentType<Menu, MenuImpl>(); pInstance->registerComponentType<KVPStore>(); pInstance->registerComponentType<Metadata, MetadataImpl>(); pInstance->registerComponentType<Scene, SceneImpl>(); pInstance->registerComponentType<Font, FontImpl>(); // nodes pInstance->registerComponentType<Node, NodeImpl>(); pInstance->registerComponentType<SceneNode, SceneImpl>(); pInstance->registerComponentType<Camera, CameraImpl>(); pInstance->registerComponentType<SimpleCamera, SimpleCameraImpl>(); pInstance->registerComponentType<GeomNode, GeomNodeImpl>(); pInstance->registerComponentType<UDNode, UDNodeImpl>(); pInstance->registerComponentType<TextNode, TextNodeImpl>(); // data sources pInstance->registerComponentType<ImageSource>(); pInstance->registerComponentType<GeomSource>(); pInstance->registerComponentType<UDSource>(); pInstance->registerComponentType<FontSource>(); // dynamic components pInstance->registerComponentType<DynamicComponent>(); pInstance->registerComponentType<VarComponent>(); // init the HAL EPTHROW_RESULT(epHAL_Init(), "epHAL_Init() failed"); // create logger and default streams spLogger = pInstance->createComponent<Logger>(); spLogger->disableCategory(LogCategories::Trace); try { StreamRef spDebugFile = pInstance->createComponent<File>({ { "name", "logfile" }, { "path", "epKernel.log" }, { "flags", FileOpenFlags::Append | FileOpenFlags::Read | FileOpenFlags::Write | FileOpenFlags::Create | FileOpenFlags::Text } }); spLogger->addStream(spDebugFile); spDebugFile->writeLn("\n*** Logging started ***"); } catch (...) {} #if EP_DEBUG StreamRef spStdIOStream = pInstance->createComponent<StdIOStream>({ { "output", StdIOStreamOutputs::StdDbg }, {"name", "debugout"} }); spLogger->addStream(spStdIOStream); #endif // resource manager spResourceManager = pInstance->createComponent<ResourceManager>({ { "name", "resourcemanager" } }); // command manager spCommandManager = pInstance->createComponent<CommandManager>({ { "name", "commandmanager" } }); // settings spSettings = pInstance->createComponent<Settings>({ { "name", "settings" }, { "src", "settings.epset" } }); // plugin manager spPluginManager = pInstance->createComponent<PluginManager>({ { "name", "pluginmanager" } }); spPluginManager->registerPluginLoader(pInstance->createComponent<NativePluginLoader>()); // Init capture and broadcast of stdout/stderr spStdOutBC = pInstance->createComponent<Broadcaster>({ { "name", "stdoutbc" } }); stdOutCapture = epNew(StdCapture, stdout); epscope(fail) { epDelete(stdOutCapture); }; spStdErrBC = pInstance->createComponent<Broadcaster>({ { "name", "stderrbc" } }); stdErrCapture = epNew(StdCapture, stderr); epscope(fail) { epDelete(stdErrCapture); }; // create lua VM spLua = pInstance->createComponent<Lua>(); bKernelCreated = true; // TODO: remove this? } void KernelImpl::FinishInit() { // create the renderer spRenderer = SharedPtr<Renderer>::create(pInstance, renderThreadCount); // init the components InitComponents(); // call application register if (HasMessageHandler("register")) { // TODO: Crash handler? if (!sendMessage("$register", "#", "register", nullptr)) { pInstance->onFatal("Fatal error encountered during application register phase.\nSee epKernel.log for details.\n\nExiting..."); pInstance->quit(); } } // load the plugins... Array<const String> pluginPaths; // search env vars for extra plugin paths SharedString pluginPathsVar = Kernel::getEnvironmentVar("PluginDirs"); #if defined(EP_WINDOWS) String delimiters = ";"; #else String delimiters = ";:"; #endif pluginPathsVar.tokenise([&](String token, size_t) { pluginPaths.pushBack(token); }, delimiters); // search global settings for extra plugin paths //... // default search paths have lower precedence pluginPaths.concat(Slice<const String>{ "bin/plugins", // *relative path* used during dev #if defined(EP_LINUX) "$(HOME)/.local/share/Euclideon/plugins", #endif "$(AppPath)plugins", #if defined(EP_LINUX) "/usr/local/share/Euclideon/plugins", "/usr/share/Euclideon/plugins" #endif }); LoadAllPlugins(pluginPaths); // make the kernel timers spStreamerTimer = pInstance->createComponent<Timer>({ { "interval", 0.033 } }); spStreamerTimer->elapsed.subscribe(FastDelegate<void()>(this, &KernelImpl::StreamerUpdate)); spUpdateTimer = pInstance->createComponent<Timer>({ { "interval", 0.016 } }); spUpdateTimer->elapsed.subscribe(FastDelegate<void()>(this, &KernelImpl::Update)); // call application init if (HasMessageHandler("init")) { // TODO: Crash handler? if (!sendMessage("$init", "#", "init", commandLineArgs)) { pInstance->onFatal("Fatal error encountered during application init phase.\nSee epKernel.log for details.\n\nExiting..."); pInstance->quit(); } } } KernelImpl::~KernelImpl() { spLua = nullptr; spResourceManager = nullptr; spCommandManager = nullptr; epDelete (stdOutCapture); epDelete (stdErrCapture); stdOutCapture = nullptr; stdErrCapture = nullptr; spStdErrBC = nullptr; spStdOutBC = nullptr; spLogger = nullptr; spSettings = nullptr; if (instanceRegistry.begin() != instanceRegistry.end()) { int count = 0; DebugFormat("!!!WARNING: Some Components have not been freed\n"); for (const auto &c : instanceRegistry) { ++count; DebugFormat("Unfreed Component: {0} ({1}) refCount {2} \n", c.key, c.value->getName(), c.value->use_count()); } DebugFormat("{0} Unfreed Component(s)\n", count); } epHAL_Deinit(); for (const auto &c : componentRegistry) epDelete(c.value.pDesc); } void KernelImpl::Shutdown() { // TODO: Consider whether or not to catch exceptions and then continuing the deinit path or just do nothing. if (spStreamerTimer) spStreamerTimer->elapsed.unsubscribe(FastDelegate<void()>(this, &KernelImpl::StreamerUpdate)); if (spUpdateTimer) spUpdateTimer->elapsed.unsubscribe(FastDelegate<void()>(this, &KernelImpl::Update)); // call application deinit if (HasMessageHandler("deinit")) sendMessage("$deinit", "#", "deinit", nullptr); pInstance->setFocusView(nullptr); spUpdateTimer = nullptr; spStreamerTimer = nullptr; spPluginManager = nullptr; spRenderer = nullptr; } void KernelImpl::WrangleEnvironmentVariables() { // TODO: ... } Array<SharedString> KernelImpl::ScanPluginFolder(String folderPath, Slice<const String> extFilter) { EPFindData findData; EPFind find; Array<SharedString> pluginFilenames; SharedString path = Kernel::resolveString(folderPath); if (!HalDirectory_FindFirst(&find, path.toStringz(), &findData)) return nullptr; do { if (findData.attributes & EPFA_Directory) { MutableString<260> childFolderPath(Format, "{0}/{1}", path, String((const char*)findData.pFilename)); Array<SharedString> childNames = ScanPluginFolder(childFolderPath, extFilter); for (SharedString &cName : childNames) pluginFilenames.pushBack(std::move(cName)); } else { bool valid = true; MutableString<260> filename(Format, "{0}/{1}", path, String((const char*)findData.pFilename)); for (auto &ext : extFilter) { valid = (filename.endsWithIC(ext)); if (valid) break; } if (valid) { pInstance->logInfo(2, " Found {0}", filename); pluginFilenames.pushBack(filename); } } } while (HalDirectory_FindNext(&find, &findData)); HalDirectory_FindClose(&find); return pluginFilenames; } void KernelImpl::LoadAllPlugins(Slice<const String> folderPaths) { for (auto path : folderPaths) { pInstance->logInfo(2, "Scanning {0} for plugins...", path); Array<SharedString> pluginFilenames = ScanPluginFolder(path); LoadPlugins(pluginFilenames); } } void KernelImpl::LoadPlugins(Slice<SharedString> files) { size_t numRemaining = files.length; size_t lastTry; do { // since plugins may depend on other plugins, we'll keep trying to reload plugins while loads are succeeding lastTry = numRemaining; for (auto &filename : files) { if (!filename) continue; if (spPluginManager->loadPlugin(filename)) { pInstance->logInfo(2, "Loaded plugin {0}", filename); filename = nullptr; --numRemaining; } } } while (numRemaining && numRemaining < lastTry); // output a warning if any plugins could not be loaded for (auto &filename : files) { if (filename) logWarning(2, "Could not load plugin '{0}'", filename); } } void KernelImpl::Update() { static uint64_t last = udPerfCounterStart(); uint64_t now = udPerfCounterStart(); double sec = (double)udPerfCounterMilliseconds(last, now) / 1000.0; last = now; RelayStdIO(); pInstance->updatePulse.signal(sec); } void KernelImpl::RelayStdIO() { if (stdOutCapture) { String str = stdOutCapture->getCapture(); if (!str.empty()) spStdOutBC->write(str); } if (stdErrCapture) { String str = stdErrCapture->getCapture(); if (!str.empty()) spStdErrBC->write(str); } } void KernelImpl::StreamerUpdate() { udStreamerStatus streamerStatus = { 0 }; udOctree_Update(&streamerStatus); // TODO: Find a cleaner way of doing this. We have to keep rendering while the streamer is active. // We need more than just a global active , we need an active per view. if (streamerStatus.active) { SceneRef spScene = spFocusView->getScene(); if (spScene) spScene->makeDirty(); } } Array<const ComponentDesc *> KernelImpl::GetDerivedComponentDescsFromString(String id, bool bIncludeBase) { ComponentType *compType = componentRegistry.get(id); if (compType) return GetDerivedComponentDescs(compType->pDesc, bIncludeBase); else return nullptr; } Array<const ComponentDesc *> KernelImpl::GetDerivedComponentDescs(const ComponentDesc *pBase, bool bIncludeBase) { Array<const ComponentDesc *> derivedDescs; for (auto ct : componentRegistry) { const ComponentDesc *pDesc = ct.value.pDesc; if(!bIncludeBase) pDesc = pDesc->pSuperDesc; while (pDesc) { if (pDesc == pBase) { derivedDescs.concat(ct.value.pDesc); break; } pDesc = pDesc->pSuperDesc; } } return derivedDescs; } bool KernelImpl::sendMessage(String target, String sender, String message, const Variant &data) { EPASSERT_THROW(!target.empty(), Result::InvalidArgument, "target was empty"); char targetType = target.popFront(); if (targetType == '@') { // component message Component **ppComponent = instanceRegistry.get(target); if (ppComponent) { ComponentRef spComponent(*ppComponent); try { spComponent->receiveMessage(message, sender, data); } catch (std::exception &e) { logError("Message Handler {0} failed: {1}", target, e.what()); return false; } catch (...) { logError("Message Handler {0} failed: C++ exception", target); return false; } } else { // TODO: check if it's in the foreign component registry and send it there EPTHROW_ERROR(Result::Failure, "Target component not found"); } } else if (targetType == '#') { // kernel message if (target.eq(uid)) { // it's for me! try { ReceiveMessage(sender, message, data); } catch (std::exception &e) { logError("Message Handler {0} failed: {1}", target, e.what()); return false; } catch (...) { logError("Message Handler {0} failed: C++ exception", target); return false; } } else { // TODO: foreign kernels?! EPTHROW_ERROR(Result::Failure, "Invalid Kernel"); } } else if (targetType == '$') { // registered message MessageCallback *pHandler = messageHandlers.get(target); if (pHandler) { try { pHandler->callback(sender, message, data); } catch (std::exception &e) { logError("Message Handler {0} failed: {1}", target, e.what()); return false; } catch (...) { logError("Message Handler {0} failed: C++ exception", target); return false; } } else { EPTHROW_ERROR(Result::Failure, "No Message Handler"); } } else { EPTHROW_ERROR(Result::Failure, "Invalid target"); } return true; } // --------------------------------------------------------------------------------------- void KernelImpl::DispatchToMainThread(MainThreadCallback callback) { EPASSERT(false, "!!shouldn't be here!!"); } // --------------------------------------------------------------------------------------- void KernelImpl::DispatchToMainThreadAndWait(MainThreadCallback callback) { EPASSERT(false, "!!shouldn't be here!!"); } // TODO: Take this hack out once RecieveMessage's body is implemented #if defined(EP_COMPILER_VISUALC) && defined(EP_RELEASE) #pragma optimize("", off) #endif // defined(EP_COMPILER_VISUALC) && defined(EP_RELEASE) void KernelImpl::ReceiveMessage(String sender, String message, const Variant &data) { } #if defined(EP_COMPILER_VISUALC) && defined(EP_RELEASE) #pragma optimize("", on) #endif // defined(EP_COMPILER_VISUALC) && defined(EP_RELEASE) void KernelImpl::RegisterMessageHandler(SharedString _name, MessageHandler messageHandler) { messageHandlers.replace(_name, MessageCallback{ _name, messageHandler }); } const ComponentDesc* KernelImpl::RegisterComponentType(ComponentDescInl *pDesc) { if (pDesc->info.identifier.exists('@') || pDesc->info.identifier.exists('$') || pDesc->info.identifier.exists('#')) EPTHROW_ERROR(Result::InvalidArgument, "Invalid component id"); // disallow duplicates if (componentRegistry.get(pDesc->info.identifier)) EPTHROW_ERROR(Result::InvalidArgument, "Component of type id '{0}' has already been registered", pDesc->info.identifier); // add to registry componentRegistry.insert(pDesc->info.identifier, ComponentType{ pDesc, 0 }); if (bKernelCreated && pDesc->pInit) pDesc->pInit(pInstance); return pDesc; } const ComponentDesc* KernelImpl::RegisterComponentTypeFromMap(Variant::VarMap typeDesc) { DynamicComponentDesc *pDesc = epNew(DynamicComponentDesc); pDesc->info.identifier = typeDesc["identifier"].asSharedString(); size_t offset = pDesc->info.identifier.findLast('.'); EPTHROW_IF(offset == (size_t)-1, Result::InvalidArgument, "Component identifier {0} has no namespace. Use form: namespace.componentname", pDesc->info.identifier); pDesc->info.nameSpace = pDesc->info.identifier.slice(0, offset); pDesc->info.name = pDesc->info.identifier.slice(offset+1, pDesc->info.identifier.length); // pDesc->info.displayName = typeDesc["name"].asSharedString(); // TODO: add this back at some point? pDesc->info.description = typeDesc["description"].asSharedString(); pDesc->info.epVersion = EP_APIVERSION; Variant *pVar = typeDesc.get("version"); pDesc->info.pluginVersion = pVar ? pVar->asSharedString() : EPKERNEL_PLUGINVERSION; pVar = typeDesc.get("flags"); pDesc->info.flags = pVar ? pVar->as<ComponentInfoFlags>() : ComponentInfoFlags(); pDesc->baseClass = typeDesc["super"].asSharedString(); pDesc->pInit = nullptr; pDesc->pCreateImpl = nullptr; pDesc->pCreateInstance = [](const ComponentDesc *_pType, Kernel *_pKernel, SharedString _uid, Variant::VarMap initParams) -> ComponentRef { MutableString128 t(Format, "New (From VarMap): {0} - {1}", _pType->info.identifier, _uid); _pKernel->logDebug(4, t); const DynamicComponentDesc *pDesc = (const DynamicComponentDesc*)_pType; DynamicComponentRef spInstance = pDesc->newInstance(KernelRef(_pKernel), initParams); ComponentRef spC = _pKernel->createGlue(pDesc->baseClass, _pType, _uid, spInstance, initParams); spInstance->attachToGlue(spC.get(), initParams); spC->pUserData = spInstance->getUserData(); return spC; }; pDesc->newInstance = typeDesc["new"].as<DynamicComponentDesc::NewInstanceFunc>(); pDesc->userData = typeDesc["userdata"].asSharedPtr(); // TODO: populate trees from stuff in dynamic descriptor // pDesc->desc.Get /* // build search trees for (auto &p : CreateHelper<_ComponentType>::GetProperties()) pDesc->propertyTree.insert(p.id, { p, p.pGetterMethod, p.pSetterMethod }); for (auto &m : CreateHelper<_ComponentType>::GetMethods()) pDesc->methodTree.insert(m.id, { m, m.pMethod }); for (auto &e : CreateHelper<_ComponentType>::GetEvents()) pDesc->eventTree.insert(e.id, { e, e.pSubscribe }); for (auto &f : CreateHelper<_ComponentType>::GetStaticFuncs()) pDesc->staticFuncTree.insert(f.id, { f, (void*)f.pCall }); */ // setup the super class and populate from its meta pDesc->pSuperDesc = GetComponentDesc(pDesc->baseClass); EPTHROW_IF(!pDesc->pSuperDesc, Result::InvalidType, "Base Component '{0}' not registered", pDesc->baseClass); pDesc->PopulateFromDesc((ComponentDescInl*)pDesc->pSuperDesc); return RegisterComponentType(pDesc); } void KernelImpl::RegisterGlueType(String name, CreateGlueFunc *pCreateFunc) { glueRegistry.insert(name, pCreateFunc); } void* KernelImpl::CreateImpl(String componentType, Component *_pInstance, Variant::VarMap initParams) { ComponentDescInl *pDesc = (ComponentDescInl*)GetComponentDesc(componentType); if (pDesc->pCreateImpl) return pDesc->pCreateImpl(_pInstance, initParams); return nullptr; } const ComponentDesc* KernelImpl::GetComponentDesc(String id) { ComponentType *pCT = componentRegistry.get(id); if (!pCT) return nullptr; return pCT->pDesc; } ComponentRef KernelImpl::CreateComponent(String typeId, Variant::VarMap initParams) { ComponentType *_pType = componentRegistry.get(typeId); EPASSERT_THROW(_pType, Result::InvalidArgument, "Unknown component type {0}", typeId); EPTHROW_IF(_pType->pDesc->info.flags & ComponentInfoFlags::Abstract, Result::InvalidType, "Cannot create component of abstract type '{0}'", typeId); try { const ComponentDescInl *pDesc = _pType->pDesc; // TODO: should we have a better uid generator than this? MutableString64 newUid(Concat, pDesc->info.identifier, _pType->createCount++); // attempt to create an instance ComponentRef spComponent(pDesc->pCreateInstance(pDesc, pInstance, newUid, initParams)); // add to the component registry instanceRegistry.insert(spComponent->uid, spComponent.get()); // TODO: inform partner kernels that I created a component //... return spComponent; } catch (std::exception &e) { logWarning(3, "Create component failed: {0}", String(e.what())); throw; } catch (...) { logWarning(3, "Create component failed!"); throw; } } ComponentRef KernelImpl::CreateGlue(String typeId, const ComponentDesc *_pType, SharedString _uid, ComponentRef spInstance, Variant::VarMap initParams) { CreateGlueFunc **ppCreate = glueRegistry.get(typeId); EPTHROW_IF_NULL(ppCreate, Result::InvalidType, "No glue type {0}", typeId); return (*ppCreate)(pInstance, _pType, _uid, spInstance, initParams); } void KernelImpl::DestroyComponent(Component *_pInstance) { if (_pInstance->name) namedInstanceRegistry.remove(_pInstance->name); instanceRegistry.remove(_pInstance->uid); // TODO: inform partners that I destroyed a component //... } ComponentRef KernelImpl::FindComponent(String _name) const { if (_name.empty() || _name[0] == '$' || _name[0] == '#') return nullptr; if (_name[0] == '@') _name.popFront(); Component * const * ppComponent = namedInstanceRegistry.get(_name); if (!ppComponent) ppComponent = instanceRegistry.get(_name); return ppComponent ? ComponentRef(*ppComponent) : nullptr; } void KernelImpl::InitComponents() { for (auto i : componentRegistry) { if (i.value.pDesc->pInit) i.value.pDesc->pInit(pInstance); } } void KernelImpl::InitRender() { Result result = epHAL_InitRender(); EPASSERT_THROW(result == Result::Success, result, "epHAL_InitRender() Failed"); } void KernelImpl::DeinitRender() { epHAL_DeinitRender(); } void KernelImpl::Exec(String code) { spLua->execute(code); } void KernelImpl::Log(int kind, int level, String text, String component) const { if (spLogger) spLogger->log(level, text, (LogCategories)kind, component); } const AVLTree<String, const ComponentDesc *> &KernelImpl::GetExtensionsRegistry() const { return extensionsRegistry; } void KernelImpl::RegisterExtensions(const ComponentDesc *pDesc, const Slice<const String> exts) { for (const String &e : exts) extensionsRegistry.insert(e, pDesc); } DataSourceRef KernelImpl::CreateDataSourceFromExtension(String ext, Variant::VarMap initParams) { const ComponentDesc **ppDesc = extensionsRegistry.get(ext); EPASSERT_THROW(ppDesc, Result::Failure, "No datasource for extension {0}", ext); return component_cast<DataSource>(CreateComponent((*ppDesc)->info.identifier, initParams)); } SharedPtr<Renderer> KernelImpl::GetRenderer() const { return spRenderer; } CommandManagerRef KernelImpl::GetCommandManager() const { return spCommandManager; } SettingsRef KernelImpl::GetSettings() const { return spSettings; } ResourceManagerRef KernelImpl::GetResourceManager() const { return spResourceManager; } BroadcasterRef KernelImpl::GetStdOutBroadcaster() const { return spStdOutBC; } BroadcasterRef KernelImpl::GetStdErrBroadcaster() const { return spStdErrBC; } ViewRef KernelImpl::GetFocusView() const { return spFocusView; } ViewRef KernelImpl::SetFocusView(ViewRef spView) { ViewRef spOld = spFocusView; spFocusView = spView; return spOld; } void KernelImplStatic::SetEnvironmentVar(String name, String value) { #if defined(EP_WINDOWS) _putenv_s(name.toStringz(), value.toStringz()); #else setenv(name.toStringz(), value.toStringz(), 1); #endif } MutableString<0> KernelImplStatic::GetEnvironmentVar(String name) { #if defined(EP_WINDOWS) MutableString<0> r; auto sz = name.toStringz(); size_t size; getenv_s(&size, nullptr, 0, sz); if (size) { r.reserve(size); getenv_s(&size, r.ptr, size, sz); r.length = size-1; } return r; #else return getenv(name.toStringz()); #endif } MutableString<0> KernelImplStatic::ResolveString(String string, bool bRecursive) { // TODO: do this loop in blocks rather than one byte at a time! MutableString<0> r(Reserve, string.length); for (size_t i = 0; i < string.length; ++i) { if (string[i] == '$' && string.length > i+1 && string[i+1] == '$') { ++i; r.pushBack(string[i]); } else if (string[i] == '$' && string.length > i+2 && string[i+1] == '(') { size_t end = i + 2; while (end < string.length && string[end] != ')') ++end; String var = string.slice(i+2, end); auto val = GetEnvironmentVar(var); if (val) { if (bRecursive) val = ResolveString(val, true); r.append(val); } i = end; } else r.pushBack(string[i]); } return r; } } // namespace ep #if __EP_MEMORY_DEBUG__ #if defined(EP_WINDOWS) namespace ep { namespace internal { int reportingHook(int reportType, char* userMessage, int* retVal) { static bool filter = true; static int debugMsgCount = 3; static int leakCount = 0; if (strcmp(userMessage, "Object dump complete.\n") == 0) filter = false; if (filter) { // Debug messages from our program should consist of 4 parts : // File (line) | AllocID | Block Descriptor | Memory Data if (!strstr(userMessage, ") : ")) { ++debugMsgCount; } else { if (leakCount == 0) OutputDebugStringA("Detected memory leaks!\nDumping objects ->\n"); debugMsgCount = 0; ++leakCount; } // Filter the output if it's not from our program return (debugMsgCount > 3); } return (leakCount == 0); } } // namespace internal } // namespace ep #endif // defined(EP_WINDOWS) # if defined (epInitMemoryTracking) # undef epInitMemoryTracking # endif // epInitMemoryTracking void epInitMemoryTracking() { #if defined(EP_WINDOWS) const wchar_t *pFilename = L"MemoryReport_" #if EP_DEBUG "Debug_" #else "Release_" #endif // EP_DEBUG #if defined(EP_ARCH_X64) "x64" #elif defined(EP_ARCH_X86) "x86" #else # error "Couldn't detect target architecture" #endif // defined (EP_ARCH_X64) ".txt"; HANDLE hCrtWarnReport = CreateFileW(pFilename, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hCrtWarnReport == INVALID_HANDLE_VALUE) OutputDebugStringA("Error creating CrtWarnReport.txt\n"); errno = 0; int warnMode = _CrtSetReportMode(_CRT_WARN, _CRTDBG_REPORT_MODE); _CrtSetReportMode(_CRT_WARN, warnMode | _CRTDBG_MODE_FILE); if (errno == EINVAL) OutputDebugStringA("Error calling _CrtSetReportMode() warnings\n"); errno = 0; _CrtSetReportFile(_CRT_WARN, hCrtWarnReport); if (errno == EINVAL)OutputDebugStringA("Error calling _CrtSetReportFile() warnings\n"); _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); //change the report function to only report memory leaks from program code _CrtSetReportHook(ep::internal::reportingHook); #endif } #endif // __EP_MEMORY_DEBUG__
31.083042
243
0.708344
Euclideon
ccdd2555f82ecda3316f35a445dd812b38ff13e3
193
hpp
C++
Classes/GameScene.hpp
InversePalindrome/Apophis
c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8
[ "MIT" ]
7
2018-08-20T17:28:29.000Z
2020-09-05T15:19:31.000Z
Classes/GameScene.hpp
InversePalindrome/JATR66
c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8
[ "MIT" ]
null
null
null
Classes/GameScene.hpp
InversePalindrome/JATR66
c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8
[ "MIT" ]
1
2019-12-25T12:02:03.000Z
2019-12-25T12:02:03.000Z
/* Copyright (c) 2018 Inverse Palindrome Apophis - GameScene.hpp InversePalindrome.com */ #pragma once #include <cocos/2d/CCScene.h> cocos2d::Scene* getGameScene(const std::string& level);
14.846154
55
0.751295
InversePalindrome
ef9adb4af0ba3756488f6a0f2409d695b815528d
1,875
cpp
C++
src/flapGame/flapGame/LoadPNG.cpp
KnyazQasan/First-Game-c-
417d312bb57bb2373d6d0a89892a55718bc597dc
[ "MIT" ]
239
2020-11-26T12:53:51.000Z
2022-03-24T01:02:49.000Z
src/flapGame/flapGame/LoadPNG.cpp
KnyazQasan/First-Game-c-
417d312bb57bb2373d6d0a89892a55718bc597dc
[ "MIT" ]
6
2020-11-27T04:00:44.000Z
2021-07-07T03:02:57.000Z
src/flapGame/flapGame/LoadPNG.cpp
KnyazQasan/First-Game-c-
417d312bb57bb2373d6d0a89892a55718bc597dc
[ "MIT" ]
24
2020-11-26T22:59:27.000Z
2022-02-06T04:02:50.000Z
#include <flapGame/Core.h> #include <flapGame/GLHelpers.h> // clang-format off #define STBI_MALLOC(sz) PLY_HEAP.alloc(sz) #define STBI_REALLOC(p, newsz) PLY_HEAP.realloc(p, newsz) #define STBI_FREE(p) PLY_HEAP.free(p) // clang-format om #define STB_IMAGE_IMPLEMENTATION #define STBI_ONLY_PNG #include "stb/stb_image.h" namespace flap { void premultiplySRGB(image::Image& dst) { PLY_ASSERT(dst.stride >= dst.width * 4); char* dstRow = dst.data; char* dstRowEnd = dstRow + dst.stride * dst.height; while (dstRow < dstRowEnd) { u32* d = (u32*) dstRow; u32* dEnd = d + dst.width; while (d < dEnd) { Float4 orig = ((Int4<u8>*) d)->to<Float4>() * (1.f / 255.f); Float3 linearPremultipliedColor = fromSRGB(orig.asFloat3()) * orig.a(); Float4 result = {toSRGB(linearPremultipliedColor), 1.f - orig.a()}; *(Int4<u8>*) d = (result * 255.f + 0.5f).to<Int4<u8>>(); d++; } dstRow += dst.stride; } } image::OwnImage loadPNG(StringView src, bool premultiply) { s32 w = 0; s32 h = 0; s32 numChannels = 0; stbi_set_flip_vertically_on_load(true); u8* data = stbi_load_from_memory((const stbi_uc*) src.bytes, src.numBytes, &w, &h, &numChannels, 0); if (!data) return {}; image::Format fmt = image::Format::Byte; if (numChannels == 4) { fmt = image::Format::RGBA; } else if (numChannels != 1) { PLY_ASSERT(0); } u8 bytespp = image::Image::FormatToBPP[(u32) fmt]; image::OwnImage result; result.data = (char*) data; result.stride = w * bytespp; result.width = w; result.height = h; result.bytespp = bytespp; result.format = fmt; if (premultiply && numChannels == 4) { premultiplySRGB(result); } return result; } } // namespace ply
28.409091
104
0.597333
KnyazQasan
ef9f57549e1dd00801d74e754e07ec188ad918e1
973
cpp
C++
Strings/Longest-Prefix-Suffix.cpp
Bhannasa/CP-DSA
395dbdb6b5eb5896cc4182711ff086e1fb76ef7a
[ "MIT" ]
22
2021-10-01T20:14:15.000Z
2022-02-22T15:27:20.000Z
Strings/Longest-Prefix-Suffix.cpp
Bhannasa/CP-DSA
395dbdb6b5eb5896cc4182711ff086e1fb76ef7a
[ "MIT" ]
15
2021-10-01T20:24:55.000Z
2021-10-31T05:55:14.000Z
Strings/Longest-Prefix-Suffix.cpp
Bhannasa/CP-DSA
395dbdb6b5eb5896cc4182711ff086e1fb76ef7a
[ "MIT" ]
76
2021-10-01T20:01:06.000Z
2022-03-02T16:15:24.000Z
// https://practice.geeksforgeeks.org/viewSol.php?subId=58bdb4aa62394291d57f659e2c839932&pid=703402&user=tomarshiv51 // Initial template for C++ #include <bits/stdc++.h> using namespace std; // } Driver Code Ends //User function template for C++ class Solution{ public: int lps(string s) { // Your code goes here int n=s.size(),j=0; int a[n]; a[0]=0; int i=1; while(i<n){ if(s[i]==s[j]){ a[i]=j+1; j++; i++; } else{ if(j==0){ a[i]=0; i++; } else{ j=a[j-1]; } } } return a[n-1]; } }; // { Driver Code Starts. int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); int t; cin >> t; while(t--) { string str; cin >> str; Solution ob; cout << ob.lps(str) << "\n"; } return 0; } // } Driver Code Ends
15.693548
116
0.463515
Bhannasa
efa401af672bc08b39212830123acadded6ac823
1,764
cpp
C++
mvp_tips/CPUID/CPUID/ExtendedCPU5Intel.cpp
allen7575/The-CPUID-Explorer
77d0feef70482b2e36cff300ea24271384329f60
[ "Naumen", "Condor-1.1", "MS-PL" ]
9
2017-08-31T06:03:18.000Z
2019-01-06T05:07:26.000Z
mvp_tips/CPUID/CPUID/ExtendedCPU5Intel.cpp
allen7575/The-CPUID-Explorer
77d0feef70482b2e36cff300ea24271384329f60
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
mvp_tips/CPUID/CPUID/ExtendedCPU5Intel.cpp
allen7575/The-CPUID-Explorer
77d0feef70482b2e36cff300ea24271384329f60
[ "Naumen", "Condor-1.1", "MS-PL" ]
8
2017-08-31T06:23:22.000Z
2022-01-24T06:47:19.000Z
// ExtendedCPU5Intel.cpp : implementation file // #include "stdafx.h" #include "resource.h" #include "ExtendedCPU5Intel.h" #include "CPUIDx86.h" #include "ReportRegs.h" // CExtendedCPU5Intel dialog IMPLEMENT_DYNCREATE(CExtendedCPU5Intel, CLeaves) CExtendedCPU5Intel::CExtendedCPU5Intel() : CLeaves(CExtendedCPU5Intel::IDD) { } CExtendedCPU5Intel::~CExtendedCPU5Intel() { } void CExtendedCPU5Intel::DoDataExchange(CDataExchange* pDX) { CLeaves::DoDataExchange(pDX); DDX_Control(pDX, IDC_EAX, c_EAX); DDX_Control(pDX, IDC_EBX, c_EBX); DDX_Control(pDX, IDC_ECX, c_ECX); DDX_Control(pDX, IDC_EDX, c_EDX); } BEGIN_MESSAGE_MAP(CExtendedCPU5Intel, CLeaves) END_MESSAGE_MAP() // CExtendedCPU5Intel message handlers /**************************************************************************** * CExtendedCPU5Intel::OnSetActive * Result: BOOL * * Effect: * Reports the registers ****************************************************************************/ BOOL CExtendedCPU5Intel::OnSetActive() { CPUregs regs; GetAndReport(0x80000005, regs); return CLeaves::OnSetActive(); } /**************************************************************************** * CExtendedCPU5Intel::OnInitDialog * Result: BOOL * TRUE, always * Effect: * Initializes the dialog ****************************************************************************/ BOOL CExtendedCPU5Intel::OnInitDialog() { CLeaves::OnInitDialog(); SetFixedFont(c_EAX); SetFixedFont(c_EBX); SetFixedFont(c_ECX); SetFixedFont(c_EDX); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE }
23.837838
77
0.573696
allen7575
efa44fa587e0b8ee43b264ca89fcd327d505a17d
20,926
cpp
C++
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8Path2D.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8Path2D.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8Path2D.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
// Copyright 2014 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. // This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY! #include "config.h" #include "V8Path2D.h" #include "bindings/core/v8/V8Path2D.h" #include "bindings/core/v8/V8SVGMatrix.h" #include "bindings/v8/ExceptionState.h" #include "bindings/v8/V8DOMConfiguration.h" #include "bindings/v8/V8HiddenValue.h" #include "bindings/v8/V8ObjectConstructor.h" #include "core/dom/ContextFeatures.h" #include "core/dom/Document.h" #include "core/frame/LocalDOMWindow.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/TraceEvent.h" #include "wtf/GetPtr.h" #include "wtf/RefPtr.h" namespace WebCore { static void initializeScriptWrappableForInterface(Path2D* object) { if (ScriptWrappable::wrapperCanBeStoredInObject(object)) ScriptWrappable::fromObject(object)->setTypeInfo(&V8Path2D::wrapperTypeInfo); else ASSERT_NOT_REACHED(); } } // namespace WebCore void webCoreInitializeScriptWrappableForInterface(WebCore::Path2D* object) { WebCore::initializeScriptWrappableForInterface(object); } namespace WebCore { const WrapperTypeInfo V8Path2D::wrapperTypeInfo = { gin::kEmbedderBlink, V8Path2D::domTemplate, V8Path2D::derefObject, 0, 0, 0, V8Path2D::installPerContextEnabledMethods, 0, WrapperTypeObjectPrototype, RefCountedObject }; namespace Path2DV8Internal { template <typename T> void V8_USE(T) { } static void addPathMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { if (UNLIKELY(info.Length() < 1)) { throwMinimumArityTypeErrorForMethod("addPath", "Path2D", 1, info.Length(), info.GetIsolate()); return; } Path2D* impl = V8Path2D::toNative(info.Holder()); Path2D* path; SVGMatrixTearOff* transform; { v8::TryCatch block; V8RethrowTryCatchScope rethrow(block); if (info.Length() > 0 && !V8Path2D::hasInstance(info[0], info.GetIsolate())) { throwTypeError(ExceptionMessages::failedToExecute("addPath", "Path2D", "parameter 1 is not of type 'Path2D'."), info.GetIsolate()); return; } TONATIVE_VOID_INTERNAL(path, V8Path2D::toNativeWithTypeCheck(info.GetIsolate(), info[0])); if (UNLIKELY(info.Length() <= 1)) { impl->addPath(path); return; } if (info.Length() > 1 && !isUndefinedOrNull(info[1]) && !V8SVGMatrix::hasInstance(info[1], info.GetIsolate())) { throwTypeError(ExceptionMessages::failedToExecute("addPath", "Path2D", "parameter 2 is not of type 'SVGMatrix'."), info.GetIsolate()); return; } TONATIVE_VOID_INTERNAL(transform, V8SVGMatrix::toNativeWithTypeCheck(info.GetIsolate(), info[1])); } impl->addPath(path, transform); } static void addPathMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); Path2DV8Internal::addPathMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void closePathMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { Path2D* impl = V8Path2D::toNative(info.Holder()); impl->closePath(); } static void closePathMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); Path2DV8Internal::closePathMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void moveToMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { if (UNLIKELY(info.Length() < 2)) { throwMinimumArityTypeErrorForMethod("moveTo", "Path2D", 2, info.Length(), info.GetIsolate()); return; } Path2D* impl = V8Path2D::toNative(info.Holder()); float x; float y; { v8::TryCatch block; V8RethrowTryCatchScope rethrow(block); TONATIVE_VOID_INTERNAL(x, static_cast<float>(info[0]->NumberValue())); TONATIVE_VOID_INTERNAL(y, static_cast<float>(info[1]->NumberValue())); } impl->moveTo(x, y); } static void moveToMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); Path2DV8Internal::moveToMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void lineToMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { if (UNLIKELY(info.Length() < 2)) { throwMinimumArityTypeErrorForMethod("lineTo", "Path2D", 2, info.Length(), info.GetIsolate()); return; } Path2D* impl = V8Path2D::toNative(info.Holder()); float x; float y; { v8::TryCatch block; V8RethrowTryCatchScope rethrow(block); TONATIVE_VOID_INTERNAL(x, static_cast<float>(info[0]->NumberValue())); TONATIVE_VOID_INTERNAL(y, static_cast<float>(info[1]->NumberValue())); } impl->lineTo(x, y); } static void lineToMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); Path2DV8Internal::lineToMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void quadraticCurveToMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { if (UNLIKELY(info.Length() < 4)) { throwMinimumArityTypeErrorForMethod("quadraticCurveTo", "Path2D", 4, info.Length(), info.GetIsolate()); return; } Path2D* impl = V8Path2D::toNative(info.Holder()); float cpx; float cpy; float x; float y; { v8::TryCatch block; V8RethrowTryCatchScope rethrow(block); TONATIVE_VOID_INTERNAL(cpx, static_cast<float>(info[0]->NumberValue())); TONATIVE_VOID_INTERNAL(cpy, static_cast<float>(info[1]->NumberValue())); TONATIVE_VOID_INTERNAL(x, static_cast<float>(info[2]->NumberValue())); TONATIVE_VOID_INTERNAL(y, static_cast<float>(info[3]->NumberValue())); } impl->quadraticCurveTo(cpx, cpy, x, y); } static void quadraticCurveToMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); Path2DV8Internal::quadraticCurveToMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void bezierCurveToMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { if (UNLIKELY(info.Length() < 6)) { throwMinimumArityTypeErrorForMethod("bezierCurveTo", "Path2D", 6, info.Length(), info.GetIsolate()); return; } Path2D* impl = V8Path2D::toNative(info.Holder()); float cp1x; float cp1y; float cp2x; float cp2y; float x; float y; { v8::TryCatch block; V8RethrowTryCatchScope rethrow(block); TONATIVE_VOID_INTERNAL(cp1x, static_cast<float>(info[0]->NumberValue())); TONATIVE_VOID_INTERNAL(cp1y, static_cast<float>(info[1]->NumberValue())); TONATIVE_VOID_INTERNAL(cp2x, static_cast<float>(info[2]->NumberValue())); TONATIVE_VOID_INTERNAL(cp2y, static_cast<float>(info[3]->NumberValue())); TONATIVE_VOID_INTERNAL(x, static_cast<float>(info[4]->NumberValue())); TONATIVE_VOID_INTERNAL(y, static_cast<float>(info[5]->NumberValue())); } impl->bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y); } static void bezierCurveToMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); Path2DV8Internal::bezierCurveToMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void arcToMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "arcTo", "Path2D", info.Holder(), info.GetIsolate()); if (UNLIKELY(info.Length() < 5)) { throwMinimumArityTypeError(exceptionState, 5, info.Length()); return; } Path2D* impl = V8Path2D::toNative(info.Holder()); float x1; float y1; float x2; float y2; float radius; { v8::TryCatch block; V8RethrowTryCatchScope rethrow(block); TONATIVE_VOID_INTERNAL(x1, static_cast<float>(info[0]->NumberValue())); TONATIVE_VOID_INTERNAL(y1, static_cast<float>(info[1]->NumberValue())); TONATIVE_VOID_INTERNAL(x2, static_cast<float>(info[2]->NumberValue())); TONATIVE_VOID_INTERNAL(y2, static_cast<float>(info[3]->NumberValue())); TONATIVE_VOID_INTERNAL(radius, static_cast<float>(info[4]->NumberValue())); } impl->arcTo(x1, y1, x2, y2, radius, exceptionState); if (exceptionState.hadException()) { exceptionState.throwIfNeeded(); return; } } static void arcToMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); Path2DV8Internal::arcToMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void rectMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { if (UNLIKELY(info.Length() < 4)) { throwMinimumArityTypeErrorForMethod("rect", "Path2D", 4, info.Length(), info.GetIsolate()); return; } Path2D* impl = V8Path2D::toNative(info.Holder()); float x; float y; float width; float height; { v8::TryCatch block; V8RethrowTryCatchScope rethrow(block); TONATIVE_VOID_INTERNAL(x, static_cast<float>(info[0]->NumberValue())); TONATIVE_VOID_INTERNAL(y, static_cast<float>(info[1]->NumberValue())); TONATIVE_VOID_INTERNAL(width, static_cast<float>(info[2]->NumberValue())); TONATIVE_VOID_INTERNAL(height, static_cast<float>(info[3]->NumberValue())); } impl->rect(x, y, width, height); } static void rectMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); Path2DV8Internal::rectMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void arcMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "arc", "Path2D", info.Holder(), info.GetIsolate()); if (UNLIKELY(info.Length() < 5)) { throwMinimumArityTypeError(exceptionState, 5, info.Length()); return; } Path2D* impl = V8Path2D::toNative(info.Holder()); float x; float y; float radius; float startAngle; float endAngle; bool anticlockwise; { v8::TryCatch block; V8RethrowTryCatchScope rethrow(block); TONATIVE_VOID_INTERNAL(x, static_cast<float>(info[0]->NumberValue())); TONATIVE_VOID_INTERNAL(y, static_cast<float>(info[1]->NumberValue())); TONATIVE_VOID_INTERNAL(radius, static_cast<float>(info[2]->NumberValue())); TONATIVE_VOID_INTERNAL(startAngle, static_cast<float>(info[3]->NumberValue())); TONATIVE_VOID_INTERNAL(endAngle, static_cast<float>(info[4]->NumberValue())); TONATIVE_VOID_INTERNAL(anticlockwise, info[5]->BooleanValue()); } impl->arc(x, y, radius, startAngle, endAngle, anticlockwise, exceptionState); if (exceptionState.hadException()) { exceptionState.throwIfNeeded(); return; } } static void arcMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); Path2DV8Internal::arcMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void ellipseMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "ellipse", "Path2D", info.Holder(), info.GetIsolate()); if (UNLIKELY(info.Length() < 7)) { throwMinimumArityTypeError(exceptionState, 7, info.Length()); return; } Path2D* impl = V8Path2D::toNative(info.Holder()); float x; float y; float radiusX; float radiusY; float rotation; float startAngle; float endAngle; bool anticlockwise; { v8::TryCatch block; V8RethrowTryCatchScope rethrow(block); TONATIVE_VOID_INTERNAL(x, static_cast<float>(info[0]->NumberValue())); TONATIVE_VOID_INTERNAL(y, static_cast<float>(info[1]->NumberValue())); TONATIVE_VOID_INTERNAL(radiusX, static_cast<float>(info[2]->NumberValue())); TONATIVE_VOID_INTERNAL(radiusY, static_cast<float>(info[3]->NumberValue())); TONATIVE_VOID_INTERNAL(rotation, static_cast<float>(info[4]->NumberValue())); TONATIVE_VOID_INTERNAL(startAngle, static_cast<float>(info[5]->NumberValue())); TONATIVE_VOID_INTERNAL(endAngle, static_cast<float>(info[6]->NumberValue())); TONATIVE_VOID_INTERNAL(anticlockwise, info[7]->BooleanValue()); } impl->ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise, exceptionState); if (exceptionState.hadException()) { exceptionState.throwIfNeeded(); return; } } static void ellipseMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); Path2DV8Internal::ellipseMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void constructor1(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); RefPtr<Path2D> impl = Path2D::create(); v8::Handle<v8::Object> wrapper = info.Holder(); V8DOMWrapper::associateObjectWithWrapper<V8Path2D>(impl.release(), &V8Path2D::wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent); v8SetReturnValue(info, wrapper); } static void constructor2(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); Path2D* path; { v8::TryCatch block; V8RethrowTryCatchScope rethrow(block); TONATIVE_VOID_INTERNAL(path, V8Path2D::toNativeWithTypeCheck(info.GetIsolate(), info[0])); } RefPtr<Path2D> impl = Path2D::create(path); v8::Handle<v8::Object> wrapper = info.Holder(); V8DOMWrapper::associateObjectWithWrapper<V8Path2D>(impl.release(), &V8Path2D::wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent); v8SetReturnValue(info, wrapper); } static void constructor3(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); V8StringResource<> text; { TOSTRING_VOID_INTERNAL(text, info[0]); } RefPtr<Path2D> impl = Path2D::create(text); v8::Handle<v8::Object> wrapper = info.Holder(); V8DOMWrapper::associateObjectWithWrapper<V8Path2D>(impl.release(), &V8Path2D::wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent); v8SetReturnValue(info, wrapper); } static void constructor(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); ExceptionState exceptionState(ExceptionState::ConstructionContext, "Path2D", info.Holder(), isolate); switch (std::min(1, info.Length())) { case 0: if (true) { Path2DV8Internal::constructor1(info); return; } break; case 1: if (V8Path2D::hasInstance(info[0], isolate)) { Path2DV8Internal::constructor2(info); return; } if (true) { Path2DV8Internal::constructor3(info); return; } break; default: exceptionState.throwTypeError(ExceptionMessages::notEnoughArguments(0, info.Length())); exceptionState.throwIfNeeded(); return; } exceptionState.throwTypeError("No matching constructor signature."); exceptionState.throwIfNeeded(); } } // namespace Path2DV8Internal static const V8DOMConfiguration::MethodConfiguration V8Path2DMethods[] = { {"closePath", Path2DV8Internal::closePathMethodCallback, 0, 0}, {"moveTo", Path2DV8Internal::moveToMethodCallback, 0, 2}, {"lineTo", Path2DV8Internal::lineToMethodCallback, 0, 2}, {"quadraticCurveTo", Path2DV8Internal::quadraticCurveToMethodCallback, 0, 4}, {"bezierCurveTo", Path2DV8Internal::bezierCurveToMethodCallback, 0, 6}, {"arcTo", Path2DV8Internal::arcToMethodCallback, 0, 5}, {"rect", Path2DV8Internal::rectMethodCallback, 0, 4}, {"arc", Path2DV8Internal::arcMethodCallback, 0, 5}, {"ellipse", Path2DV8Internal::ellipseMethodCallback, 0, 7}, }; void V8Path2D::constructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "DOMConstructor"); if (!info.IsConstructCall()) { throwTypeError(ExceptionMessages::constructorNotCallableAsFunction("Path2D"), info.GetIsolate()); return; } if (ConstructorMode::current(info.GetIsolate()) == ConstructorMode::WrapExistingObject) { v8SetReturnValue(info, info.Holder()); return; } Path2DV8Internal::constructor(info); } static void configureV8Path2DTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) { functionTemplate->ReadOnlyPrototype(); v8::Local<v8::Signature> defaultSignature; if (!RuntimeEnabledFeatures::path2DEnabled()) defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "", v8::Local<v8::FunctionTemplate>(), V8Path2D::internalFieldCount, 0, 0, 0, 0, 0, 0, isolate); else defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "Path2D", v8::Local<v8::FunctionTemplate>(), V8Path2D::internalFieldCount, 0, 0, 0, 0, V8Path2DMethods, WTF_ARRAY_LENGTH(V8Path2DMethods), isolate); functionTemplate->SetCallHandler(V8Path2D::constructorCallback); functionTemplate->SetLength(0); v8::Local<v8::ObjectTemplate> instanceTemplate ALLOW_UNUSED = functionTemplate->InstanceTemplate(); v8::Local<v8::ObjectTemplate> prototypeTemplate ALLOW_UNUSED = functionTemplate->PrototypeTemplate(); if (RuntimeEnabledFeatures::experimentalCanvasFeaturesEnabled()) { prototypeTemplate->Set(v8AtomicString(isolate, "addPath"), v8::FunctionTemplate::New(isolate, Path2DV8Internal::addPathMethodCallback, v8Undefined(), defaultSignature, 1)); } // Custom toString template functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate()); } v8::Handle<v8::FunctionTemplate> V8Path2D::domTemplate(v8::Isolate* isolate) { return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), configureV8Path2DTemplate); } bool V8Path2D::hasInstance(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value); } v8::Handle<v8::Object> V8Path2D::findInstanceInPrototypeChain(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value); } Path2D* V8Path2D::toNativeWithTypeCheck(v8::Isolate* isolate, v8::Handle<v8::Value> value) { return hasInstance(value, isolate) ? fromInternalPointer(v8::Handle<v8::Object>::Cast(value)->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex)) : 0; } v8::Handle<v8::Object> wrap(Path2D* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { ASSERT(impl); ASSERT(!DOMDataStore::containsWrapper<V8Path2D>(impl, isolate)); return V8Path2D::createWrapper(impl, creationContext, isolate); } v8::Handle<v8::Object> V8Path2D::createWrapper(PassRefPtr<Path2D> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { ASSERT(impl); ASSERT(!DOMDataStore::containsWrapper<V8Path2D>(impl.get(), isolate)); if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) { const WrapperTypeInfo* actualInfo = ScriptWrappable::fromObject(impl.get())->typeInfo(); // Might be a XXXConstructor::wrapperTypeInfo instead of an XXX::wrapperTypeInfo. These will both have // the same object de-ref functions, though, so use that as the basis of the check. RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction); } v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate); if (UNLIKELY(wrapper.IsEmpty())) return wrapper; installPerContextEnabledProperties(wrapper, impl.get(), isolate); V8DOMWrapper::associateObjectWithWrapper<V8Path2D>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent); return wrapper; } void V8Path2D::derefObject(void* object) { fromInternalPointer(object)->deref(); } template<> v8::Handle<v8::Value> toV8NoInline(Path2D* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { return toV8(impl, creationContext, isolate); } } // namespace WebCore
38.823748
221
0.704721
jingcao80
efaa95e67d306944eeea043d8368c7cea94e20aa
5,430
cc
C++
chrome/browser/media/router/discovery/media_sink_service_base_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/media/router/discovery/media_sink_service_base_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/media/router/discovery/media_sink_service_base_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/media/router/discovery/media_sink_service_base.h" #include "base/test/mock_callback.h" #include "base/timer/mock_timer.h" #include "chrome/browser/media/router/test_helper.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::_; using ::testing::Return; namespace { media_router::DialSinkExtraData CreateDialSinkExtraData( const std::string& model_name, const std::string& ip_address, const std::string& app_url) { media_router::DialSinkExtraData dial_extra_data; EXPECT_TRUE(dial_extra_data.ip_address.AssignFromIPLiteral(ip_address)); dial_extra_data.model_name = model_name; dial_extra_data.app_url = GURL(app_url); return dial_extra_data; } std::vector<media_router::MediaSinkInternal> CreateDialMediaSinks() { media_router::MediaSink sink1("sink1", "sink_name_1", media_router::SinkIconType::CAST); media_router::DialSinkExtraData extra_data1 = CreateDialSinkExtraData( "model_name1", "192.168.1.1", "https://example1.com"); media_router::MediaSink sink2("sink2", "sink_name_2", media_router::SinkIconType::CAST); media_router::DialSinkExtraData extra_data2 = CreateDialSinkExtraData( "model_name2", "192.168.1.2", "https://example2.com"); std::vector<media_router::MediaSinkInternal> sinks; sinks.push_back(media_router::MediaSinkInternal(sink1, extra_data1)); sinks.push_back(media_router::MediaSinkInternal(sink2, extra_data2)); return sinks; } } // namespace namespace media_router { class TestMediaSinkServiceBase : public MediaSinkServiceBase { public: explicit TestMediaSinkServiceBase(const OnSinksDiscoveredCallback& callback) : MediaSinkServiceBase(callback) {} void Start() override {} void Stop() override {} }; class MediaSinkServiceBaseTest : public ::testing::Test { public: MediaSinkServiceBaseTest() : // thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), media_sink_service_( new TestMediaSinkServiceBase(mock_sink_discovered_cb_.Get())) {} void SetUp() override { mock_timer_ = new base::MockTimer(true /*retain_user_task*/, false /*is_repeating*/); media_sink_service_->SetTimerForTest(base::WrapUnique(mock_timer_)); } void TestFetchCompleted(const std::vector<MediaSinkInternal>& old_sinks, const std::vector<MediaSinkInternal>& new_sinks) { media_sink_service_->mrp_sinks_ = std::set<MediaSinkInternal>(old_sinks.begin(), old_sinks.end()); media_sink_service_->current_sinks_ = std::set<MediaSinkInternal>(new_sinks.begin(), new_sinks.end()); EXPECT_CALL(mock_sink_discovered_cb_, Run(new_sinks)); media_sink_service_->OnFetchCompleted(); } protected: base::MockCallback<MediaSinkService::OnSinksDiscoveredCallback> mock_sink_discovered_cb_; base::MockTimer* mock_timer_; std::unique_ptr<TestMediaSinkServiceBase> media_sink_service_; DISALLOW_COPY_AND_ASSIGN(MediaSinkServiceBaseTest); }; TEST_F(MediaSinkServiceBaseTest, TestFetchCompleted_SameSink) { std::vector<MediaSinkInternal> old_sinks; std::vector<MediaSinkInternal> new_sinks = CreateDialMediaSinks(); TestFetchCompleted(old_sinks, new_sinks); // Same sink EXPECT_CALL(mock_sink_discovered_cb_, Run(new_sinks)).Times(0); media_sink_service_->OnFetchCompleted(); } TEST_F(MediaSinkServiceBaseTest, TestFetchCompleted_OneNewSink) { std::vector<MediaSinkInternal> old_sinks = CreateDialMediaSinks(); std::vector<MediaSinkInternal> new_sinks = CreateDialMediaSinks(); MediaSink sink3("sink3", "sink_name_3", SinkIconType::CAST); DialSinkExtraData extra_data3 = CreateDialSinkExtraData( "model_name3", "192.168.1.3", "https://example3.com"); new_sinks.push_back(MediaSinkInternal(sink3, extra_data3)); TestFetchCompleted(old_sinks, new_sinks); } TEST_F(MediaSinkServiceBaseTest, TestFetchCompleted_RemovedOneSink) { std::vector<MediaSinkInternal> old_sinks = CreateDialMediaSinks(); std::vector<MediaSinkInternal> new_sinks = CreateDialMediaSinks(); new_sinks.erase(new_sinks.begin()); TestFetchCompleted(old_sinks, new_sinks); } TEST_F(MediaSinkServiceBaseTest, TestFetchCompleted_UpdatedOneSink) { std::vector<MediaSinkInternal> old_sinks = CreateDialMediaSinks(); std::vector<MediaSinkInternal> new_sinks = CreateDialMediaSinks(); new_sinks[0].set_name("sink_name_4"); TestFetchCompleted(old_sinks, new_sinks); } TEST_F(MediaSinkServiceBaseTest, TestFetchCompleted_Mixed) { std::vector<MediaSinkInternal> old_sinks = CreateDialMediaSinks(); MediaSink sink1("sink1", "sink_name_1", SinkIconType::CAST); DialSinkExtraData extra_data2 = CreateDialSinkExtraData( "model_name2", "192.168.1.2", "https://example2.com"); MediaSink sink3("sink3", "sink_name_3", SinkIconType::CAST); DialSinkExtraData extra_data3 = CreateDialSinkExtraData( "model_name3", "192.168.1.3", "https://example3.com"); std::vector<MediaSinkInternal> new_sinks; new_sinks.push_back(MediaSinkInternal(sink1, extra_data2)); new_sinks.push_back(MediaSinkInternal(sink3, extra_data3)); TestFetchCompleted(old_sinks, new_sinks); } } // namespace media_router
37.708333
79
0.759484
metux
efac67313dd9bd9f69caae66d56b1ffaf67e9911
1,591
hpp
C++
internal/o80_internal/controllers_manager.hpp
luator/o80
65fe75bc6d375db0e4a2fe075c097a54dde7b571
[ "BSD-3-Clause" ]
null
null
null
internal/o80_internal/controllers_manager.hpp
luator/o80
65fe75bc6d375db0e4a2fe075c097a54dde7b571
[ "BSD-3-Clause" ]
null
null
null
internal/o80_internal/controllers_manager.hpp
luator/o80
65fe75bc6d375db0e4a2fe075c097a54dde7b571
[ "BSD-3-Clause" ]
null
null
null
// Copyright (C) 2019 Max Planck Gesellschaft // Author : Vincent Berenz #pragma once #include <memory> #include "command.hpp" #include "controller.hpp" #include "o80/states.hpp" #include "time_series/multiprocess_time_series.hpp" namespace o80 { template <int NB_ACTUATORS, int QUEUE_SIZE, class STATE> class ControllersManager { public: typedef std::array<Controller<STATE>, NB_ACTUATORS> Controllers; typedef time_series::MultiprocessTimeSeries<Command<STATE>> CommandsTimeSeries; typedef time_series::MultiprocessTimeSeries<int> CompletedCommandsTimeSeries; public: ControllersManager(std::string segment_id); void process_commands(long int current_iteration); STATE get_desired_state(int dof, long int current_iteration, const TimePoint &time_now, const STATE &current_state); int get_current_command_id(int dof) const; void get_newly_executed_commands(std::queue<int> &get); bool reapplied_desired_states() const; CommandsTimeSeries &get_commands_time_series(); CompletedCommandsTimeSeries &get_completed_commands_time_series(); private: std::string segment_id_; CommandsTimeSeries commands_; long int pulse_id_; time_series::Index commands_index_; CompletedCommandsTimeSeries completed_commands_; Controllers controllers_; States<NB_ACTUATORS, STATE> previous_desired_states_; std::array<bool, NB_ACTUATORS> initialized_; long int relative_iteration_; }; } #include "controllers_manager.hxx"
27.912281
70
0.733501
luator
eface07d49cd2d31155cbaf2a0de6163d32bde90
5,470
cc
C++
nacl/net/rtp/rtp_sender.cc
maxsong11/nacld
c4802cc7d9bda03487bde566a3003e8bc0f574d3
[ "BSD-3-Clause" ]
9
2015-12-23T21:18:28.000Z
2018-11-25T10:10:12.000Z
nacl/net/rtp/rtp_sender.cc
maxsong11/nacld
c4802cc7d9bda03487bde566a3003e8bc0f574d3
[ "BSD-3-Clause" ]
1
2016-01-08T20:56:21.000Z
2016-01-08T20:56:21.000Z
nacl/net/rtp/rtp_sender.cc
maxsong11/nacld
c4802cc7d9bda03487bde566a3003e8bc0f574d3
[ "BSD-3-Clause" ]
6
2015-12-04T18:23:49.000Z
2018-11-06T03:52:58.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Copyright 2015 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/rtp/rtp_sender.h" #include "base/big_endian.h" #include "base/logger.h" #include "base/ptr_utils.h" #include "base/rand_util.h" #include "sharer_defines.h" namespace sharer { namespace { // If there is only one reference to the packet then copy the // reference and return. // Otherwise return a deep copy of the packet. PacketRef FastCopyPacket(const PacketRef& packet) { if (packet.unique()) return packet; return std::make_shared<Packet>(*packet); } } // namespace RtpSender::RtpSender(PacedSender* const transport) : transport_(transport) { // Randomly set sequence number start value. config_.sequence_number = base::RandInt(0, 65535); } RtpSender::~RtpSender() {} bool RtpSender::Initialize(const SharerTransportRtpConfig& config) { config_.ssrc = config.ssrc; config_.payload_type = config.rtp_payload_type; packetizer_ = make_unique<RtpPacketizer>(transport_, &storage_, config_); return true; } void RtpSender::SendFrame(const EncodedFrame& frame) { PP_DCHECK(packetizer_); packetizer_->SendFrameAsPackets(frame); if (storage_.GetNumberOfStoredFrames() > kMaxUnackedFrames) { // TODO: Change to LOG_IF DERR() << "Possible bug: Frames are not being actively released from storage."; } } void RtpSender::ResendPackets( const std::string& addr, const MissingFramesAndPacketsMap& missing_frames_and_packets, bool cancel_rtx_if_not_in_list, const DedupInfo& dedup_info) { // Iterate over all frames in the list. for (MissingFramesAndPacketsMap::const_iterator it = missing_frames_and_packets.begin(); it != missing_frames_and_packets.end(); ++it) { SendPacketVector packets_to_resend; uint32_t frame_id = it->first; // Set of packets that the receiver wants us to re-send. // If empty, we need to re-send all packets for this frame. const PacketIdSet& missing_packet_set = it->second; bool resend_all = missing_packet_set.find(kRtcpSharerAllPacketsLost) != missing_packet_set.end(); bool resend_last = missing_packet_set.find(kRtcpSharerLastPacket) != missing_packet_set.end(); const SendPacketVector* stored_packets = storage_.GetFrame32(frame_id); if (!stored_packets) { DERR() << "Can't resend " << missing_packet_set.size() << " packets for frame:" << frame_id; continue; } for (SendPacketVector::const_iterator it = stored_packets->begin(); it != stored_packets->end(); ++it) { const PacketKey& packet_key = it->first; const uint16_t packet_id = packet_key.second.second; // Should we resend the packet? bool resend = resend_all; // Should we resend it because it's in the missing_packet_set? if (!resend && missing_packet_set.find(packet_id) != missing_packet_set.end()) { resend = true; } // If we were asked to resend the last packet, check if it's the // last packet. if (!resend && resend_last && (it + 1) == stored_packets->end()) { resend = true; } if (resend) { // Resend packet to the network. DINF() << "Resend " << static_cast<int>(frame_id) << ":" << packet_id << ", dest: " << addr; // Set a unique incremental sequence number for every packet. PacketRef packet_copy = FastCopyPacket(it->second); UpdateSequenceNumber(packet_copy); packets_to_resend.push_back(std::make_pair(packet_key, packet_copy)); } else if (cancel_rtx_if_not_in_list) { transport_->CancelSendingPacket(addr, it->first); } } transport_->ResendPackets(addr, packets_to_resend, dedup_info); } } void RtpSender::ResendFrameForKickstart(uint32_t frame_id, base::TimeDelta dedupe_window) { // Send the last packet of the encoded frame to kick start // retransmission. This gives enough information to the receiver what // packets and frames are missing. MissingFramesAndPacketsMap missing_frames_and_packets; PacketIdSet missing; missing.insert(kRtcpSharerLastPacket); missing_frames_and_packets.insert(std::make_pair(frame_id, missing)); // Sending this extra packet is to kick-start the session. There is // no need to optimize re-transmission for this case. DedupInfo dedup_info; dedup_info.resend_interval = dedupe_window; // ResendPackets(missing_frames_and_packets, false, dedup_info); } void RtpSender::UpdateSequenceNumber(PacketRef packet) { // TODO(miu): This is an abstraction violation. This needs to be a part of // the overall packet (de)serialization consolidation. static const int kByteOffsetToSequenceNumber = 2; BigEndianWriter big_endian_writer( reinterpret_cast<char*>((packet->data()) + kByteOffsetToSequenceNumber), sizeof(uint16_t)); big_endian_writer.WriteU16(packetizer_->NextSequenceNumber()); } int64_t RtpSender::GetLastByteSentForFrame(uint32_t frame_id) { const SendPacketVector* stored_packets = storage_.GetFrame32(frame_id); if (!stored_packets) return 0; PacketKey last_packet_key = stored_packets->rbegin()->first; return transport_->GetLastByteSentForPacket(last_packet_key); } } // namespace sharer
36.711409
80
0.706399
maxsong11
efae40771253fa3bfb27b1ee80c55f32c9e089be
3,140
cpp
C++
minesweeper_v1/Instructions.cpp
sangpham2710/CS161-Project
7051cc17bc64bdcb128884ef02ec70e1552c982e
[ "MIT" ]
6
2021-12-28T08:07:16.000Z
2022-03-13T06:17:45.000Z
minesweeper_v1/Instructions.cpp
sangpham2710/CS161-Project
7051cc17bc64bdcb128884ef02ec70e1552c982e
[ "MIT" ]
null
null
null
minesweeper_v1/Instructions.cpp
sangpham2710/CS161-Project
7051cc17bc64bdcb128884ef02ec70e1552c982e
[ "MIT" ]
1
2021-12-24T07:19:16.000Z
2021-12-24T07:19:16.000Z
#include "instructions.h" #include <algorithm> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include "cmanip.h" #include "game_model.h" #include "global.h" #include "main_utils.h" #include "scene_manager.h" #include "windows.h" const long long MAX_TIME = (long long)1e18; int PADDING_INSTRUCTIONS_X, PADDING_INSTRUCTIONS_Y; // 3 che do // 0 0 0 0 0 0 0 0 0 0 // 0 0 0 0 0 0 0 0 0 0 // 0 0 0 0 0 0 0 0 0 0 const std::vector<std::string> instructions = { R"([WASD]/[Arrow keys])", "Move Cursor", "[J]/[Enter]", "Select | Open A Cell", "[K]", "Open Neighboring Cells", "[L]", "Flag A Cell", "[O]", "Save Game", "[R]", "Replay Game", "[Y]", "Yes", "[N]", "No", R"([Escape])", R"(Quit Game | Back to Menu)", }; int instructionsWidth = strlen(R"( [Escape]: Quit Game | Back to Menu)"); int instructionsHeight = instructions.size() / 2; std::vector<std::string> getInstructionHeaderText() { return { R"( _ _ ___ __ __ _____ ___ ___ _ _ __ __)", R"(| || | / _ \\ \ / / |_ _|/ _ \ | _ \| | /_\\ \ / /)", R"(| __ || (_) |\ \/\/ / | | | (_) | | _/| |__ / _ \\ V / )", R"(|_||_| \___/ \_/\_/ |_| \___/ |_| |____|/_/ \_\|_| )", }; } int getInstructionsPosition() { return PADDING_INSTRUCTIONS_Y + 1; } void displayInstructionsHeaderAndFooter() { std::vector<std::string> headerText = getInstructionHeaderText(); const int spacing = 1; for (int i = 0; i < headerText.size(); i++) printCenteredText(headerText[i], 3 + i); printCenteredText(R"([J] Back to Menu)", getWindowHeight() - 2); } int Instructions() { setupInstructionsDisplay(); displayInstructions(); while (true) { int action = getUserAction(); if (action == MOUSE1 || action == ESCAPE) return WELCOME; } } void displayInstructions() { resetConsoleScreen(); int cellWidth = instructions[0].size(); displayInstructionsHeaderAndFooter(); for (int i = 0; i < instructions.size(); i++) { setConsoleCursorPosition( PADDING_INSTRUCTIONS_X + (cellWidth - instructions[i].size()) / 2 - 5, PADDING_INSTRUCTIONS_Y + i / 2 + 2); std::cout << instructions[i]; setConsoleCursorPosition(PADDING_INSTRUCTIONS_X + cellWidth - 2, PADDING_INSTRUCTIONS_Y + i / 2 + 2); std::cout << " : " << instructions[i + 1]; // printCenteredText(std::string((cellWidth - instruction[i].size()) / 2, ' // ') + instruction[i] + std::string((cellWidth - instruction[i].size()) / // 2, ' ') + std::string(instructionWidth - cellWidth, ' '), // PADDING_INSTRUCTION_Y + i / 2 + 2); // printCenteredText(std::string(instruction[i].size(), ' ') + instruction[i // + 1] + std::string(instructionWidth - instruction[i].size() - // instruction[i + 1].size(), ' '), PADDING_INSTRUCTION_Y + i / 2 + 2); i++; } } void setupInstructionsDisplay() { PADDING_INSTRUCTIONS_X = (getWindowWidth() - instructionsWidth) / 2; PADDING_INSTRUCTIONS_Y = (getWindowHeight() - instructionsHeight) / 2; }
28.545455
80
0.58758
sangpham2710
efafcec13c75a40f7bfe2a3549a569f79f732878
83,097
cc
C++
protobufs/c_peer2peer_netmessages.pb.cc
devilesk/dota-replay-parser
e83b96ee513a7193e6703615df4f676e27b1b8a0
[ "0BSD" ]
2
2017-02-03T16:57:17.000Z
2020-10-28T21:13:12.000Z
protobufs/c_peer2peer_netmessages.pb.cc
invokr/dota-replay-parser
6260aa834fb47f0f1a8c713f4edada6baeb9dcfa
[ "0BSD" ]
1
2017-02-03T22:44:17.000Z
2017-02-04T08:58:13.000Z
protobufs/c_peer2peer_netmessages.pb.cc
invokr/dota-replay-parser
6260aa834fb47f0f1a8c713f4edada6baeb9dcfa
[ "0BSD" ]
2
2017-02-03T17:51:57.000Z
2021-05-22T02:40:00.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: c_peer2peer_netmessages.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "c_peer2peer_netmessages.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace { const ::google::protobuf::Descriptor* CP2P_TextMessage_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* CP2P_TextMessage_reflection_ = NULL; const ::google::protobuf::Descriptor* CSteam_Voice_Encoding_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* CSteam_Voice_Encoding_reflection_ = NULL; const ::google::protobuf::Descriptor* CP2P_Voice_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* CP2P_Voice_reflection_ = NULL; const ::google::protobuf::EnumDescriptor* CP2P_Voice_Handler_Flags_descriptor_ = NULL; const ::google::protobuf::Descriptor* CP2P_Ping_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* CP2P_Ping_reflection_ = NULL; const ::google::protobuf::Descriptor* CP2P_VRAvatarPosition_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* CP2P_VRAvatarPosition_reflection_ = NULL; const ::google::protobuf::Descriptor* CP2P_VRAvatarPosition_COrientation_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* CP2P_VRAvatarPosition_COrientation_reflection_ = NULL; const ::google::protobuf::Descriptor* CP2P_WatchSynchronization_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* CP2P_WatchSynchronization_reflection_ = NULL; const ::google::protobuf::EnumDescriptor* P2P_Messages_descriptor_ = NULL; } // namespace void protobuf_AssignDesc_c_5fpeer2peer_5fnetmessages_2eproto() { protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "c_peer2peer_netmessages.proto"); GOOGLE_CHECK(file != NULL); CP2P_TextMessage_descriptor_ = file->message_type(0); static const int CP2P_TextMessage_offsets_[1] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_TextMessage, text_), }; CP2P_TextMessage_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( CP2P_TextMessage_descriptor_, CP2P_TextMessage::default_instance_, CP2P_TextMessage_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_TextMessage, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_TextMessage, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(CP2P_TextMessage)); CSteam_Voice_Encoding_descriptor_ = file->message_type(1); static const int CSteam_Voice_Encoding_offsets_[1] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CSteam_Voice_Encoding, voice_data_), }; CSteam_Voice_Encoding_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( CSteam_Voice_Encoding_descriptor_, CSteam_Voice_Encoding::default_instance_, CSteam_Voice_Encoding_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CSteam_Voice_Encoding, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CSteam_Voice_Encoding, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(CSteam_Voice_Encoding)); CP2P_Voice_descriptor_ = file->message_type(2); static const int CP2P_Voice_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_Voice, audio_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_Voice, broadcast_group_), }; CP2P_Voice_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( CP2P_Voice_descriptor_, CP2P_Voice::default_instance_, CP2P_Voice_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_Voice, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_Voice, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(CP2P_Voice)); CP2P_Voice_Handler_Flags_descriptor_ = CP2P_Voice_descriptor_->enum_type(0); CP2P_Ping_descriptor_ = file->message_type(3); static const int CP2P_Ping_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_Ping, send_time_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_Ping, is_reply_), }; CP2P_Ping_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( CP2P_Ping_descriptor_, CP2P_Ping::default_instance_, CP2P_Ping_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_Ping, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_Ping, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(CP2P_Ping)); CP2P_VRAvatarPosition_descriptor_ = file->message_type(4); static const int CP2P_VRAvatarPosition_offsets_[4] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition, body_parts_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition, hat_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition, scene_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition, world_scale_), }; CP2P_VRAvatarPosition_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( CP2P_VRAvatarPosition_descriptor_, CP2P_VRAvatarPosition::default_instance_, CP2P_VRAvatarPosition_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(CP2P_VRAvatarPosition)); CP2P_VRAvatarPosition_COrientation_descriptor_ = CP2P_VRAvatarPosition_descriptor_->nested_type(0); static const int CP2P_VRAvatarPosition_COrientation_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition_COrientation, pos_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition_COrientation, ang_), }; CP2P_VRAvatarPosition_COrientation_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( CP2P_VRAvatarPosition_COrientation_descriptor_, CP2P_VRAvatarPosition_COrientation::default_instance_, CP2P_VRAvatarPosition_COrientation_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition_COrientation, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition_COrientation, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(CP2P_VRAvatarPosition_COrientation)); CP2P_WatchSynchronization_descriptor_ = file->message_type(5); static const int CP2P_WatchSynchronization_offsets_[8] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, demo_tick_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, paused_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, tv_listen_voice_indices_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, dota_spectator_mode_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, dota_spectator_watching_broadcaster_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, dota_spectator_hero_index_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, dota_spectator_autospeed_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, dota_replay_speed_), }; CP2P_WatchSynchronization_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( CP2P_WatchSynchronization_descriptor_, CP2P_WatchSynchronization::default_instance_, CP2P_WatchSynchronization_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(CP2P_WatchSynchronization)); P2P_Messages_descriptor_ = file->enum_type(0); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_c_5fpeer2peer_5fnetmessages_2eproto); } void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( CP2P_TextMessage_descriptor_, &CP2P_TextMessage::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( CSteam_Voice_Encoding_descriptor_, &CSteam_Voice_Encoding::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( CP2P_Voice_descriptor_, &CP2P_Voice::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( CP2P_Ping_descriptor_, &CP2P_Ping::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( CP2P_VRAvatarPosition_descriptor_, &CP2P_VRAvatarPosition::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( CP2P_VRAvatarPosition_COrientation_descriptor_, &CP2P_VRAvatarPosition_COrientation::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( CP2P_WatchSynchronization_descriptor_, &CP2P_WatchSynchronization::default_instance()); } } // namespace void protobuf_ShutdownFile_c_5fpeer2peer_5fnetmessages_2eproto() { delete CP2P_TextMessage::default_instance_; delete CP2P_TextMessage_reflection_; delete CSteam_Voice_Encoding::default_instance_; delete CSteam_Voice_Encoding_reflection_; delete CP2P_Voice::default_instance_; delete CP2P_Voice_reflection_; delete CP2P_Ping::default_instance_; delete CP2P_Ping_reflection_; delete CP2P_VRAvatarPosition::default_instance_; delete CP2P_VRAvatarPosition_reflection_; delete CP2P_VRAvatarPosition_COrientation::default_instance_; delete CP2P_VRAvatarPosition_COrientation_reflection_; delete CP2P_WatchSynchronization::default_instance_; delete CP2P_WatchSynchronization_reflection_; } void protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::protobuf_AddDesc_netmessages_2eproto(); ::protobuf_AddDesc_networkbasetypes_2eproto(); ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\035c_peer2peer_netmessages.proto\032\021netmess" "ages.proto\032\026networkbasetypes.proto\" \n\020CP" "2P_TextMessage\022\014\n\004text\030\001 \001(\014\"+\n\025CSteam_V" "oice_Encoding\022\022\n\nvoice_data\030\001 \001(\014\"h\n\nCP2" "P_Voice\022\036\n\005audio\030\001 \001(\0132\017.CMsgVoiceAudio\022" "\027\n\017broadcast_group\030\002 \001(\r\"!\n\rHandler_Flag" "s\022\020\n\014Played_Audio\020\001\"0\n\tCP2P_Ping\022\021\n\tsend" "_time\030\001 \002(\004\022\020\n\010is_reply\030\002 \002(\010\"\313\001\n\025CP2P_V" "RAvatarPosition\0227\n\nbody_parts\030\001 \003(\0132#.CP" "2P_VRAvatarPosition.COrientation\022\016\n\006hat_" "id\030\002 \001(\005\022\020\n\010scene_id\030\003 \001(\005\022\023\n\013world_scal" "e\030\004 \001(\005\032B\n\014COrientation\022\030\n\003pos\030\001 \001(\0132\013.C" "MsgVector\022\030\n\003ang\030\002 \001(\0132\013.CMsgQAngle\"\211\002\n\031" "CP2P_WatchSynchronization\022\021\n\tdemo_tick\030\001" " \001(\005\022\016\n\006paused\030\002 \001(\010\022\037\n\027tv_listen_voice_" "indices\030\003 \001(\005\022\033\n\023dota_spectator_mode\030\004 \001" "(\005\022+\n#dota_spectator_watching_broadcaste" "r\030\005 \001(\005\022!\n\031dota_spectator_hero_index\030\006 \001" "(\005\022 \n\030dota_spectator_autospeed\030\007 \001(\005\022\031\n\021" "dota_replay_speed\030\010 \001(\005*}\n\014P2P_Messages\022" "\024\n\017p2p_TextMessage\020\200\002\022\016\n\tp2p_Voice\020\201\002\022\r\n" "\010p2p_Ping\020\202\002\022\031\n\024p2p_VRAvatarPosition\020\203\002\022" "\035\n\030p2p_WatchSynchronization\020\204\002B\003\200\001\000", 915); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "c_peer2peer_netmessages.proto", &protobuf_RegisterTypes); CP2P_TextMessage::default_instance_ = new CP2P_TextMessage(); CSteam_Voice_Encoding::default_instance_ = new CSteam_Voice_Encoding(); CP2P_Voice::default_instance_ = new CP2P_Voice(); CP2P_Ping::default_instance_ = new CP2P_Ping(); CP2P_VRAvatarPosition::default_instance_ = new CP2P_VRAvatarPosition(); CP2P_VRAvatarPosition_COrientation::default_instance_ = new CP2P_VRAvatarPosition_COrientation(); CP2P_WatchSynchronization::default_instance_ = new CP2P_WatchSynchronization(); CP2P_TextMessage::default_instance_->InitAsDefaultInstance(); CSteam_Voice_Encoding::default_instance_->InitAsDefaultInstance(); CP2P_Voice::default_instance_->InitAsDefaultInstance(); CP2P_Ping::default_instance_->InitAsDefaultInstance(); CP2P_VRAvatarPosition::default_instance_->InitAsDefaultInstance(); CP2P_VRAvatarPosition_COrientation::default_instance_->InitAsDefaultInstance(); CP2P_WatchSynchronization::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_c_5fpeer2peer_5fnetmessages_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_c_5fpeer2peer_5fnetmessages_2eproto { StaticDescriptorInitializer_c_5fpeer2peer_5fnetmessages_2eproto() { protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto(); } } static_descriptor_initializer_c_5fpeer2peer_5fnetmessages_2eproto_; const ::google::protobuf::EnumDescriptor* P2P_Messages_descriptor() { protobuf_AssignDescriptorsOnce(); return P2P_Messages_descriptor_; } bool P2P_Messages_IsValid(int value) { switch(value) { case 256: case 257: case 258: case 259: case 260: return true; default: return false; } } // =================================================================== #ifndef _MSC_VER const int CP2P_TextMessage::kTextFieldNumber; #endif // !_MSC_VER CP2P_TextMessage::CP2P_TextMessage() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:CP2P_TextMessage) } void CP2P_TextMessage::InitAsDefaultInstance() { } CP2P_TextMessage::CP2P_TextMessage(const CP2P_TextMessage& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:CP2P_TextMessage) } void CP2P_TextMessage::SharedCtor() { ::google::protobuf::internal::GetEmptyString(); _cached_size_ = 0; text_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } CP2P_TextMessage::~CP2P_TextMessage() { // @@protoc_insertion_point(destructor:CP2P_TextMessage) SharedDtor(); } void CP2P_TextMessage::SharedDtor() { if (text_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete text_; } if (this != default_instance_) { } } void CP2P_TextMessage::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* CP2P_TextMessage::descriptor() { protobuf_AssignDescriptorsOnce(); return CP2P_TextMessage_descriptor_; } const CP2P_TextMessage& CP2P_TextMessage::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto(); return *default_instance_; } CP2P_TextMessage* CP2P_TextMessage::default_instance_ = NULL; CP2P_TextMessage* CP2P_TextMessage::New() const { return new CP2P_TextMessage; } void CP2P_TextMessage::Clear() { if (has_text()) { if (text_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { text_->clear(); } } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool CP2P_TextMessage::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:CP2P_TextMessage) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional bytes text = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_text())); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:CP2P_TextMessage) return true; failure: // @@protoc_insertion_point(parse_failure:CP2P_TextMessage) return false; #undef DO_ } void CP2P_TextMessage::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:CP2P_TextMessage) // optional bytes text = 1; if (has_text()) { ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( 1, this->text(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:CP2P_TextMessage) } ::google::protobuf::uint8* CP2P_TextMessage::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:CP2P_TextMessage) // optional bytes text = 1; if (has_text()) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 1, this->text(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:CP2P_TextMessage) return target; } int CP2P_TextMessage::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // optional bytes text = 1; if (has_text()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->text()); } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void CP2P_TextMessage::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const CP2P_TextMessage* source = ::google::protobuf::internal::dynamic_cast_if_available<const CP2P_TextMessage*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void CP2P_TextMessage::MergeFrom(const CP2P_TextMessage& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_text()) { set_text(from.text()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void CP2P_TextMessage::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void CP2P_TextMessage::CopyFrom(const CP2P_TextMessage& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool CP2P_TextMessage::IsInitialized() const { return true; } void CP2P_TextMessage::Swap(CP2P_TextMessage* other) { if (other != this) { std::swap(text_, other->text_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata CP2P_TextMessage::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = CP2P_TextMessage_descriptor_; metadata.reflection = CP2P_TextMessage_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int CSteam_Voice_Encoding::kVoiceDataFieldNumber; #endif // !_MSC_VER CSteam_Voice_Encoding::CSteam_Voice_Encoding() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:CSteam_Voice_Encoding) } void CSteam_Voice_Encoding::InitAsDefaultInstance() { } CSteam_Voice_Encoding::CSteam_Voice_Encoding(const CSteam_Voice_Encoding& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:CSteam_Voice_Encoding) } void CSteam_Voice_Encoding::SharedCtor() { ::google::protobuf::internal::GetEmptyString(); _cached_size_ = 0; voice_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } CSteam_Voice_Encoding::~CSteam_Voice_Encoding() { // @@protoc_insertion_point(destructor:CSteam_Voice_Encoding) SharedDtor(); } void CSteam_Voice_Encoding::SharedDtor() { if (voice_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete voice_data_; } if (this != default_instance_) { } } void CSteam_Voice_Encoding::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* CSteam_Voice_Encoding::descriptor() { protobuf_AssignDescriptorsOnce(); return CSteam_Voice_Encoding_descriptor_; } const CSteam_Voice_Encoding& CSteam_Voice_Encoding::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto(); return *default_instance_; } CSteam_Voice_Encoding* CSteam_Voice_Encoding::default_instance_ = NULL; CSteam_Voice_Encoding* CSteam_Voice_Encoding::New() const { return new CSteam_Voice_Encoding; } void CSteam_Voice_Encoding::Clear() { if (has_voice_data()) { if (voice_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { voice_data_->clear(); } } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool CSteam_Voice_Encoding::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:CSteam_Voice_Encoding) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional bytes voice_data = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_voice_data())); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:CSteam_Voice_Encoding) return true; failure: // @@protoc_insertion_point(parse_failure:CSteam_Voice_Encoding) return false; #undef DO_ } void CSteam_Voice_Encoding::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:CSteam_Voice_Encoding) // optional bytes voice_data = 1; if (has_voice_data()) { ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( 1, this->voice_data(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:CSteam_Voice_Encoding) } ::google::protobuf::uint8* CSteam_Voice_Encoding::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:CSteam_Voice_Encoding) // optional bytes voice_data = 1; if (has_voice_data()) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 1, this->voice_data(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:CSteam_Voice_Encoding) return target; } int CSteam_Voice_Encoding::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // optional bytes voice_data = 1; if (has_voice_data()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->voice_data()); } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void CSteam_Voice_Encoding::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const CSteam_Voice_Encoding* source = ::google::protobuf::internal::dynamic_cast_if_available<const CSteam_Voice_Encoding*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void CSteam_Voice_Encoding::MergeFrom(const CSteam_Voice_Encoding& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_voice_data()) { set_voice_data(from.voice_data()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void CSteam_Voice_Encoding::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void CSteam_Voice_Encoding::CopyFrom(const CSteam_Voice_Encoding& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool CSteam_Voice_Encoding::IsInitialized() const { return true; } void CSteam_Voice_Encoding::Swap(CSteam_Voice_Encoding* other) { if (other != this) { std::swap(voice_data_, other->voice_data_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata CSteam_Voice_Encoding::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = CSteam_Voice_Encoding_descriptor_; metadata.reflection = CSteam_Voice_Encoding_reflection_; return metadata; } // =================================================================== const ::google::protobuf::EnumDescriptor* CP2P_Voice_Handler_Flags_descriptor() { protobuf_AssignDescriptorsOnce(); return CP2P_Voice_Handler_Flags_descriptor_; } bool CP2P_Voice_Handler_Flags_IsValid(int value) { switch(value) { case 1: return true; default: return false; } } #ifndef _MSC_VER const CP2P_Voice_Handler_Flags CP2P_Voice::Played_Audio; const CP2P_Voice_Handler_Flags CP2P_Voice::Handler_Flags_MIN; const CP2P_Voice_Handler_Flags CP2P_Voice::Handler_Flags_MAX; const int CP2P_Voice::Handler_Flags_ARRAYSIZE; #endif // _MSC_VER #ifndef _MSC_VER const int CP2P_Voice::kAudioFieldNumber; const int CP2P_Voice::kBroadcastGroupFieldNumber; #endif // !_MSC_VER CP2P_Voice::CP2P_Voice() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:CP2P_Voice) } void CP2P_Voice::InitAsDefaultInstance() { audio_ = const_cast< ::CMsgVoiceAudio*>(&::CMsgVoiceAudio::default_instance()); } CP2P_Voice::CP2P_Voice(const CP2P_Voice& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:CP2P_Voice) } void CP2P_Voice::SharedCtor() { _cached_size_ = 0; audio_ = NULL; broadcast_group_ = 0u; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } CP2P_Voice::~CP2P_Voice() { // @@protoc_insertion_point(destructor:CP2P_Voice) SharedDtor(); } void CP2P_Voice::SharedDtor() { if (this != default_instance_) { delete audio_; } } void CP2P_Voice::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* CP2P_Voice::descriptor() { protobuf_AssignDescriptorsOnce(); return CP2P_Voice_descriptor_; } const CP2P_Voice& CP2P_Voice::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto(); return *default_instance_; } CP2P_Voice* CP2P_Voice::default_instance_ = NULL; CP2P_Voice* CP2P_Voice::New() const { return new CP2P_Voice; } void CP2P_Voice::Clear() { if (_has_bits_[0 / 32] & 3) { if (has_audio()) { if (audio_ != NULL) audio_->::CMsgVoiceAudio::Clear(); } broadcast_group_ = 0u; } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool CP2P_Voice::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:CP2P_Voice) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional .CMsgVoiceAudio audio = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_audio())); } else { goto handle_unusual; } if (input->ExpectTag(16)) goto parse_broadcast_group; break; } // optional uint32 broadcast_group = 2; case 2: { if (tag == 16) { parse_broadcast_group: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &broadcast_group_))); set_has_broadcast_group(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:CP2P_Voice) return true; failure: // @@protoc_insertion_point(parse_failure:CP2P_Voice) return false; #undef DO_ } void CP2P_Voice::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:CP2P_Voice) // optional .CMsgVoiceAudio audio = 1; if (has_audio()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->audio(), output); } // optional uint32 broadcast_group = 2; if (has_broadcast_group()) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(2, this->broadcast_group(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:CP2P_Voice) } ::google::protobuf::uint8* CP2P_Voice::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:CP2P_Voice) // optional .CMsgVoiceAudio audio = 1; if (has_audio()) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 1, this->audio(), target); } // optional uint32 broadcast_group = 2; if (has_broadcast_group()) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(2, this->broadcast_group(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:CP2P_Voice) return target; } int CP2P_Voice::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // optional .CMsgVoiceAudio audio = 1; if (has_audio()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->audio()); } // optional uint32 broadcast_group = 2; if (has_broadcast_group()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->broadcast_group()); } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void CP2P_Voice::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const CP2P_Voice* source = ::google::protobuf::internal::dynamic_cast_if_available<const CP2P_Voice*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void CP2P_Voice::MergeFrom(const CP2P_Voice& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_audio()) { mutable_audio()->::CMsgVoiceAudio::MergeFrom(from.audio()); } if (from.has_broadcast_group()) { set_broadcast_group(from.broadcast_group()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void CP2P_Voice::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void CP2P_Voice::CopyFrom(const CP2P_Voice& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool CP2P_Voice::IsInitialized() const { return true; } void CP2P_Voice::Swap(CP2P_Voice* other) { if (other != this) { std::swap(audio_, other->audio_); std::swap(broadcast_group_, other->broadcast_group_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata CP2P_Voice::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = CP2P_Voice_descriptor_; metadata.reflection = CP2P_Voice_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int CP2P_Ping::kSendTimeFieldNumber; const int CP2P_Ping::kIsReplyFieldNumber; #endif // !_MSC_VER CP2P_Ping::CP2P_Ping() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:CP2P_Ping) } void CP2P_Ping::InitAsDefaultInstance() { } CP2P_Ping::CP2P_Ping(const CP2P_Ping& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:CP2P_Ping) } void CP2P_Ping::SharedCtor() { _cached_size_ = 0; send_time_ = GOOGLE_ULONGLONG(0); is_reply_ = false; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } CP2P_Ping::~CP2P_Ping() { // @@protoc_insertion_point(destructor:CP2P_Ping) SharedDtor(); } void CP2P_Ping::SharedDtor() { if (this != default_instance_) { } } void CP2P_Ping::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* CP2P_Ping::descriptor() { protobuf_AssignDescriptorsOnce(); return CP2P_Ping_descriptor_; } const CP2P_Ping& CP2P_Ping::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto(); return *default_instance_; } CP2P_Ping* CP2P_Ping::default_instance_ = NULL; CP2P_Ping* CP2P_Ping::New() const { return new CP2P_Ping; } void CP2P_Ping::Clear() { #define OFFSET_OF_FIELD_(f) (reinterpret_cast<char*>( \ &reinterpret_cast<CP2P_Ping*>(16)->f) - \ reinterpret_cast<char*>(16)) #define ZR_(first, last) do { \ size_t f = OFFSET_OF_FIELD_(first); \ size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ ::memset(&first, 0, n); \ } while (0) ZR_(send_time_, is_reply_); #undef OFFSET_OF_FIELD_ #undef ZR_ ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool CP2P_Ping::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:CP2P_Ping) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required uint64 send_time = 1; case 1: { if (tag == 8) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>( input, &send_time_))); set_has_send_time(); } else { goto handle_unusual; } if (input->ExpectTag(16)) goto parse_is_reply; break; } // required bool is_reply = 2; case 2: { if (tag == 16) { parse_is_reply: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &is_reply_))); set_has_is_reply(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:CP2P_Ping) return true; failure: // @@protoc_insertion_point(parse_failure:CP2P_Ping) return false; #undef DO_ } void CP2P_Ping::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:CP2P_Ping) // required uint64 send_time = 1; if (has_send_time()) { ::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->send_time(), output); } // required bool is_reply = 2; if (has_is_reply()) { ::google::protobuf::internal::WireFormatLite::WriteBool(2, this->is_reply(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:CP2P_Ping) } ::google::protobuf::uint8* CP2P_Ping::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:CP2P_Ping) // required uint64 send_time = 1; if (has_send_time()) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(1, this->send_time(), target); } // required bool is_reply = 2; if (has_is_reply()) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->is_reply(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:CP2P_Ping) return target; } int CP2P_Ping::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required uint64 send_time = 1; if (has_send_time()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt64Size( this->send_time()); } // required bool is_reply = 2; if (has_is_reply()) { total_size += 1 + 1; } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void CP2P_Ping::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const CP2P_Ping* source = ::google::protobuf::internal::dynamic_cast_if_available<const CP2P_Ping*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void CP2P_Ping::MergeFrom(const CP2P_Ping& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_send_time()) { set_send_time(from.send_time()); } if (from.has_is_reply()) { set_is_reply(from.is_reply()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void CP2P_Ping::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void CP2P_Ping::CopyFrom(const CP2P_Ping& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool CP2P_Ping::IsInitialized() const { if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; return true; } void CP2P_Ping::Swap(CP2P_Ping* other) { if (other != this) { std::swap(send_time_, other->send_time_); std::swap(is_reply_, other->is_reply_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata CP2P_Ping::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = CP2P_Ping_descriptor_; metadata.reflection = CP2P_Ping_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int CP2P_VRAvatarPosition_COrientation::kPosFieldNumber; const int CP2P_VRAvatarPosition_COrientation::kAngFieldNumber; #endif // !_MSC_VER CP2P_VRAvatarPosition_COrientation::CP2P_VRAvatarPosition_COrientation() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:CP2P_VRAvatarPosition.COrientation) } void CP2P_VRAvatarPosition_COrientation::InitAsDefaultInstance() { pos_ = const_cast< ::CMsgVector*>(&::CMsgVector::default_instance()); ang_ = const_cast< ::CMsgQAngle*>(&::CMsgQAngle::default_instance()); } CP2P_VRAvatarPosition_COrientation::CP2P_VRAvatarPosition_COrientation(const CP2P_VRAvatarPosition_COrientation& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:CP2P_VRAvatarPosition.COrientation) } void CP2P_VRAvatarPosition_COrientation::SharedCtor() { _cached_size_ = 0; pos_ = NULL; ang_ = NULL; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } CP2P_VRAvatarPosition_COrientation::~CP2P_VRAvatarPosition_COrientation() { // @@protoc_insertion_point(destructor:CP2P_VRAvatarPosition.COrientation) SharedDtor(); } void CP2P_VRAvatarPosition_COrientation::SharedDtor() { if (this != default_instance_) { delete pos_; delete ang_; } } void CP2P_VRAvatarPosition_COrientation::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* CP2P_VRAvatarPosition_COrientation::descriptor() { protobuf_AssignDescriptorsOnce(); return CP2P_VRAvatarPosition_COrientation_descriptor_; } const CP2P_VRAvatarPosition_COrientation& CP2P_VRAvatarPosition_COrientation::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto(); return *default_instance_; } CP2P_VRAvatarPosition_COrientation* CP2P_VRAvatarPosition_COrientation::default_instance_ = NULL; CP2P_VRAvatarPosition_COrientation* CP2P_VRAvatarPosition_COrientation::New() const { return new CP2P_VRAvatarPosition_COrientation; } void CP2P_VRAvatarPosition_COrientation::Clear() { if (_has_bits_[0 / 32] & 3) { if (has_pos()) { if (pos_ != NULL) pos_->::CMsgVector::Clear(); } if (has_ang()) { if (ang_ != NULL) ang_->::CMsgQAngle::Clear(); } } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool CP2P_VRAvatarPosition_COrientation::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:CP2P_VRAvatarPosition.COrientation) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional .CMsgVector pos = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_pos())); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_ang; break; } // optional .CMsgQAngle ang = 2; case 2: { if (tag == 18) { parse_ang: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_ang())); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:CP2P_VRAvatarPosition.COrientation) return true; failure: // @@protoc_insertion_point(parse_failure:CP2P_VRAvatarPosition.COrientation) return false; #undef DO_ } void CP2P_VRAvatarPosition_COrientation::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:CP2P_VRAvatarPosition.COrientation) // optional .CMsgVector pos = 1; if (has_pos()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->pos(), output); } // optional .CMsgQAngle ang = 2; if (has_ang()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->ang(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:CP2P_VRAvatarPosition.COrientation) } ::google::protobuf::uint8* CP2P_VRAvatarPosition_COrientation::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:CP2P_VRAvatarPosition.COrientation) // optional .CMsgVector pos = 1; if (has_pos()) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 1, this->pos(), target); } // optional .CMsgQAngle ang = 2; if (has_ang()) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 2, this->ang(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:CP2P_VRAvatarPosition.COrientation) return target; } int CP2P_VRAvatarPosition_COrientation::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // optional .CMsgVector pos = 1; if (has_pos()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->pos()); } // optional .CMsgQAngle ang = 2; if (has_ang()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->ang()); } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void CP2P_VRAvatarPosition_COrientation::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const CP2P_VRAvatarPosition_COrientation* source = ::google::protobuf::internal::dynamic_cast_if_available<const CP2P_VRAvatarPosition_COrientation*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void CP2P_VRAvatarPosition_COrientation::MergeFrom(const CP2P_VRAvatarPosition_COrientation& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_pos()) { mutable_pos()->::CMsgVector::MergeFrom(from.pos()); } if (from.has_ang()) { mutable_ang()->::CMsgQAngle::MergeFrom(from.ang()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void CP2P_VRAvatarPosition_COrientation::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void CP2P_VRAvatarPosition_COrientation::CopyFrom(const CP2P_VRAvatarPosition_COrientation& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool CP2P_VRAvatarPosition_COrientation::IsInitialized() const { return true; } void CP2P_VRAvatarPosition_COrientation::Swap(CP2P_VRAvatarPosition_COrientation* other) { if (other != this) { std::swap(pos_, other->pos_); std::swap(ang_, other->ang_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata CP2P_VRAvatarPosition_COrientation::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = CP2P_VRAvatarPosition_COrientation_descriptor_; metadata.reflection = CP2P_VRAvatarPosition_COrientation_reflection_; return metadata; } // ------------------------------------------------------------------- #ifndef _MSC_VER const int CP2P_VRAvatarPosition::kBodyPartsFieldNumber; const int CP2P_VRAvatarPosition::kHatIdFieldNumber; const int CP2P_VRAvatarPosition::kSceneIdFieldNumber; const int CP2P_VRAvatarPosition::kWorldScaleFieldNumber; #endif // !_MSC_VER CP2P_VRAvatarPosition::CP2P_VRAvatarPosition() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:CP2P_VRAvatarPosition) } void CP2P_VRAvatarPosition::InitAsDefaultInstance() { } CP2P_VRAvatarPosition::CP2P_VRAvatarPosition(const CP2P_VRAvatarPosition& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:CP2P_VRAvatarPosition) } void CP2P_VRAvatarPosition::SharedCtor() { _cached_size_ = 0; hat_id_ = 0; scene_id_ = 0; world_scale_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } CP2P_VRAvatarPosition::~CP2P_VRAvatarPosition() { // @@protoc_insertion_point(destructor:CP2P_VRAvatarPosition) SharedDtor(); } void CP2P_VRAvatarPosition::SharedDtor() { if (this != default_instance_) { } } void CP2P_VRAvatarPosition::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* CP2P_VRAvatarPosition::descriptor() { protobuf_AssignDescriptorsOnce(); return CP2P_VRAvatarPosition_descriptor_; } const CP2P_VRAvatarPosition& CP2P_VRAvatarPosition::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto(); return *default_instance_; } CP2P_VRAvatarPosition* CP2P_VRAvatarPosition::default_instance_ = NULL; CP2P_VRAvatarPosition* CP2P_VRAvatarPosition::New() const { return new CP2P_VRAvatarPosition; } void CP2P_VRAvatarPosition::Clear() { #define OFFSET_OF_FIELD_(f) (reinterpret_cast<char*>( \ &reinterpret_cast<CP2P_VRAvatarPosition*>(16)->f) - \ reinterpret_cast<char*>(16)) #define ZR_(first, last) do { \ size_t f = OFFSET_OF_FIELD_(first); \ size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ ::memset(&first, 0, n); \ } while (0) ZR_(hat_id_, world_scale_); #undef OFFSET_OF_FIELD_ #undef ZR_ body_parts_.Clear(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool CP2P_VRAvatarPosition::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:CP2P_VRAvatarPosition) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .CP2P_VRAvatarPosition.COrientation body_parts = 1; case 1: { if (tag == 10) { parse_body_parts: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_body_parts())); } else { goto handle_unusual; } if (input->ExpectTag(10)) goto parse_body_parts; if (input->ExpectTag(16)) goto parse_hat_id; break; } // optional int32 hat_id = 2; case 2: { if (tag == 16) { parse_hat_id: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &hat_id_))); set_has_hat_id(); } else { goto handle_unusual; } if (input->ExpectTag(24)) goto parse_scene_id; break; } // optional int32 scene_id = 3; case 3: { if (tag == 24) { parse_scene_id: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &scene_id_))); set_has_scene_id(); } else { goto handle_unusual; } if (input->ExpectTag(32)) goto parse_world_scale; break; } // optional int32 world_scale = 4; case 4: { if (tag == 32) { parse_world_scale: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &world_scale_))); set_has_world_scale(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:CP2P_VRAvatarPosition) return true; failure: // @@protoc_insertion_point(parse_failure:CP2P_VRAvatarPosition) return false; #undef DO_ } void CP2P_VRAvatarPosition::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:CP2P_VRAvatarPosition) // repeated .CP2P_VRAvatarPosition.COrientation body_parts = 1; for (int i = 0; i < this->body_parts_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->body_parts(i), output); } // optional int32 hat_id = 2; if (has_hat_id()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->hat_id(), output); } // optional int32 scene_id = 3; if (has_scene_id()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->scene_id(), output); } // optional int32 world_scale = 4; if (has_world_scale()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(4, this->world_scale(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:CP2P_VRAvatarPosition) } ::google::protobuf::uint8* CP2P_VRAvatarPosition::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:CP2P_VRAvatarPosition) // repeated .CP2P_VRAvatarPosition.COrientation body_parts = 1; for (int i = 0; i < this->body_parts_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 1, this->body_parts(i), target); } // optional int32 hat_id = 2; if (has_hat_id()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->hat_id(), target); } // optional int32 scene_id = 3; if (has_scene_id()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->scene_id(), target); } // optional int32 world_scale = 4; if (has_world_scale()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(4, this->world_scale(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:CP2P_VRAvatarPosition) return target; } int CP2P_VRAvatarPosition::ByteSize() const { int total_size = 0; if (_has_bits_[1 / 32] & (0xffu << (1 % 32))) { // optional int32 hat_id = 2; if (has_hat_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->hat_id()); } // optional int32 scene_id = 3; if (has_scene_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->scene_id()); } // optional int32 world_scale = 4; if (has_world_scale()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->world_scale()); } } // repeated .CP2P_VRAvatarPosition.COrientation body_parts = 1; total_size += 1 * this->body_parts_size(); for (int i = 0; i < this->body_parts_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->body_parts(i)); } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void CP2P_VRAvatarPosition::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const CP2P_VRAvatarPosition* source = ::google::protobuf::internal::dynamic_cast_if_available<const CP2P_VRAvatarPosition*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void CP2P_VRAvatarPosition::MergeFrom(const CP2P_VRAvatarPosition& from) { GOOGLE_CHECK_NE(&from, this); body_parts_.MergeFrom(from.body_parts_); if (from._has_bits_[1 / 32] & (0xffu << (1 % 32))) { if (from.has_hat_id()) { set_hat_id(from.hat_id()); } if (from.has_scene_id()) { set_scene_id(from.scene_id()); } if (from.has_world_scale()) { set_world_scale(from.world_scale()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void CP2P_VRAvatarPosition::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void CP2P_VRAvatarPosition::CopyFrom(const CP2P_VRAvatarPosition& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool CP2P_VRAvatarPosition::IsInitialized() const { return true; } void CP2P_VRAvatarPosition::Swap(CP2P_VRAvatarPosition* other) { if (other != this) { body_parts_.Swap(&other->body_parts_); std::swap(hat_id_, other->hat_id_); std::swap(scene_id_, other->scene_id_); std::swap(world_scale_, other->world_scale_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata CP2P_VRAvatarPosition::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = CP2P_VRAvatarPosition_descriptor_; metadata.reflection = CP2P_VRAvatarPosition_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int CP2P_WatchSynchronization::kDemoTickFieldNumber; const int CP2P_WatchSynchronization::kPausedFieldNumber; const int CP2P_WatchSynchronization::kTvListenVoiceIndicesFieldNumber; const int CP2P_WatchSynchronization::kDotaSpectatorModeFieldNumber; const int CP2P_WatchSynchronization::kDotaSpectatorWatchingBroadcasterFieldNumber; const int CP2P_WatchSynchronization::kDotaSpectatorHeroIndexFieldNumber; const int CP2P_WatchSynchronization::kDotaSpectatorAutospeedFieldNumber; const int CP2P_WatchSynchronization::kDotaReplaySpeedFieldNumber; #endif // !_MSC_VER CP2P_WatchSynchronization::CP2P_WatchSynchronization() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:CP2P_WatchSynchronization) } void CP2P_WatchSynchronization::InitAsDefaultInstance() { } CP2P_WatchSynchronization::CP2P_WatchSynchronization(const CP2P_WatchSynchronization& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:CP2P_WatchSynchronization) } void CP2P_WatchSynchronization::SharedCtor() { _cached_size_ = 0; demo_tick_ = 0; paused_ = false; tv_listen_voice_indices_ = 0; dota_spectator_mode_ = 0; dota_spectator_watching_broadcaster_ = 0; dota_spectator_hero_index_ = 0; dota_spectator_autospeed_ = 0; dota_replay_speed_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } CP2P_WatchSynchronization::~CP2P_WatchSynchronization() { // @@protoc_insertion_point(destructor:CP2P_WatchSynchronization) SharedDtor(); } void CP2P_WatchSynchronization::SharedDtor() { if (this != default_instance_) { } } void CP2P_WatchSynchronization::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* CP2P_WatchSynchronization::descriptor() { protobuf_AssignDescriptorsOnce(); return CP2P_WatchSynchronization_descriptor_; } const CP2P_WatchSynchronization& CP2P_WatchSynchronization::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto(); return *default_instance_; } CP2P_WatchSynchronization* CP2P_WatchSynchronization::default_instance_ = NULL; CP2P_WatchSynchronization* CP2P_WatchSynchronization::New() const { return new CP2P_WatchSynchronization; } void CP2P_WatchSynchronization::Clear() { #define OFFSET_OF_FIELD_(f) (reinterpret_cast<char*>( \ &reinterpret_cast<CP2P_WatchSynchronization*>(16)->f) - \ reinterpret_cast<char*>(16)) #define ZR_(first, last) do { \ size_t f = OFFSET_OF_FIELD_(first); \ size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ ::memset(&first, 0, n); \ } while (0) if (_has_bits_[0 / 32] & 255) { ZR_(demo_tick_, dota_replay_speed_); } #undef OFFSET_OF_FIELD_ #undef ZR_ ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool CP2P_WatchSynchronization::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:CP2P_WatchSynchronization) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional int32 demo_tick = 1; case 1: { if (tag == 8) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &demo_tick_))); set_has_demo_tick(); } else { goto handle_unusual; } if (input->ExpectTag(16)) goto parse_paused; break; } // optional bool paused = 2; case 2: { if (tag == 16) { parse_paused: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &paused_))); set_has_paused(); } else { goto handle_unusual; } if (input->ExpectTag(24)) goto parse_tv_listen_voice_indices; break; } // optional int32 tv_listen_voice_indices = 3; case 3: { if (tag == 24) { parse_tv_listen_voice_indices: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &tv_listen_voice_indices_))); set_has_tv_listen_voice_indices(); } else { goto handle_unusual; } if (input->ExpectTag(32)) goto parse_dota_spectator_mode; break; } // optional int32 dota_spectator_mode = 4; case 4: { if (tag == 32) { parse_dota_spectator_mode: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &dota_spectator_mode_))); set_has_dota_spectator_mode(); } else { goto handle_unusual; } if (input->ExpectTag(40)) goto parse_dota_spectator_watching_broadcaster; break; } // optional int32 dota_spectator_watching_broadcaster = 5; case 5: { if (tag == 40) { parse_dota_spectator_watching_broadcaster: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &dota_spectator_watching_broadcaster_))); set_has_dota_spectator_watching_broadcaster(); } else { goto handle_unusual; } if (input->ExpectTag(48)) goto parse_dota_spectator_hero_index; break; } // optional int32 dota_spectator_hero_index = 6; case 6: { if (tag == 48) { parse_dota_spectator_hero_index: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &dota_spectator_hero_index_))); set_has_dota_spectator_hero_index(); } else { goto handle_unusual; } if (input->ExpectTag(56)) goto parse_dota_spectator_autospeed; break; } // optional int32 dota_spectator_autospeed = 7; case 7: { if (tag == 56) { parse_dota_spectator_autospeed: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &dota_spectator_autospeed_))); set_has_dota_spectator_autospeed(); } else { goto handle_unusual; } if (input->ExpectTag(64)) goto parse_dota_replay_speed; break; } // optional int32 dota_replay_speed = 8; case 8: { if (tag == 64) { parse_dota_replay_speed: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &dota_replay_speed_))); set_has_dota_replay_speed(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:CP2P_WatchSynchronization) return true; failure: // @@protoc_insertion_point(parse_failure:CP2P_WatchSynchronization) return false; #undef DO_ } void CP2P_WatchSynchronization::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:CP2P_WatchSynchronization) // optional int32 demo_tick = 1; if (has_demo_tick()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->demo_tick(), output); } // optional bool paused = 2; if (has_paused()) { ::google::protobuf::internal::WireFormatLite::WriteBool(2, this->paused(), output); } // optional int32 tv_listen_voice_indices = 3; if (has_tv_listen_voice_indices()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->tv_listen_voice_indices(), output); } // optional int32 dota_spectator_mode = 4; if (has_dota_spectator_mode()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(4, this->dota_spectator_mode(), output); } // optional int32 dota_spectator_watching_broadcaster = 5; if (has_dota_spectator_watching_broadcaster()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(5, this->dota_spectator_watching_broadcaster(), output); } // optional int32 dota_spectator_hero_index = 6; if (has_dota_spectator_hero_index()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(6, this->dota_spectator_hero_index(), output); } // optional int32 dota_spectator_autospeed = 7; if (has_dota_spectator_autospeed()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(7, this->dota_spectator_autospeed(), output); } // optional int32 dota_replay_speed = 8; if (has_dota_replay_speed()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(8, this->dota_replay_speed(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:CP2P_WatchSynchronization) } ::google::protobuf::uint8* CP2P_WatchSynchronization::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:CP2P_WatchSynchronization) // optional int32 demo_tick = 1; if (has_demo_tick()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->demo_tick(), target); } // optional bool paused = 2; if (has_paused()) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->paused(), target); } // optional int32 tv_listen_voice_indices = 3; if (has_tv_listen_voice_indices()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->tv_listen_voice_indices(), target); } // optional int32 dota_spectator_mode = 4; if (has_dota_spectator_mode()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(4, this->dota_spectator_mode(), target); } // optional int32 dota_spectator_watching_broadcaster = 5; if (has_dota_spectator_watching_broadcaster()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(5, this->dota_spectator_watching_broadcaster(), target); } // optional int32 dota_spectator_hero_index = 6; if (has_dota_spectator_hero_index()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(6, this->dota_spectator_hero_index(), target); } // optional int32 dota_spectator_autospeed = 7; if (has_dota_spectator_autospeed()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(7, this->dota_spectator_autospeed(), target); } // optional int32 dota_replay_speed = 8; if (has_dota_replay_speed()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(8, this->dota_replay_speed(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:CP2P_WatchSynchronization) return target; } int CP2P_WatchSynchronization::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // optional int32 demo_tick = 1; if (has_demo_tick()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->demo_tick()); } // optional bool paused = 2; if (has_paused()) { total_size += 1 + 1; } // optional int32 tv_listen_voice_indices = 3; if (has_tv_listen_voice_indices()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->tv_listen_voice_indices()); } // optional int32 dota_spectator_mode = 4; if (has_dota_spectator_mode()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->dota_spectator_mode()); } // optional int32 dota_spectator_watching_broadcaster = 5; if (has_dota_spectator_watching_broadcaster()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->dota_spectator_watching_broadcaster()); } // optional int32 dota_spectator_hero_index = 6; if (has_dota_spectator_hero_index()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->dota_spectator_hero_index()); } // optional int32 dota_spectator_autospeed = 7; if (has_dota_spectator_autospeed()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->dota_spectator_autospeed()); } // optional int32 dota_replay_speed = 8; if (has_dota_replay_speed()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->dota_replay_speed()); } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void CP2P_WatchSynchronization::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const CP2P_WatchSynchronization* source = ::google::protobuf::internal::dynamic_cast_if_available<const CP2P_WatchSynchronization*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void CP2P_WatchSynchronization::MergeFrom(const CP2P_WatchSynchronization& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_demo_tick()) { set_demo_tick(from.demo_tick()); } if (from.has_paused()) { set_paused(from.paused()); } if (from.has_tv_listen_voice_indices()) { set_tv_listen_voice_indices(from.tv_listen_voice_indices()); } if (from.has_dota_spectator_mode()) { set_dota_spectator_mode(from.dota_spectator_mode()); } if (from.has_dota_spectator_watching_broadcaster()) { set_dota_spectator_watching_broadcaster(from.dota_spectator_watching_broadcaster()); } if (from.has_dota_spectator_hero_index()) { set_dota_spectator_hero_index(from.dota_spectator_hero_index()); } if (from.has_dota_spectator_autospeed()) { set_dota_spectator_autospeed(from.dota_spectator_autospeed()); } if (from.has_dota_replay_speed()) { set_dota_replay_speed(from.dota_replay_speed()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void CP2P_WatchSynchronization::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void CP2P_WatchSynchronization::CopyFrom(const CP2P_WatchSynchronization& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool CP2P_WatchSynchronization::IsInitialized() const { return true; } void CP2P_WatchSynchronization::Swap(CP2P_WatchSynchronization* other) { if (other != this) { std::swap(demo_tick_, other->demo_tick_); std::swap(paused_, other->paused_); std::swap(tv_listen_voice_indices_, other->tv_listen_voice_indices_); std::swap(dota_spectator_mode_, other->dota_spectator_mode_); std::swap(dota_spectator_watching_broadcaster_, other->dota_spectator_watching_broadcaster_); std::swap(dota_spectator_hero_index_, other->dota_spectator_hero_index_); std::swap(dota_spectator_autospeed_, other->dota_spectator_autospeed_); std::swap(dota_replay_speed_, other->dota_replay_speed_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata CP2P_WatchSynchronization::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = CP2P_WatchSynchronization_descriptor_; metadata.reflection = CP2P_WatchSynchronization_reflection_; return metadata; } // @@protoc_insertion_point(namespace_scope) // @@protoc_insertion_point(global_scope)
33.944853
133
0.703118
devilesk