hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
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
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
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
a865f27a20daf4e5f2d44d68a329738578fdeb54
4,959
cpp
C++
examples/tlm/at_ooo/src/at_ooo_top.cpp
veeYceeY/systemc
1bd5598ed1a8cf677ebb750accd5af485bc1085a
[ "Apache-2.0" ]
194
2019-07-25T21:27:23.000Z
2022-03-22T00:08:06.000Z
examples/tlm/at_ooo/src/at_ooo_top.cpp
veeYceeY/systemc
1bd5598ed1a8cf677ebb750accd5af485bc1085a
[ "Apache-2.0" ]
24
2019-12-03T18:26:07.000Z
2022-02-17T09:38:25.000Z
examples/tlm/at_ooo/src/at_ooo_top.cpp
veeYceeY/systemc
1bd5598ed1a8cf677ebb750accd5af485bc1085a
[ "Apache-2.0" ]
64
2019-08-02T19:28:25.000Z
2022-03-30T10:21:22.000Z
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /*============================================================================= @file example_system_top.cpp @brief This class instantiates components that compose a TLM2 example system that demonstrates Out Of Order transaction processing =============================================================================*/ /***************************************************************************** Original Authors: Bill Bunton, ESLX Anna Keist, ESLX *****************************************************************************/ #include "at_ooo_top.h" // example system top header #include "at_target_2_phase.h" // memory target #include "at_target_ooo_2_phase.h" // memory target #include "initiator_top.h" // initiator #include "tlm.h" // TLM header /*============================================================================= @fn example_system_top::example_system_top @brief example_system_top constructor @details This class instantiates the example system components and call the modules bind methods to logically connect the model components. @param name module name @retval void =============================================================================*/ example_system_top::example_system_top ///< constructor ( sc_core::sc_module_name name ///< module name ) : sc_core::sc_module ///< SC base ( name ///< module name ) , m_bus ///< bus ( "m_bus" ///< module name ) , m_at_target_2_phase_1 ///< at_test_target ( "m_at_target_2_phase_1" ///< module name , 201 , "memory_socket_1" ///< socket name , 4*1024 ///< memory size (bytes) , 4 ///< memory width (bytes) , sc_core::sc_time(10, sc_core::SC_NS) ///< accept delay , sc_core::sc_time(50, sc_core::SC_NS) ///< read response delay , sc_core::sc_time(30, sc_core::SC_NS) ///< write response delay ) , m_at_target_ooo_2_phase_1 ///< at_test_target ( "m_at_target_ooo_2_phase_1" ///< module name , 202 , "memory_socket_1" ///< socket name , 4*1024 ///< memory size (bytes) , 4 ///< memory width (bytes) // force additional out of order execution by making on // target longer than the other , sc_core::sc_time(20, sc_core::SC_NS) ///< accept delay , sc_core::sc_time(100, sc_core::SC_NS) ///< read response delay , sc_core::sc_time(60, sc_core::SC_NS) ///< write response delay ) , m_initiator_1 ///< initiator 1 ( "m_initiator_1" ///< module name , 101 ///< initiator ID , 0x0000000000000100 ///< fitst base address , 0x0000000010000100 ///< second base address , 2 // active transactions ) , m_initiator_2 ///< initiator 2 ( "m_initiator_2" ///< module name , 102 ///< initiator ID , 0x0000000000000200 ///< fitst base address , 0x0000000010000200 ///< second base address , 2 // active transactions ) { // bind TLM2 initiator to TLM2 target m_initiator_1.initiator_socket(m_bus.target_socket[0]); m_initiator_2.initiator_socket(m_bus.target_socket[1]); m_bus.initiator_socket[0](m_at_target_2_phase_1.m_memory_socket); m_bus.initiator_socket[1](m_at_target_ooo_2_phase_1.m_memory_socket); }
43.5
80
0.497076
veeYceeY
a86623195137bb99ea71ffcb7029404dda1ec14a
6,306
hpp
C++
src/3rd party/boost/boost/multi_array/concept_checks.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
8
2016-01-25T20:18:51.000Z
2019-03-06T07:00:04.000Z
src/3rd party/boost/boost/multi_array/concept_checks.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
null
null
null
src/3rd party/boost/boost/multi_array/concept_checks.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
// Copyright (C) 2002 Ronald Garcia // // Permission to copy, use, sell and distribute this software is granted // provided this copyright notice appears in all copies. // Permission to modify the code and to distribute modified code is granted // provided this copyright notice appears in all copies, and a notice // that the code was modified is included with the copyright notice. // // This software is provided "as is" without express or implied warranty, // and with no claim as to its suitability for any purpose. // #ifndef BOOST_MULTI_ARRAY_CONCEPT_CHECKS_RG110101_HPP #define BOOST_MULTI_ARRAY_CONCEPT_CHECKS_RG110101_HPP // // concept-checks.hpp - Checks out Const MultiArray and MultiArray // concepts // #include "boost/concept_check.hpp" namespace boost { namespace detail { namespace multi_array { // // idgen_helper - // This is a helper for generating index_gen instantiations with // the right type in order to test the call to // operator[](index_gen). Since one would normally write: // A[ indices[range1][range2] ]; // or // B[ indices[index1][index2][range1] ]; // idgen helper allows us to generate the "indices" type by // creating it through recursive calls. template <std::size_t N> struct idgen_helper { template <typename Array, typename IdxGen, typename Call_Type> static void call(Array& a, const IdxGen& idgen, Call_Type c) { typedef typename Array::index_range index_range; typedef typename Array::index index; idgen_helper<N-1>::call(a,idgen[c],c); } }; template <> struct idgen_helper<0> { template <typename Array, typename IdxGen, typename Call_Type> static void call(Array& a, const IdxGen& idgen, Call_Type) { typedef typename Array::index_range index_range; typedef typename Array::index index; a[ idgen ]; } }; template <typename Array, std::size_t NumDims > struct ConstMultiArrayConcept { void constraints() { // function_requires< CopyConstructibleConcept<Array> >(); // RG - a( CollectionArchetype) when available... a[ id ]; // Test slicing, keeping only the first dimension, losing the rest idgen_helper<NumDims-1>::call(a,idgen[range],id); // Test slicing, keeping all dimensions. idgen_helper<NumDims-1>::call(a,idgen[range],range); st = a.size(); st = a.num_dimensions(); st = a.num_elements(); stp = a.shape(); idp = a.strides(); idp = a.index_bases(); cit = a.begin(); cit = a.end(); crit = a.rbegin(); crit = a.rend(); eltp = a.origin(); } typedef typename Array::value_type value_type; typedef typename Array::reference reference; typedef typename Array::const_reference const_reference; typedef typename Array::size_type size_type; typedef typename Array::difference_type difference_type; typedef typename Array::iterator iterator; typedef typename Array::const_iterator const_iterator; typedef typename Array::reverse_iterator reverse_iterator; typedef typename Array::const_reverse_iterator const_reverse_iterator; typedef typename Array::element element; typedef typename Array::index index; typedef typename Array::index_gen index_gen; typedef typename Array::index_range index_range; typedef typename Array::extent_gen extent_gen; typedef typename Array::extent_range extent_range; Array a; size_type st; const size_type* stp; index id; const index* idp; const_iterator cit; const_reverse_iterator crit; const element* eltp; index_gen idgen; index_range range; }; template <typename Array, std::size_t NumDims > struct MutableMultiArrayConcept { void constraints() { // function_requires< CopyConstructibleConcept<Array> >(); // RG - a( CollectionArchetype) when available... value_type vt = a[ id ]; // Test slicing, keeping only the first dimension, losing the rest idgen_helper<NumDims-1>::call(a,idgen[range],id); // Test slicing, keeping all dimensions. idgen_helper<NumDims-1>::call(a,idgen[range],range); st = a.size(); st = a.num_dimensions(); st = a.num_elements(); stp = a.shape(); idp = a.strides(); idp = a.index_bases(); it = a.begin(); it = a.end(); rit = a.rbegin(); rit = a.rend(); eltp = a.origin(); const_constraints(a); } void const_constraints(const Array& a) { // value_type vt = a[ id ]; // Test slicing, keeping only the first dimension, losing the rest idgen_helper<NumDims-1>::call(a,idgen[range],id); // Test slicing, keeping all dimensions. idgen_helper<NumDims-1>::call(a,idgen[range],range); st = a.size(); st = a.num_dimensions(); st = a.num_elements(); stp = a.shape(); idp = a.strides(); idp = a.index_bases(); cit = a.begin(); cit = a.end(); crit = a.rbegin(); crit = a.rend(); eltp = a.origin(); } typedef typename Array::value_type value_type; typedef typename Array::reference reference; typedef typename Array::const_reference const_reference; typedef typename Array::size_type size_type; typedef typename Array::difference_type difference_type; typedef typename Array::iterator iterator; typedef typename Array::const_iterator const_iterator; typedef typename Array::reverse_iterator reverse_iterator; typedef typename Array::const_reverse_iterator const_reverse_iterator; typedef typename Array::element element; typedef typename Array::index index; typedef typename Array::index_gen index_gen; typedef typename Array::index_range index_range; typedef typename Array::extent_gen extent_gen; typedef typename Array::extent_range extent_range; Array a; size_type st; const size_type* stp; index id; const index* idp; iterator it; const_iterator cit; reverse_iterator rit; const_reverse_iterator crit; const element* eltp; index_gen idgen; index_range range; }; } // namespace multi_array } // namespace detail } // namespace boost #endif // BOOST_MULTI_ARRAY_CONCEPT_CHECKS_RG110101_HPP
30.911765
75
0.679987
OLR-xray
a86a357c163bc7e81e00664a6ed39905f5d40611
15,313
cc
C++
source/geometry/divisions/pyG4ParameterisationCons.cc
yu22mal/geant4_pybind
ff7efc322fe53f39c7ae7ed140861052a92479fd
[ "Unlicense" ]
6
2021-08-08T08:40:13.000Z
2022-03-23T03:05:15.000Z
source/geometry/divisions/pyG4ParameterisationCons.cc
yu22mal/geant4_pybind
ff7efc322fe53f39c7ae7ed140861052a92479fd
[ "Unlicense" ]
3
2021-12-01T14:38:06.000Z
2022-02-10T11:28:28.000Z
source/geometry/divisions/pyG4ParameterisationCons.cc
yu22mal/geant4_pybind
ff7efc322fe53f39c7ae7ed140861052a92479fd
[ "Unlicense" ]
3
2021-07-16T13:57:34.000Z
2022-02-07T11:17:19.000Z
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <G4ParameterisationCons.hh> #include <G4Material.hh> #include <G4VPhysicalVolume.hh> #include <G4VTouchable.hh> #include <G4VSolid.hh> #include <G4Box.hh> #include <G4Tubs.hh> #include <G4Trd.hh> #include <G4Trap.hh> #include <G4Cons.hh> #include <G4Sphere.hh> #include <G4Orb.hh> #include <G4Ellipsoid.hh> #include <G4Torus.hh> #include <G4Para.hh> #include <G4Polycone.hh> #include <G4Polyhedra.hh> #include <G4Hype.hh> #include "typecast.hh" #include "opaques.hh" namespace py = pybind11; class PyG4VParameterisationCons : public G4VParameterisationCons, public py::trampoline_self_life_support { public: using G4VParameterisationCons::G4VParameterisationCons; void ComputeTransformation(const G4int copyNo, G4VPhysicalVolume *physVol) const override { PYBIND11_OVERRIDE_PURE(void, G4VParameterisationCons, ComputeTransformation, copyNo, physVol); } G4double GetMaxParameter() const override { PYBIND11_OVERRIDE_PURE(G4double, G4VParameterisationCons, GetMaxParameter, ); } G4VSolid *ComputeSolid(const G4int arg0, G4VPhysicalVolume *arg1) override { PYBIND11_OVERRIDE(G4VSolid *, G4VParameterisationCons, ComputeSolid, arg0, arg1); } void CheckParametersValidity() override { PYBIND11_OVERRIDE(void, G4VParameterisationCons, CheckParametersValidity, ); } G4Material *ComputeMaterial(const G4int repNo, G4VPhysicalVolume *currentVol, const G4VTouchable *parentTouch) override { PYBIND11_OVERRIDE(G4Material *, G4VParameterisationCons, ComputeMaterial, repNo, currentVol, parentTouch); } G4bool IsNested() const override { PYBIND11_OVERRIDE(G4bool, G4VParameterisationCons, IsNested, ); } G4VVolumeMaterialScanner *GetMaterialScanner() override { PYBIND11_OVERRIDE(G4VVolumeMaterialScanner *, G4VParameterisationCons, GetMaterialScanner, ); } void ComputeDimensions(G4Box &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override { PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2); return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2); } void ComputeDimensions(G4Tubs &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override { PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2); return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2); } void ComputeDimensions(G4Trd &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override { PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2); return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2); } void ComputeDimensions(G4Trap &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override { PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2); return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2); } void ComputeDimensions(G4Cons &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override { PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2); return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2); } void ComputeDimensions(G4Sphere &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override { PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2); return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2); } void ComputeDimensions(G4Orb &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override { PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2); return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2); } void ComputeDimensions(G4Ellipsoid &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override { PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2); return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2); } void ComputeDimensions(G4Torus &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override { PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2); return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2); } void ComputeDimensions(G4Para &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override { PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2); return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2); } void ComputeDimensions(G4Polycone &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override { PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2); return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2); } void ComputeDimensions(G4Polyhedra &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override { PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2); return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2); } void ComputeDimensions(G4Hype &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override { PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2); return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2); } }; class PyG4ParameterisationConsRho : public G4ParameterisationConsRho, public py::trampoline_self_life_support { public: using G4ParameterisationConsRho::G4ParameterisationConsRho; G4double GetMaxParameter() const override { PYBIND11_OVERRIDE(G4double, G4ParameterisationConsRho, GetMaxParameter, ); } void ComputeTransformation(const G4int copyNo, G4VPhysicalVolume *physVol) const override { PYBIND11_OVERRIDE(void, G4ParameterisationConsRho, ComputeTransformation, copyNo, physVol); } void ComputeDimensions(G4Cons &tubs, const G4int copyNo, const G4VPhysicalVolume *physVol) const override { PYBIND11_OVERRIDE_IMPL(void, G4ParameterisationConsRho, "ComputeDimensions", std::addressof(tubs), copyNo, physVol); G4ParameterisationConsRho::ComputeDimensions(tubs, copyNo, physVol); } G4VSolid *ComputeSolid(const G4int arg0, G4VPhysicalVolume *arg1) override { PYBIND11_OVERRIDE(G4VSolid *, G4ParameterisationConsRho, ComputeSolid, arg0, arg1); } void CheckParametersValidity() override { PYBIND11_OVERRIDE(void, G4ParameterisationConsRho, CheckParametersValidity, ); } G4Material *ComputeMaterial(const G4int repNo, G4VPhysicalVolume *currentVol, const G4VTouchable *parentTouch) override { PYBIND11_OVERRIDE(G4Material *, G4ParameterisationConsRho, ComputeMaterial, repNo, currentVol, parentTouch); } G4bool IsNested() const override { PYBIND11_OVERRIDE(G4bool, G4ParameterisationConsRho, IsNested, ); } G4VVolumeMaterialScanner *GetMaterialScanner() override { PYBIND11_OVERRIDE(G4VVolumeMaterialScanner *, G4ParameterisationConsRho, GetMaterialScanner, ); } }; class PyG4ParameterisationConsPhi : public G4ParameterisationConsPhi, public py::trampoline_self_life_support { public: using G4ParameterisationConsPhi::G4ParameterisationConsPhi; G4double GetMaxParameter() const override { PYBIND11_OVERRIDE(G4double, G4ParameterisationConsPhi, GetMaxParameter, ); } void ComputeTransformation(const G4int copyNo, G4VPhysicalVolume *physVol) const override { PYBIND11_OVERRIDE(void, G4ParameterisationConsPhi, ComputeTransformation, copyNo, physVol); } void ComputeDimensions(G4Cons &tubs, const G4int copyNo, const G4VPhysicalVolume *physVol) const override { PYBIND11_OVERRIDE_IMPL(void, G4ParameterisationConsPhi, "ComputeDimensions", std::addressof(tubs), copyNo, physVol); G4ParameterisationConsPhi::ComputeDimensions(tubs, copyNo, physVol); } G4VSolid *ComputeSolid(const G4int arg0, G4VPhysicalVolume *arg1) override { PYBIND11_OVERRIDE(G4VSolid *, G4ParameterisationConsPhi, ComputeSolid, arg0, arg1); } void CheckParametersValidity() override { PYBIND11_OVERRIDE(void, G4ParameterisationConsPhi, CheckParametersValidity, ); } G4Material *ComputeMaterial(const G4int repNo, G4VPhysicalVolume *currentVol, const G4VTouchable *parentTouch) override { PYBIND11_OVERRIDE(G4Material *, G4ParameterisationConsPhi, ComputeMaterial, repNo, currentVol, parentTouch); } G4bool IsNested() const override { PYBIND11_OVERRIDE(G4bool, G4ParameterisationConsPhi, IsNested, ); } G4VVolumeMaterialScanner *GetMaterialScanner() override { PYBIND11_OVERRIDE(G4VVolumeMaterialScanner *, G4ParameterisationConsPhi, GetMaterialScanner, ); } }; class PyG4ParameterisationConsZ : public G4ParameterisationConsZ, public py::trampoline_self_life_support { public: using G4ParameterisationConsZ::G4ParameterisationConsZ; G4double GetMaxParameter() const override { PYBIND11_OVERRIDE(G4double, G4ParameterisationConsZ, GetMaxParameter, ); } void ComputeTransformation(const G4int copyNo, G4VPhysicalVolume *physVol) const override { PYBIND11_OVERRIDE(void, G4ParameterisationConsZ, ComputeTransformation, copyNo, physVol); } void ComputeDimensions(G4Cons &tubs, const G4int copyNo, const G4VPhysicalVolume *physVol) const override { PYBIND11_OVERRIDE_IMPL(void, G4ParameterisationConsZ, "ComputeDimensions", std::addressof(tubs), copyNo, physVol); G4ParameterisationConsZ::ComputeDimensions(tubs, copyNo, physVol); } G4VSolid *ComputeSolid(const G4int arg0, G4VPhysicalVolume *arg1) override { PYBIND11_OVERRIDE(G4VSolid *, G4ParameterisationConsZ, ComputeSolid, arg0, arg1); } void CheckParametersValidity() override { PYBIND11_OVERRIDE(void, G4ParameterisationConsZ, CheckParametersValidity, ); } G4Material *ComputeMaterial(const G4int repNo, G4VPhysicalVolume *currentVol, const G4VTouchable *parentTouch) override { PYBIND11_OVERRIDE(G4Material *, G4ParameterisationConsZ, ComputeMaterial, repNo, currentVol, parentTouch); } G4bool IsNested() const override { PYBIND11_OVERRIDE(G4bool, G4ParameterisationConsZ, IsNested, ); } G4VVolumeMaterialScanner *GetMaterialScanner() override { PYBIND11_OVERRIDE(G4VVolumeMaterialScanner *, G4ParameterisationConsZ, GetMaterialScanner, ); } }; void export_G4ParameterisationCons(py::module &m) { py::class_<G4VParameterisationCons, PyG4VParameterisationCons, G4VDivisionParameterisation>( m, "G4VParameterisationCons") .def(py::init<EAxis, G4int, G4double, G4double, G4VSolid *, DivisionType>(), py::arg("axis"), py::arg("nCopies"), py::arg("offset"), py::arg("step"), py::arg("msolid"), py::arg("divType")) .def("__copy__", [](const PyG4VParameterisationCons &self) { return PyG4VParameterisationCons(self); }) .def("__deepcopy__", [](const PyG4VParameterisationCons &self, py::dict) { return PyG4VParameterisationCons(self); }); py::class_<G4ParameterisationConsRho, PyG4ParameterisationConsRho, G4VParameterisationCons>( m, "G4ParameterisationConsRho") .def(py::init<EAxis, G4int, G4double, G4double, G4VSolid *, DivisionType>(), py::arg("axis"), py::arg("nCopies"), py::arg("offset"), py::arg("step"), py::arg("motherSolid"), py::arg("divType")) .def("__copy__", [](const PyG4ParameterisationConsRho &self) { return PyG4ParameterisationConsRho(self); }) .def("__deepcopy__", [](const PyG4ParameterisationConsRho &self, py::dict) { return PyG4ParameterisationConsRho(self); }) .def("GetMaxParameter", &G4ParameterisationConsRho::GetMaxParameter) .def("ComputeTransformation", &G4ParameterisationConsRho::ComputeTransformation, py::arg("copyNo"), py::arg("physVol")) .def("ComputeDimensions", py::overload_cast<G4Cons &, const G4int, const G4VPhysicalVolume *>( &G4ParameterisationConsRho::ComputeDimensions, py::const_), py::arg("tubs"), py::arg("copyNo"), py::arg("physVol")); py::class_<G4ParameterisationConsPhi, PyG4ParameterisationConsPhi, G4VParameterisationCons>( m, "G4ParameterisationConsPhi") .def(py::init<EAxis, G4int, G4double, G4double, G4VSolid *, DivisionType>(), py::arg("axis"), py::arg("nCopies"), py::arg("offset"), py::arg("step"), py::arg("motherSolid"), py::arg("divType")) .def("__copy__", [](const PyG4ParameterisationConsPhi &self) { return PyG4ParameterisationConsPhi(self); }) .def("__deepcopy__", [](const PyG4ParameterisationConsPhi &self, py::dict) { return PyG4ParameterisationConsPhi(self); }) .def("GetMaxParameter", &G4ParameterisationConsPhi::GetMaxParameter) .def("ComputeTransformation", &G4ParameterisationConsPhi::ComputeTransformation, py::arg("copyNo"), py::arg("physVol")) .def("ComputeDimensions", py::overload_cast<G4Cons &, const G4int, const G4VPhysicalVolume *>( &G4ParameterisationConsPhi::ComputeDimensions, py::const_), py::arg("tubs"), py::arg("copyNo"), py::arg("physVol")); py::class_<G4ParameterisationConsZ, PyG4ParameterisationConsZ, G4VParameterisationCons>(m, "G4ParameterisationConsZ") .def(py::init<EAxis, G4int, G4double, G4double, G4VSolid *, DivisionType>(), py::arg("axis"), py::arg("nCopies"), py::arg("offset"), py::arg("step"), py::arg("motherSolid"), py::arg("divType")) .def("__copy__", [](const PyG4ParameterisationConsZ &self) { return PyG4ParameterisationConsZ(self); }) .def("__deepcopy__", [](const PyG4ParameterisationConsZ &self, py::dict) { return PyG4ParameterisationConsZ(self); }) .def("GetMaxParameter", &G4ParameterisationConsZ::GetMaxParameter) .def("ComputeTransformation", &G4ParameterisationConsZ::ComputeTransformation, py::arg("copyNo"), py::arg("physVol")) .def("ComputeDimensions", py::overload_cast<G4Cons &, const G4int, const G4VPhysicalVolume *>( &G4ParameterisationConsZ::ComputeDimensions, py::const_), py::arg("tubs"), py::arg("copyNo"), py::arg("physVol")); }
43.751429
121
0.717691
yu22mal
a86d654f31b46bd834a81acc20772f64da3ee653
22,484
hpp
C++
src/Enzo/enzo_EnzoRiemannLUT.hpp
buketbenek/enzo-e
329a398ce4b11b03a1b2f1aef9e46d04560fe894
[ "BSD-3-Clause" ]
null
null
null
src/Enzo/enzo_EnzoRiemannLUT.hpp
buketbenek/enzo-e
329a398ce4b11b03a1b2f1aef9e46d04560fe894
[ "BSD-3-Clause" ]
null
null
null
src/Enzo/enzo_EnzoRiemannLUT.hpp
buketbenek/enzo-e
329a398ce4b11b03a1b2f1aef9e46d04560fe894
[ "BSD-3-Clause" ]
null
null
null
// See LICENSE_CELLO file for license and copyright information /// @file enzo_EnzoRiemannUtils.hpp /// @author Matthew Abruzzo ([email protected]) /// @date Thurs May 15 2020 /// @brief [\ref Enzo] Implementation of EnzoRiemannLUTWrapper #ifndef ENZO_ENZO_RIEMANN_LUT_WRAPPER_HPP #define ENZO_ENZO_RIEMANN_LUT_WRAPPER_HPP //---------------------------------------------------------------------- /// @typedef lutarray /// @brief Specialization of std::array to be used to hold enzo_floats /// associated with lookup tables (used with Riemann solvers) template<class LUT> using lutarray = std::array<enzo_float, LUT::num_entries>; //---------------------------------------------------------------------- // Yields a combined token #define COMBINE(prefix, suffix) prefix##suffix #define COMBINE3(first, second, third) first##second##third // Yields a stringized version of the combined token #define STRINGIZE_COMBINE(prefix,suffix) STR_C_1(COMBINE(prefix,suffix)) #define STR_C_1(s) STR_C_2(s) #define STR_C_2(s) #s //---------------------------------------------------------------------- /// @def CREATE_ENUM_VALUE_FORWARDER /// @brief Given an argument, {name}, this macro defines a struct called /// forward_{name} that retrieves the value of the enum member /// called {name} from a given struct/class. If the member is not /// present, indicates a value of minus 1. This implementation is /// loosely inspired by https://stackoverflow.com/a/16000226 #define CREATE_ENUM_VALUE_FORWARDER(name) \ /* Default case: target template doesn't have a member named {name}. */ \ template <typename T, typename = int> \ struct COMBINE(forward_, name) \ {static constexpr int value = -1; }; \ \ /* Specialized case: */ \ template <typename T> \ struct COMBINE(forward_, name) <T, decltype((void) T::name, 0)> \ { static constexpr int value = T::name; } // omit trailing semicolon to avoid -Wpedantic warning //---------------------------------------------------------------------- /// @def LUT_INDEX_FORWARDER_T_SCALAR /// @brief Part of the LUT_INDEX_FORWARDER group of macros that define /// structs for forwarding the values of enum members of a target /// struct/class named for actively advected quantities from /// FIELD_TABLE #define LUT_INDEX_FORWARDER_T_SCALAR(name) CREATE_ENUM_VALUE_FORWARDER(name); #define LUT_INDEX_FORWARDER_T_VECTOR(name) \ CREATE_ENUM_VALUE_FORWARDER(COMBINE(name, _i)); \ CREATE_ENUM_VALUE_FORWARDER(COMBINE(name, _j)); \ CREATE_ENUM_VALUE_FORWARDER(COMBINE(name, _k)); #define LUT_INDEX_FORWARDER_F_SCALAR(name) /* ... */ #define LUT_INDEX_FORWARDER_F_VECTOR(name) /* ... */ namespace LUTIndexForward_ { #define ENTRY(name, math_type, category, if_advection) \ LUT_INDEX_FORWARDER_##if_advection ## _ ## math_type (name) FIELD_TABLE #undef ENTRY // forward number of equations CREATE_ENUM_VALUE_FORWARDER(num_entries); // forward the first index holding specific quantities CREATE_ENUM_VALUE_FORWARDER(specific_start); } //---------------------------------------------------------------------- /// @def WRAPPED_LUT_INDEX_VALUE_T_SCALAR /// @brief Part of the WRAPPED_LUT_INDEX_VALUE group of macros that define /// is used for defining that values of enum members in /// `EnzoRiemannLUTWrapper` by forwarding the enum member values from /// a separate LUT for each of the actively advected quantities from /// FIELD_TABLE #define WRAPPED_LUT_INDEX_VALUE_T_SCALAR(name, LUT) \ name = LUTIndexForward_::COMBINE(forward_, name)<LUT>::value, #define WRAPPED_LUT_INDEX_VALUE_T_VECTOR(name, LUT) \ COMBINE(name,_i) = LUTIndexForward_::COMBINE3(forward_,name,_i)<LUT>::value,\ COMBINE(name,_j) = LUTIndexForward_::COMBINE3(forward_,name,_j)<LUT>::value,\ COMBINE(name,_k) = LUTIndexForward_::COMBINE3(forward_,name,_k)<LUT>::value, #define WRAPPED_LUT_INDEX_VALUE_F_SCALAR(name, LUT) /* ... */ #define WRAPPED_LUT_INDEX_VALUE_F_VECTOR(name, LUT) /* ... */ //---------------------------------------------------------------------- template <typename InputLUT> struct EnzoRiemannLUT{ /// @class EnzoRiemannLUT /// @ingroup Enzo /// @brief [\ref Enzo] Provides a compile-time lookup table that maps the /// components of a subset of the actively advected integration /// quantities from FIELD_TABLE to unique indices /// /// This is a template class that provides the following features at compile /// time: /// - a lookup table (LUT) that maps the names of components of a subset /// of the actively advected integration quantities defined in /// FIELD_TABLE to unique, contiguous indices. /// - the number of quantity components included in the table /// - a way to iterate over just the conserved or specific integration /// quantities values that are stored in an array using these mapping /// - a way to query which of the actively advected integration quantities /// in FIELD_TABLE are not included in the LUT /// /// These feature are provided via the definition of publicly accessible /// integer constants in every specialization of the template class. All /// specializations have: /// - a constant called `num_entries` equal to the number of integration /// quantity components included in the lookup table /// - a constant called `specific_start` equal to the number of components /// of conserved integration quantities included in the lookup table /// - `qkey` constants, which include constants named for the components /// of ALL actively advected integration quantities in FIELD_TABLE. A /// constant associated with a SCALAR quantity, `{qname}`, is simply /// called `{qname}` while constants associated with a vector quantity, /// `{qname}`, are called `{qname}_i`, `{qname}_j`, and `{qname}_k`. /// /// The `qkey` constants serve as both the keys of the lookup table and a /// way to check whether a component of an actively advected quantity is /// included in the table. Their values satisfy the following conditions: /// - All constants named for values corresponding to quantities NOT /// included in the lookup table have values of `-1` /// - All constants named for conserved integration quantities have unique /// integer values in the internal `[0,specific_start)` /// - All constants named for specific integration quantities have unique /// integer values in the interval `[specific_start, num_entries)` /// /// The lookup table is always expected to include density and the 3 velocity /// components. Although it may not be strictly enforced (yet), the lookup /// table is also expected to include either all 3 components of a vector /// quantity or None of them. Additionally, the kth component of a vector /// quantity is expected to have a value that is 1 larger than that of the /// jth component and 2 larger than the ith component, /// /// This template class also provides a handful of helpful static methods to /// programmatically probe the table's contents at runtime and validate that /// the above requirements are specified. /// /// @tparam InputLUT Type that defines the `num_entries` constant, the /// `specific_start` constant, and the `qkey` constants that correspond /// to the actively advected integration quantities that are actually /// included in the lookup table. All of the constant values will be /// directly reused by the resulting template specialization and /// therefore must meet the criteria defined above. Any undefined `qkey` /// constants are assumed to not be included in the lookup table and will /// be defined within the template specialization to have values of `-1`. /// This type can be implemented with either an unscoped enum OR a class /// that includes some combination of publicly accessible unscoped enums /// and static constant member variables. /// /// @par Examples /// For the sake of the example, let's assume we have a type `MyInputLUT` /// that's defined as: /// @code /// struct MyIntLUT { /// enum vals { density=0, velocity_i, velocity_j, velocity_k, /// total_energy, num_entries, specific_start = 1}; /// }; /// @endcode /// To access the index associated with density or the jth component of /// velocity, one would evaluate: /// @code /// int density_index = EnzoRiemannLUT<MyInLUT>::density; //=0 /// int vj_index = EnzoRiemannLUT<MyInLUT>::velocity_j; //=2 /// @endcode /// /// @par /// It makes more sense to talk about the use of this template class when we /// have a companion array. For convenience, the alias template /// `lutarray<LUT>` type is defined. The type, /// `lutarray<EnzoRiemannLUT<InputLUT>>` is an alias of the type /// `std::array<enzo_float, EnzoRiemannLUT<InputLUT>::num_entries>;`. /// /// @par /// As an example, imagine that the total kinetic energy density needs to be /// computed at a single location from the values stored in an array, `integ`, /// of type `lutarray<EnzoRiemannLUT<MyIntLUT>>`. The resulting code to /// do that might look something like: /// @code /// using LUT = EnzoRiemannLUT<MyIntLUT>; /// enzo_float v2 = (integ[LUT::velocity_i] * integ[LUT::velocity_i] + /// integ[LUT::velocity_j] * integ[LUT::velocity_j] + /// integ[LUT::velocity_k] * integ[LUT::velocity_k]); /// enzo_float kinetic = 0.5 * integ[LUT::density] * v2; /// @endcode /// /// @par /// This template class makes it very easy to write generic code that can be /// reused for multiple different lookup table by making the lookup table /// itself into a template argument. Consider the case where a single /// template function is desired to compute the total non-thermal energy /// density at a single location for an arbitrary lookup table. To do this, /// one might write the following code: /// @code /// template <class LUT> /// enzo_float calc_nonthermal_edens(lutarray<LUT> prim) /// { /// enzo_float v2 = (prim[LUT::velocity_i] * prim[LUT::velocity_i] + /// prim[LUT::velocity_j] * prim[LUT::velocity_j] + /// prim[LUT::velocity_k] * prim[LUT::velocity_k]); /// /// enzo_float bi = (LUT::bfield_i >= 0) ? prim[LUT::bfield_i] : 0; /// enzo_float bj = (LUT::bfield_j >= 0) ? prim[LUT::bfield_j] : 0; /// enzo_float bk = (LUT::bfield_k >= 0) ? prim[LUT::bfield_k] : 0; /// enzo_float b2 = bi*bi + bj*bj + bk*bk; /// /// return 0.5(v2*prim[LUT::density] + b2); /// } /// @endcode /// /// @par /// This final example will show the value of grouping the conserved and /// specific integration quantities. To implement some Riemann solvers, it is /// useful to have a generic, reusable function that constructs an array of /// all quantities that are in the lookup table in their conserved form. The /// following function was used to accomplish this at one point /// @code /// template <class LUT> /// lutarray<LUT> compute_conserved(const lutarray<LUT> integr) noexcept /// { /// lutarray<LUT> cons; /// for (std::size_t i = 0; i < LUT::specific_start; i++) { /// cons[i] = integr[i]; /// } /// for (std::size_t i=LUT::specific_start; i<LUT::num_entries; i++){ /// cons[i] = integr[i] * integr[LUT::density]; /// } /// return cons; /// } /// @endcode public: /// initialize the lookup table entries for ever actively advected scalar /// quantity and component of a vector quantity in FIELD_TABLE by forwarding /// values from InputLUT (entries not included in InputLUT default to -1) enum qkey { #define ENTRY(name, math_type, category, if_advection) \ WRAPPED_LUT_INDEX_VALUE_##if_advection##_##math_type (name, InputLUT) FIELD_TABLE #undef ENTRY }; /// The entry with the minimum (non-negative) index corresponding to a /// specific integration quantity. All conserved integration quantity entries /// must have smaller indices (defaults to -1 if not explicitly specified in /// InputLUT) static constexpr std::size_t specific_start = LUTIndexForward_::forward_specific_start<InputLUT>::value; /// The total number of entries in the InputLUT (with non-negative indices). /// (defaults to -1 if not explicitly set in InputLUT) static constexpr std::size_t num_entries = LUTIndexForward_::forward_num_entries<InputLUT>::value; // perform some sanity checks: static_assert(qkey::density >= 0, "InputLUT must have an entry corresponding to density"); static_assert((qkey::velocity_i >= 0 && qkey::velocity_j >= 0 && qkey::velocity_k >= 0), "InputLUT must have entries for each velocity component."); static_assert(specific_start > 0, "InputLUT::specific_start was not set to a positive value"); static_assert(specific_start < num_entries, "InputLUT::num_entries was not set to a value exceeding " "InputLUT::specific_start"); private: /// This is not meant to be constructed. /// /// if it becomes necessary in the future to construct it in the future, /// there is no harm in doing so EnzoRiemannLUT() {} public: //associated static functions /// returns whether the LUT has any bfields static constexpr bool has_bfields(){ return (qkey::bfield_i>=0) || (qkey::bfield_j>=0) || (qkey::bfield_k>=0); } /// for each actively advected scalar integration quantity and component of /// an actively advected vector integration quantity in FIELD_TABLE, this /// passes the associated name and index from the wrapped InputLUT to the /// function `fn` /// /// The function should expect (std::string name, int index). In cases where /// quantites in FIELD_TABLE do not appear in the wrapped InputLUT, an index /// of -1 is passed. template<class Function> static void for_each_entry(Function fn) noexcept; /// a function that performs a check to make sure that the InputLUT satisfies /// all assumptions. If it doesn't, the program aborts (with an Error message) static void validate() noexcept; }; //---------------------------------------------------------------------- /// @def LUT_UNARY_FUNC_T_SCALAR /// @brief Part of the LUT_UNARY_FUNC group of macros that apply a /// unary function to the entries of named for advection related /// quantities in FIELD_TABLE #define LUT_UNARY_FUNC_T_SCALAR(func, LUT, name) func(#name, LUT::name) #define LUT_UNARY_FUNC_T_VECTOR(func, LUT, name) \ func(STRINGIZE_COMBINE(name,_i), LUT::COMBINE(name,_i)); \ func(STRINGIZE_COMBINE(name,_j), LUT::COMBINE(name,_j)); \ func(STRINGIZE_COMBINE(name,_k), LUT::COMBINE(name,_k)) #define LUT_UNARY_FUNC_F_SCALAR(func, LUT, name) /* ... */ #define LUT_UNARY_FUNC_F_VECTOR(func, LUT, name) /* ... */ //---------------------------------------------------------------------- /// template helper function that applies unary function on the enum members of /// a lookup table that have been named for advection related quantities in /// FIELD_TABLE /// @param fn Unary function or that accepts the name of the member and the /// value of the member as arguments template<class LUT> template<class Function> void EnzoRiemannLUT<LUT>::for_each_entry(Function fn) noexcept{ #define ENTRY(name, math_type, category, if_advection) \ LUT_UNARY_FUNC_##if_advection##_##math_type (fn, \ EnzoRiemannLUT<LUT>, \ name); FIELD_TABLE #undef ENTRY } //---------------------------------------------------------------------- template <class InputLUT> void EnzoRiemannLUT<InputLUT>::validate() noexcept { // the elements in the array are default-initialized (they are each "") std::array<std::string, EnzoRiemannLUT<InputLUT>::num_entries> entry_names; // define a lambda function to execute for every member of lut auto fn = [&](std::string name, int index) { if ((index >= 0) && (index >= EnzoRiemannLUT<InputLUT>::num_entries)) { ERROR3("EnzoRiemannLUT<InputLUT>::validate", ("The value of %s, %d, is greater than or equal to " "InputLUT::num_entries, %d"), name.c_str(), index, EnzoRiemannLUT<InputLUT>::num_entries); } else if (index >= 0) { if (entry_names[index] != ""){ ERROR3("EnzoRiemannLUT<InputLUT>::validate", "%s and %s both have values of %d", name.c_str(), entry_names[index], index); } entry_names[index] = name; } }; EnzoRiemannLUT<InputLUT>::for_each_entry(fn); std::size_t max_conserved = 0; std::size_t min_specific = EnzoRiemannLUT<InputLUT>::num_entries; for (std::size_t i = 0; i < entry_names.size(); i++){ std::string name = entry_names[i]; if (name == ""){ ERROR2("EnzoRiemannLUT<InputLUT>::validate", "The value of num_entries, %d, is wrong. There is no entry for " "index %d", (int)EnzoRiemannLUT<InputLUT>::num_entries, (int)i); } std::string quantity = EnzoCenteredFieldRegistry::get_actively_advected_quantity_name(name, true); if (quantity == ""){ ERROR2("EnzoRiemannLUT<InputLUT>::validate", "\"%s\" (at index %d) isn't an actively advected scalar quantity" "or a component of an actively advected vector quantity", name.c_str(), (int)i); } FieldCat category; EnzoCenteredFieldRegistry::quantity_properties(quantity, NULL, &category, NULL); if ((i == 0) && (category != FieldCat::conserved)) { ERROR("EnzoRiemannLUT<InputLUT>::validate", ("the lookup table's entry for index 0 should correspond to a " "conserved quantity")); } else if (((i+1) == entry_names.size()) && (category != FieldCat::specific)) { ERROR("EnzoRiemannLUT<InputLUT>::validate", ("the lookup table's entry for the index InputLUT::num_entries-1 " "should correspond to a specific quantity")); } switch(category){ case FieldCat::conserved : { max_conserved = std::max(max_conserved, i); break; } case FieldCat::specific : { min_specific = std::min(min_specific, i); break; } case FieldCat::other : { ERROR1("EnzoRiemannLUT<InputLUT>::validate", ("%s corresponds to a quantity with FieldCat::other. Quantities " "of this category should not be included in a lookup table."), name.c_str()); } } } // The assumption is that all LUTs contain at least 1 conserved quantity // (nominally density) and at least 1 specific quantity (nominally velocity) if ((max_conserved+1) != min_specific){ ERROR("EnzoRiemannLUT<InputLUT>::validate", ("InputLUT's entries corresponding to conserved quantities are not " "all grouped together at indices smaller than those corresponding " "to specific quantities")); } else if (min_specific != EnzoRiemannLUT<InputLUT>::specific_start) { ERROR2("EnzoRiemannLUT<InputLUT>::validate", "InputLUT's specfic_start value should be set to %d, not %d.", (int)min_specific, (int)EnzoRiemannLUT<InputLUT>::specific_start); } // (It would be faster to include this within the above loop, but this is] // more readable) // verify for actively advected vector quantity, qname, that has components // associated with non-negative values that: // - if InputLUT::{qname}_j >= 0, then it's equal to 1 + InputLUT::{qname}_i // and greater than 0 // - if InputLUT::{qname}_k >= 0, then it's equal to 1 + InputLUT::{qname}_j // and greater than 1 char prev_entry_vector_ax = '\0'; std::string prev_quantity = ""; for (const auto& name : entry_names){ char component; const std::string cur_quantity = EnzoCenteredFieldRegistry::get_actively_advected_quantity_name (name, true, &component); if (component == '\0'){ // name isn't a component of a vector prev_entry_vector_ax = '\0'; prev_quantity = ""; // we intentionally use an empty string } else { if ( (component == 'j') && ((cur_quantity != prev_quantity) || (prev_entry_vector_ax != 'i')) ){ ERROR2("EnzoRiemannLUT<InputLUT>::validate", "\"%s_j\" is expected to have an index that is 1 greater than " "the index of \"%s_i\".", cur_quantity.c_str(), cur_quantity.c_str()); } else if ( (component == 'k') && ((cur_quantity != prev_quantity) || (prev_entry_vector_ax != 'j')) ){ ERROR2("EnzoRiemannLUT<InputLUT>::validate", "\"%s_k\" is expected to have an index that is 1 greater than " "the index of \"%s_j\".", cur_quantity.c_str(), cur_quantity.c_str()); } prev_entry_vector_ax = component; prev_quantity = cur_quantity; } } } #endif /* ENZO_ENZO_RIEMANN_LUT_WRAPPER_HPP */
46.939457
80
0.618262
buketbenek
a86e86e5c4401366713810ee099c099e47b96948
3,007
cpp
C++
examples/stackedfm.cpp
vlazzarini/aurora
4990d81a6873beace4a39d6584cc77afbda82cf4
[ "BSD-3-Clause" ]
11
2021-11-26T16:23:40.000Z
2022-01-19T21:36:35.000Z
examples/stackedfm.cpp
vlazzarini/aurora
4990d81a6873beace4a39d6584cc77afbda82cf4
[ "BSD-3-Clause" ]
null
null
null
examples/stackedfm.cpp
vlazzarini/aurora
4990d81a6873beace4a39d6584cc77afbda82cf4
[ "BSD-3-Clause" ]
null
null
null
// stackedfm.cpp: // Stacked FM example // // (c) V Lazzarini, 2021 // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE #include "Osc.h" #include <cstdlib> #include <iostream> namespace Aurora { inline double scl(double a, double b) { return a * b; } inline double mix(double a, double b) { return a + b; } template <typename S> class StackedFM { Osc<S> mod0; Osc<S> mod1; Osc<S> car; BinOp<S, scl> amp; BinOp<S, mix> add; public: StackedFM(S fs = (S)def_sr, std::size_t vsize = def_vsize) : mod0(fs, vsize), mod1(fs, vsize), car(fs, vsize), amp(vsize), add(vsize){}; std::size_t vsize() { return car.vsize(); } S fs() { return car.fs(); } const std::vector<S> &operator()(S a, S fc, S fm0, S fm1, S z0, S z1, std::size_t vsiz = 0) { if (vsiz) mod0.vsize(vsiz); auto &s0 = add(fm1, mod0(z0 * fm0, fm0)); auto &s1 = add(fc, mod1(amp(z1, s0), s0)); return car(a, s1); } }; } // namespace Aurora int main(int argc, const char *argv[]) { if (argc > 3) { double sr = argc > 4 ? std::atof(argv[4]) : Aurora::def_sr; auto dur = std::atof(argv[1]); auto amp = std::atof(argv[2]); auto fr = std::atof(argv[3]); Aurora::StackedFM<double> fm(sr); for (int n = 0; n < fm.fs() * dur; n += fm.vsize()) { const std::vector<double> &out = fm(amp, fr, fr, fr, 3, 2); for (auto s : out) std::cout << s << std::endl; } } else std::cout << "usage: " << argv[0] << " dur(s) amp freq(Hz) [sr]" << std::endl; return 0; }
37.123457
80
0.663785
vlazzarini
a870b58f24e926981982fe06011b886bee7bf558
9,897
cpp
C++
mps/src/v20190612/model/MediaVideoStreamItem.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
mps/src/v20190612/model/MediaVideoStreamItem.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
mps/src/v20190612/model/MediaVideoStreamItem.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/mps/v20190612/model/MediaVideoStreamItem.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Mps::V20190612::Model; using namespace std; MediaVideoStreamItem::MediaVideoStreamItem() : m_bitrateHasBeenSet(false), m_heightHasBeenSet(false), m_widthHasBeenSet(false), m_codecHasBeenSet(false), m_fpsHasBeenSet(false), m_colorPrimariesHasBeenSet(false), m_colorSpaceHasBeenSet(false), m_colorTransferHasBeenSet(false), m_hdrTypeHasBeenSet(false) { } CoreInternalOutcome MediaVideoStreamItem::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Bitrate") && !value["Bitrate"].IsNull()) { if (!value["Bitrate"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.Bitrate` IsInt64=false incorrectly").SetRequestId(requestId)); } m_bitrate = value["Bitrate"].GetInt64(); m_bitrateHasBeenSet = true; } if (value.HasMember("Height") && !value["Height"].IsNull()) { if (!value["Height"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.Height` IsInt64=false incorrectly").SetRequestId(requestId)); } m_height = value["Height"].GetInt64(); m_heightHasBeenSet = true; } if (value.HasMember("Width") && !value["Width"].IsNull()) { if (!value["Width"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.Width` IsInt64=false incorrectly").SetRequestId(requestId)); } m_width = value["Width"].GetInt64(); m_widthHasBeenSet = true; } if (value.HasMember("Codec") && !value["Codec"].IsNull()) { if (!value["Codec"].IsString()) { return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.Codec` IsString=false incorrectly").SetRequestId(requestId)); } m_codec = string(value["Codec"].GetString()); m_codecHasBeenSet = true; } if (value.HasMember("Fps") && !value["Fps"].IsNull()) { if (!value["Fps"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.Fps` IsInt64=false incorrectly").SetRequestId(requestId)); } m_fps = value["Fps"].GetInt64(); m_fpsHasBeenSet = true; } if (value.HasMember("ColorPrimaries") && !value["ColorPrimaries"].IsNull()) { if (!value["ColorPrimaries"].IsString()) { return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.ColorPrimaries` IsString=false incorrectly").SetRequestId(requestId)); } m_colorPrimaries = string(value["ColorPrimaries"].GetString()); m_colorPrimariesHasBeenSet = true; } if (value.HasMember("ColorSpace") && !value["ColorSpace"].IsNull()) { if (!value["ColorSpace"].IsString()) { return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.ColorSpace` IsString=false incorrectly").SetRequestId(requestId)); } m_colorSpace = string(value["ColorSpace"].GetString()); m_colorSpaceHasBeenSet = true; } if (value.HasMember("ColorTransfer") && !value["ColorTransfer"].IsNull()) { if (!value["ColorTransfer"].IsString()) { return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.ColorTransfer` IsString=false incorrectly").SetRequestId(requestId)); } m_colorTransfer = string(value["ColorTransfer"].GetString()); m_colorTransferHasBeenSet = true; } if (value.HasMember("HdrType") && !value["HdrType"].IsNull()) { if (!value["HdrType"].IsString()) { return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.HdrType` IsString=false incorrectly").SetRequestId(requestId)); } m_hdrType = string(value["HdrType"].GetString()); m_hdrTypeHasBeenSet = true; } return CoreInternalOutcome(true); } void MediaVideoStreamItem::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_bitrateHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Bitrate"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_bitrate, allocator); } if (m_heightHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Height"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_height, allocator); } if (m_widthHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Width"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_width, allocator); } if (m_codecHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Codec"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_codec.c_str(), allocator).Move(), allocator); } if (m_fpsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Fps"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_fps, allocator); } if (m_colorPrimariesHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ColorPrimaries"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_colorPrimaries.c_str(), allocator).Move(), allocator); } if (m_colorSpaceHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ColorSpace"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_colorSpace.c_str(), allocator).Move(), allocator); } if (m_colorTransferHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ColorTransfer"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_colorTransfer.c_str(), allocator).Move(), allocator); } if (m_hdrTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "HdrType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_hdrType.c_str(), allocator).Move(), allocator); } } int64_t MediaVideoStreamItem::GetBitrate() const { return m_bitrate; } void MediaVideoStreamItem::SetBitrate(const int64_t& _bitrate) { m_bitrate = _bitrate; m_bitrateHasBeenSet = true; } bool MediaVideoStreamItem::BitrateHasBeenSet() const { return m_bitrateHasBeenSet; } int64_t MediaVideoStreamItem::GetHeight() const { return m_height; } void MediaVideoStreamItem::SetHeight(const int64_t& _height) { m_height = _height; m_heightHasBeenSet = true; } bool MediaVideoStreamItem::HeightHasBeenSet() const { return m_heightHasBeenSet; } int64_t MediaVideoStreamItem::GetWidth() const { return m_width; } void MediaVideoStreamItem::SetWidth(const int64_t& _width) { m_width = _width; m_widthHasBeenSet = true; } bool MediaVideoStreamItem::WidthHasBeenSet() const { return m_widthHasBeenSet; } string MediaVideoStreamItem::GetCodec() const { return m_codec; } void MediaVideoStreamItem::SetCodec(const string& _codec) { m_codec = _codec; m_codecHasBeenSet = true; } bool MediaVideoStreamItem::CodecHasBeenSet() const { return m_codecHasBeenSet; } int64_t MediaVideoStreamItem::GetFps() const { return m_fps; } void MediaVideoStreamItem::SetFps(const int64_t& _fps) { m_fps = _fps; m_fpsHasBeenSet = true; } bool MediaVideoStreamItem::FpsHasBeenSet() const { return m_fpsHasBeenSet; } string MediaVideoStreamItem::GetColorPrimaries() const { return m_colorPrimaries; } void MediaVideoStreamItem::SetColorPrimaries(const string& _colorPrimaries) { m_colorPrimaries = _colorPrimaries; m_colorPrimariesHasBeenSet = true; } bool MediaVideoStreamItem::ColorPrimariesHasBeenSet() const { return m_colorPrimariesHasBeenSet; } string MediaVideoStreamItem::GetColorSpace() const { return m_colorSpace; } void MediaVideoStreamItem::SetColorSpace(const string& _colorSpace) { m_colorSpace = _colorSpace; m_colorSpaceHasBeenSet = true; } bool MediaVideoStreamItem::ColorSpaceHasBeenSet() const { return m_colorSpaceHasBeenSet; } string MediaVideoStreamItem::GetColorTransfer() const { return m_colorTransfer; } void MediaVideoStreamItem::SetColorTransfer(const string& _colorTransfer) { m_colorTransfer = _colorTransfer; m_colorTransferHasBeenSet = true; } bool MediaVideoStreamItem::ColorTransferHasBeenSet() const { return m_colorTransferHasBeenSet; } string MediaVideoStreamItem::GetHdrType() const { return m_hdrType; } void MediaVideoStreamItem::SetHdrType(const string& _hdrType) { m_hdrType = _hdrType; m_hdrTypeHasBeenSet = true; } bool MediaVideoStreamItem::HdrTypeHasBeenSet() const { return m_hdrTypeHasBeenSet; }
27.722689
153
0.682025
suluner
a8764ec99f69dcf8e96cdfb694ae72a5c9e31b59
1,107
cpp
C++
Source/Services/TitleStorage/title_storage_blob_result.cpp
blgrossMS/xbox-live-api
17c586336e11f0fa3a2a3f3acd665b18c5487b24
[ "MIT" ]
2
2021-07-17T13:34:20.000Z
2022-01-09T00:55:51.000Z
Source/Services/TitleStorage/title_storage_blob_result.cpp
blgrossMS/xbox-live-api
17c586336e11f0fa3a2a3f3acd665b18c5487b24
[ "MIT" ]
null
null
null
Source/Services/TitleStorage/title_storage_blob_result.cpp
blgrossMS/xbox-live-api
17c586336e11f0fa3a2a3f3acd665b18c5487b24
[ "MIT" ]
1
2018-11-18T08:32:40.000Z
2018-11-18T08:32:40.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "xsapi/title_storage.h" NAMESPACE_MICROSOFT_XBOX_SERVICES_TITLE_STORAGE_CPP_BEGIN title_storage_blob_result::title_storage_blob_result() { } title_storage_blob_result::title_storage_blob_result( _In_ std::shared_ptr<std::vector<unsigned char>> blobBuffer, _In_ title_storage_blob_metadata blobMetadata ) : m_blobBuffer(blobBuffer), m_blobMetadata(std::move(blobMetadata)) { } std::shared_ptr<std::vector<unsigned char>> const title_storage_blob_result::blob_buffer() const { return m_blobBuffer; } const title_storage_blob_metadata& title_storage_blob_result::blob_metadata() const { return m_blobMetadata; } NAMESPACE_MICROSOFT_XBOX_SERVICES_TITLE_STORAGE_CPP_END
27.675
64
0.707317
blgrossMS
a87c3784001508ab174db2c836a7b2647d2e98b0
1,212
ipp
C++
ThirdParty/oglplus-develop/implement/oglplus/enums/ext/compat_client_attrib_group_range.ipp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
24
2015-01-31T15:30:49.000Z
2022-01-29T08:36:42.000Z
ThirdParty/oglplus-develop/implement/oglplus/enums/ext/compat_client_attrib_group_range.ipp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
4
2015-08-21T02:29:15.000Z
2020-05-02T13:50:36.000Z
ThirdParty/oglplus-develop/implement/oglplus/enums/ext/compat_client_attrib_group_range.ipp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
9
2015-06-08T22:04:15.000Z
2021-08-16T03:52:11.000Z
/* * .file oglplus/enums/ext/compat_client_attrib_group_range.ipp * * Automatically generated header file. DO NOT modify manually, * edit 'source/enums/oglplus/ext/compat_client_attrib_group.txt' instead. * * Copyright 2010-2013 Matus Chochlik. 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) */ namespace enums { OGLPLUS_LIB_FUNC aux::CastIterRange< const GLbitfield*, CompatibilityClientAttributeGroup > ValueRange_(CompatibilityClientAttributeGroup*) #if (!OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY)) && \ !defined(OGLPLUS_IMPL_EVR_COMPATIBILITYCLIENTATTRIBUTEGROUP) #define OGLPLUS_IMPL_EVR_COMPATIBILITYCLIENTATTRIBUTEGROUP { static const GLbitfield _values[] = { #if defined GL_CLIENT_VERTEX_ARRAY_BIT GL_CLIENT_VERTEX_ARRAY_BIT, #endif #if defined GL_CLIENT_PIXEL_STORE_BIT GL_CLIENT_PIXEL_STORE_BIT, #endif #if defined GL_CLIENT_ALL_ATTRIB_BITS GL_CLIENT_ALL_ATTRIB_BITS, #endif 0 }; return aux::CastIterRange< const GLbitfield*, CompatibilityClientAttributeGroup >(_values, _values+sizeof(_values)/sizeof(_values[0])-1); } #else ; #endif } // namespace enums
28.186047
75
0.808581
vif
a880e6c33081304e5af2743506785dcbeb227880
1,423
cpp
C++
src/isPaADescendantOfPb.cpp
buaazhouxingyu/topoana
50a235614efe48cc17d9691c3cc150564e6e60f7
[ "MIT" ]
15
2020-01-13T01:30:14.000Z
2022-01-17T03:22:34.000Z
src/isPaADescendantOfPb.cpp
buaazhouxingyu/topoana
50a235614efe48cc17d9691c3cc150564e6e60f7
[ "MIT" ]
5
2019-06-01T13:38:44.000Z
2021-06-19T09:26:12.000Z
src/isPaADescendantOfPb.cpp
buaazhouxingyu/topoana
50a235614efe48cc17d9691c3cc150564e6e60f7
[ "MIT" ]
9
2019-06-01T10:19:25.000Z
2022-01-10T15:00:21.000Z
#include "../include/topoana.h" #include <iostream> #include <cstdlib> bool topoana::isPaADescendantOfPb(vector<int> vMidx, int idxA, int idxB) { if(idxA<0||((unsigned int) idxA)>=vMidx.size()) { cerr<<"Error: The integer \"idxA\" is not a reasonable index for the vector \"vMidx\"!"<<endl; cerr<<"Infor: The integer \"idxA\" is "<<idxA<<"."<<endl; cerr<<"Infor: The size of the vector \"vMidx\" is "<<vMidx.size()<<"."<<endl; cerr<<"Infor: Please check them."<<endl; exit(-1); } if(idxB<0||((unsigned int) idxB)>=vMidx.size()) { cerr<<"Error: The integer \"idxB\" is not a reasonable index for the vector \"vMidx\"!"<<endl; cerr<<"Infor: The integer \"idxB\" is "<<idxB<<"."<<endl; cerr<<"Infor: The size of the vector \"vMidx\" is "<<vMidx.size()<<"."<<endl; cerr<<"Infor: Please check them."<<endl; exit(-1); } if(idxA<idxB) { cerr<<"Error: The integer \"idxA\" is less than the integer \"idxB\"!"<<endl; cerr<<"Infor: The integer \"idxA\" is "<<idxA<<"."<<endl; cerr<<"Infor: The integer \"idxB\" is "<<idxB<<"."<<endl; cerr<<"Infor: The integer \"idxA\" should be greater than the integer \"idxB\"!"<<endl; cerr<<"Infor: Please check them."<<endl; exit(-1); } while(vMidx[idxA]!=idxA) { if(vMidx[idxA]==idxB) return true; else idxA=vMidx[idxA]; } return false; }
33.093023
100
0.574842
buaazhouxingyu
a88bb60b8cfba4c5329201301f9d32e310f9cfef
2,725
cc
C++
tests/semaphore_unit_test.cc
boboxxd/DelayQueueCpp
b6e7d0271122932e7d947973048bae4a4769aa3c
[ "Apache-2.0" ]
5
2020-11-10T00:07:35.000Z
2022-02-08T06:27:13.000Z
tests/semaphore_unit_test.cc
boboxxd/DelayQueueCpp
b6e7d0271122932e7d947973048bae4a4769aa3c
[ "Apache-2.0" ]
null
null
null
tests/semaphore_unit_test.cc
boboxxd/DelayQueueCpp
b6e7d0271122932e7d947973048bae4a4769aa3c
[ "Apache-2.0" ]
3
2021-02-07T07:16:29.000Z
2021-06-18T01:28:07.000Z
// Copyright (c) 2020 Xi Cheng. All rights reserved. // Use of this source code is governed by a Apache License 2.0 that can be // found in the LICENSE file. #include <atomic> #include <chrono> #include <thread> #include "gtest/gtest.h" #include "src/semaphore.h" class SemaphoreUnitTest : public ::testing::Test { }; // Initialize a semaphore with count 1, and verify that wait won't block TEST_F(SemaphoreUnitTest, InitCountAsOneAndSingleWait) { Semaphore semaphore(1); semaphore.Wait(); } // Initialize a sempahore with count 0, and wait until a timeout TEST_F(SemaphoreUnitTest, InitCountAsZeroAndSingleWaitUntil) { Semaphore sempahore; // Set the timeout duration to be 1 second auto now = std::chrono::high_resolution_clock::now(); auto wait_duration = std::chrono::milliseconds(1000); // Because there is only one thread and because the count is initialized as // zero, we expect WaitUntil to timeout and therefore return false EXPECT_FALSE(sempahore.WaitUntil(now + wait_duration)); // Just some sanity check on the time that elapses auto now2 = std::chrono::high_resolution_clock::now(); EXPECT_TRUE(now2 - now >= wait_duration); } // A rather simple multi-threaded case that one thread runs as producer which // notifies and the other runs as a consumer which wait on the semaphore // Repeat this exercise for 100 times TEST_F(SemaphoreUnitTest, InitCountAsOneAndOneWaitAndOneNotify) { Semaphore semaphore; for (int i = 0; i < 100; i++) { auto producer_thread(std::thread([&semaphore] () { semaphore.Notify(); })); auto consumer_thread(std::thread([&semaphore] () { semaphore.Wait(); })); // We expect both threads to complete so join should return successfully producer_thread.join(); consumer_thread.join(); } } // Initialize a semaphore with a count of 10, and have 20 consumer threads to // wait on this semaphore. 10 of them returns immediately and the remaining // 10 timeout TEST_F(SemaphoreUnitTest, InitCountAsTenWithTwentyConsumers) { Semaphore semaphore(10); std::atomic<int> timeouts{0}; auto const wait_duration = std::chrono::milliseconds(1000); std::vector<std::thread> threads; for (int i = 0; i < 20; i++) { threads.push_back(std::thread([&semaphore, &wait_duration, &timeouts] () { auto now = std::chrono::high_resolution_clock::now(); auto wait_result = semaphore.WaitUntil(now + wait_duration); // Increment the timeouts counter if a consumer thread times out on wait if (!wait_result) { timeouts++; } })); } // Join the threads and clear the placeholder for threads for (auto& t : threads) { t.join(); } threads.clear(); EXPECT_EQ(timeouts.load(), 10); }
34.493671
79
0.714862
boboxxd
a8920ba644c3c9ba7d729fa7f8da6344aabc0ee8
3,099
hpp
C++
classdef/ObjectRoot.hpp
dwringer/a3system
b14f8992542c2c3c38c9b87644f2c5d7249affda
[ "MIT" ]
3
2016-10-31T21:05:20.000Z
2017-08-15T14:00:05.000Z
classdef/ObjectRoot.hpp
dwringer/ANIMA
a8813dbac158d05bea5d9a9c882567446caf48c3
[ "MIT" ]
null
null
null
classdef/ObjectRoot.hpp
dwringer/ANIMA
a8813dbac158d05bea5d9a9c882567446caf48c3
[ "MIT" ]
null
null
null
/* ObjectRoot class :: ObjectRoot -> nil Methods: _setf var_name value :: set variable in obj namespace and record key _getf var_name :: simple getVariable interface _push_attr var_name value :: append to an array variable _locals :: list of all recorded keys that have been stored _class :: show object's class hierarchy array This class is meant to act as the root of an object hierarchy, providing a standard interface for keeping instance variables in a namespace unique to each instance. This is just a thin layer of abstraction over the built-in setVariable and getVariable functions (which are already object-oriented in nature and provide a simple way of bootstrapping on top of the engine). Example: Obj = ["ObjectRoot"] call fnc_new; [Obj, "_setf", "a key", "associated data"] call fnc_tell; hint str ([Obj, "_getf", "a key"] call fnc_tell) // ... outputs "associated data" hint str ([Obj, "_locals"] call fnc_tell) // ... outputs ["a key"] Subclass example: ["ANewClass", ["_self"], { [_self, "ObjectRoot"] call fnc_instance; ... rest of init ... } call fnc_lambda] call fnc_class; w/macros: DEFCLASS("HeaderDefinedClass") ["_self"] DO { SUPER("ObjectRoot", _self); ... rest of init ... } ENDCLASS; */ DEFCLASS("ObjectRoot") ["_self"] DO { /* Initialize base object class instance */ _self setVariable ["__locals__", []]; _self } ENDCLASS; DEFMETHOD("ObjectRoot", "_setf") ["_self", "_var_name", "_value"] DO { /* Set value of a local variable */ private ["_locals"]; _locals = _self getVariable "__locals__"; if (not isNil "_value") then { if (({_x == _var_name} count _locals) == 0) then { _locals pushBack _var_name; }; _self setVariable [_var_name, _value]; } else { if (({_x == _var_name} count _locals) > 0) then { _locals = _locals - [_var_name]; }; _self setVariable [_var_name, nil]; }; _self setVariable ["__locals__", _locals]; } ENDMETHOD; DEFMETHOD("ObjectRoot", "_getf") ["_self", "_var_name"] DO { /* Get value of a local variable */ _self getVariable [_var_name, nil] } ENDMETHOD; DEFMETHOD("ObjectRoot", "_locals") ["_self"] DO { /* Return list of locally stored variable names */ _self getVariable "__locals__" } ENDMETHOD; ///////////////////////////////// TEST //////////////////////////////////////// DEFMETHOD("ObjectRoot", "_push_attr") ["_self", "_attribute", "_value"] DO { /* Append a value to attribute variable that is an array */ _self setVariable [_attribute, (_self getVariable _attribute) + [_value]]; // [_self, "_setf", _attribute, // ([_self, "_getf", _attribute] call fnc_tell) + // [_value]] call fnc_tell } ENDMETHOD; ///////////////////////////////// TEST //////////////////////////////////////// DEFMETHOD("ObjectRoot", "_class") ["_self"] DO { /* Return the class hierarchy for an instance */ _self getVariable "class_names" } ENDMETHOD;
32.621053
79
0.611488
dwringer
a89574102e7d1798c0f51304b552e553df5864df
1,700
cpp
C++
ema-tools/find-rigid-coil-vertex-correspondence/src/bin/main.cpp
ahewer/mri-shape-tools
4268499948f1330b983ffcdb43df62e38ca45079
[ "MIT" ]
null
null
null
ema-tools/find-rigid-coil-vertex-correspondence/src/bin/main.cpp
ahewer/mri-shape-tools
4268499948f1330b983ffcdb43df62e38ca45079
[ "MIT" ]
2
2017-05-29T09:43:01.000Z
2017-05-29T09:50:05.000Z
ema-tools/find-rigid-coil-vertex-correspondence/src/bin/main.cpp
ahewer/mri-shape-tools
4268499948f1330b983ffcdb43df62e38ca45079
[ "MIT" ]
4
2017-05-17T11:56:02.000Z
2022-03-05T09:12:24.000Z
#include "mesh/MeshIO.h" #include "ema/Ema.h" #include "settings.h" #include "CorrespondenceSubsetFinder.h" #include "CorrespondenceSubsetFinderBuilder.h" #include "VertexSubsets.h" #include "OutputResult.h" int main(int argc, char* argv[]) { Settings settings(argc, argv); Mesh mesh = MeshIO::read(settings.mesh); Ema ema; ema.read().from(settings.emaFile); ema.reduce_coil_set().to(settings.channels); ema.transform_all_coils().scale(settings.scaleFactor); std::vector<arma::vec> emaData; for(const std::string& coilName: settings.channels) { ema.coil(coilName).boundary().change_size(1); ema.coil(coilName).mirror().positions(); emaData.push_back( ema.coil(coilName).interpolate().position_at_time(settings.timeStamp)); } // read subsets auto subset = VertexSubsets::read_from(settings.subsets); // find correspondences and record energy std::vector<unsigned int> vertexIndices; double energy; CorrespondenceSubsetFinderBuilder() \ .set_ema_data(emaData) \ .set_energy_settings(settings.energySettings) \ .set_minimizer_settings(settings.minimizerSettings) \ .set_mesh(mesh) \ .set_subsets(subset) \ .set_partition_index(settings.partitionIndex) \ .set_partition_amount(settings.partitionAmount) \ .build() \ .find_best_correspondence() \ .get_best_correspondence(vertexIndices) \ .get_best_energy(energy); // output result OutputResult() \ .set_vertex_indices(vertexIndices) \ .set_ema_channels(settings.channels) \ .set_energy(energy) \ .set_partition_amount(settings.partitionAmount) \ .set_partition_index(settings.partitionIndex) \ .write(settings.outputFile); }
27.419355
94
0.731765
ahewer
a89d419de02d737fbdb96d5cb9e63a37bb25c9a1
2,825
cpp
C++
src/test_hdf5.cpp
uwmri/mri_recon
c74780d56c87603fb935744bf312e8c59d415997
[ "BSD-3-Clause" ]
null
null
null
src/test_hdf5.cpp
uwmri/mri_recon
c74780d56c87603fb935744bf312e8c59d415997
[ "BSD-3-Clause" ]
2
2020-11-06T19:45:34.000Z
2020-11-07T03:22:25.000Z
src/test_hdf5.cpp
uwmri/mri_recon
c74780d56c87603fb935744bf312e8c59d415997
[ "BSD-3-Clause" ]
null
null
null
#include "recon_lib.h" using namespace NDarray; using namespace std; int main(void) { // Write Section { HDF5 file = HDF5("TEST.h5", "w"); Array<float, 3> TEMP(2, 3, 4, ColumnMajorArray<3>()); Array<complex<float>, 3> TEMPC(4, 3, 2, ColumnMajorArray<3>()); Array<short, 3> TEMPS(2, 3, 4, ColumnMajorArray<3>()); for (int k = 0; k < TEMPC.length(thirdDim); k++) { for (int j = 0; j < TEMPC.length(secondDim); j++) { for (int i = 0; i < TEMPC.length(firstDim); i++) { TEMPC(i, j, k) = complex<float>(10 * k + j, i); } } } for (int k = 0; k < TEMP.length(thirdDim); k++) { for (int j = 0; j < TEMP.length(secondDim); j++) { for (int i = 0; i < TEMP.length(firstDim); i++) { TEMP(i, j, k) = 100 * k + 10 * j + i; TEMPS(i, j, k) = 100 * k + 10 * j + i - 2; } } } cout << "Exporting Attributes" << endl; int A = 10; float B = 3.14156; string C = "Super"; file.AddH5Scaler("Kdata", "A", A); file.AddH5Scaler("Kdata", "B", B); file.AddH5Char("Kdata", "C", C.c_str()); file.AddH5Array("Kdata", "D", TEMP); file.AddH5Array("Kdata", "E", TEMPC); file.AddH5Array("Kdata", "F", TEMPS); } // Write Section { HDF5 file = HDF5("TEST.h5", "r"); cout << "Reading Attributes" << endl; int A; float B; std::string C; file.ReadH5Scaler("Kdata", "A", &A); cout << "A = " << A << endl << flush; file.ReadH5Scaler("Kdata", "B", &B); cout << "B = " << B << endl << flush; file.ReadH5Char("Kdata", "C", C); cout << "C = " << C << endl << flush; Array<float, 3> TEMP(3, 3, 3); file.ReadH5Array("Kdata", "D", TEMP); for (int k = 0; k < TEMP.length(thirdDim); k++) { for (int j = 0; j < TEMP.length(secondDim); j++) { for (int i = 0; i < TEMP.length(firstDim); i++) { cout << "k=" << k << ",j=" << j << ",i=" << i << " = " << TEMP(i, j, k) << endl; } } } Array<complex<float>, 3> TEMPC; file.ReadH5Array("Kdata", "E", TEMPC); for (int k = 0; k < TEMPC.length(thirdDim); k++) { for (int j = 0; j < TEMPC.length(secondDim); j++) { for (int i = 0; i < TEMPC.length(firstDim); i++) { cout << "k=" << k << ",j=" << j << ",i=" << i << " = " << TEMPC(i, j, k) << endl; } } } Array<short, 3> TEMPF; file.ReadH5Array("Kdata", "F", TEMPF); for (int k = 0; k < TEMPF.length(thirdDim); k++) { for (int j = 0; j < TEMPF.length(secondDim); j++) { for (int i = 0; i < TEMPF.length(firstDim); i++) { cout << "k=" << k << ",j=" << j << ",i=" << i << " = " << TEMPF(i, j, k) << endl; } } } } return 0; }
27.163462
67
0.458761
uwmri
a8a1f8e567cd88425fd2864cba0cfaf5017f967a
3,395
cpp
C++
examples/07_BLE/BLE_write/lib/BLE/BLEServiceMap.cpp
MelihOzbk/deneyapkart-platformio-core
c0fbc8ffa181ee22e597569b24bde5a011ccaaa4
[ "Apache-2.0" ]
17
2021-07-28T21:57:26.000Z
2022-02-28T20:32:04.000Z
esp-at/libraries/BLE/src/BLEServiceMap.cpp
PowerfulCat/Works
94b729ee2afd14a5fde03ea94f826e0b98b80dcf
[ "MIT" ]
7
2021-08-07T23:20:14.000Z
2022-03-20T15:05:21.000Z
esp-at/libraries/BLE/src/BLEServiceMap.cpp
PowerfulCat/Works
94b729ee2afd14a5fde03ea94f826e0b98b80dcf
[ "MIT" ]
10
2021-08-11T13:47:36.000Z
2022-03-26T02:41:45.000Z
/* * BLEServiceMap.cpp * * Created on: Jun 22, 2017 * Author: kolban */ #include "sdkconfig.h" #if defined(CONFIG_BT_ENABLED) #include <stdio.h> #include <iomanip> #include "BLEService.h" /** * @brief Return the service by UUID. * @param [in] UUID The UUID to look up the service. * @return The characteristic. */ BLEService* BLEServiceMap::getByUUID(const char* uuid) { return getByUUID(BLEUUID(uuid)); } /** * @brief Return the service by UUID. * @param [in] UUID The UUID to look up the service. * @return The characteristic. */ BLEService* BLEServiceMap::getByUUID(BLEUUID uuid, uint8_t inst_id) { for (auto &myPair : m_uuidMap) { if (myPair.first->getUUID().equals(uuid)) { return myPair.first; } } //return m_uuidMap.at(uuid.toString()); return nullptr; } // getByUUID /** * @brief Return the service by handle. * @param [in] handle The handle to look up the service. * @return The service. */ BLEService* BLEServiceMap::getByHandle(uint16_t handle) { return m_handleMap.at(handle); } // getByHandle /** * @brief Set the service by UUID. * @param [in] uuid The uuid of the service. * @param [in] characteristic The service to cache. * @return N/A. */ void BLEServiceMap::setByUUID(BLEUUID uuid, BLEService* service) { m_uuidMap.insert(std::pair<BLEService*, std::string>(service, uuid.toString())); } // setByUUID /** * @brief Set the service by handle. * @param [in] handle The handle of the service. * @param [in] service The service to cache. * @return N/A. */ void BLEServiceMap::setByHandle(uint16_t handle, BLEService* service) { m_handleMap.insert(std::pair<uint16_t, BLEService*>(handle, service)); } // setByHandle /** * @brief Return a string representation of the service map. * @return A string representation of the service map. */ std::string BLEServiceMap::toString() { std::string res; char hex[5]; for (auto &myPair: m_handleMap) { res += "handle: 0x"; snprintf(hex, sizeof(hex), "%04x", myPair.first); res += hex; res += ", uuid: " + myPair.second->getUUID().toString() + "\n"; } return res; } // toString void BLEServiceMap::handleGATTServerEvent( esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param) { // Invoke the handler for every Service we have. for (auto &myPair : m_uuidMap) { myPair.first->handleGATTServerEvent(event, gatts_if, param); } } /** * @brief Get the first service in the map. * @return The first service in the map. */ BLEService* BLEServiceMap::getFirst() { m_iterator = m_uuidMap.begin(); if (m_iterator == m_uuidMap.end()) return nullptr; BLEService* pRet = m_iterator->first; m_iterator++; return pRet; } // getFirst /** * @brief Get the next service in the map. * @return The next service in the map. */ BLEService* BLEServiceMap::getNext() { if (m_iterator == m_uuidMap.end()) return nullptr; BLEService* pRet = m_iterator->first; m_iterator++; return pRet; } // getNext /** * @brief Removes service from maps. * @return N/A. */ void BLEServiceMap::removeService(BLEService* service) { m_handleMap.erase(service->getHandle()); m_uuidMap.erase(service); } // removeService /** * @brief Returns the amount of registered services * @return amount of registered services */ int BLEServiceMap::getRegisteredServiceCount(){ return m_handleMap.size(); } #endif /* CONFIG_BT_ENABLED */
24.601449
81
0.693078
MelihOzbk
a8a7066949366a04cb2241d22dc414ca03c1cb48
782
cpp
C++
ablateLibrary/domain/region.cpp
UBCHREST/ablate
02a5b390ba4e257b96bd19f4604c269598dccd9d
[ "BSD-3-Clause" ]
3
2021-01-19T21:29:10.000Z
2021-08-20T19:54:49.000Z
ablateLibrary/domain/region.cpp
UBCHREST/ablate
02a5b390ba4e257b96bd19f4604c269598dccd9d
[ "BSD-3-Clause" ]
124
2021-01-14T15:30:48.000Z
2022-03-28T14:44:31.000Z
ablateLibrary/domain/region.cpp
UBCHREST/ablate
02a5b390ba4e257b96bd19f4604c269598dccd9d
[ "BSD-3-Clause" ]
17
2021-02-10T22:34:57.000Z
2022-03-21T18:46:06.000Z
#include "region.hpp" #include <algorithm> #include <functional> ablate::domain::Region::Region(std::string name, std::vector<int> valuesIn) : name(name), values(valuesIn.empty() ? valuesIn : std::vector<int>{1}) { // sort the values std::sort(values.begin(), values.end()); // Create a unique string auto hashString = name; for (const auto& value : values) { hashString += "," + std::to_string(value); } id = std::hash<std::string>()(hashString); } #include "parser/registrar.hpp" REGISTERDEFAULT(ablate::domain::Region, ablate::domain::Region, "The region in which this solver applies (Label & Values)", ARG(std::string, "name", "the label name"), OPT(std::vector<int>, "values", "the values on the label (default is 1)"));
37.238095
167
0.648338
UBCHREST
a8a84ec6b2d6731049af178e48b57c0ed74bf879
57,757
cpp
C++
src/stm32_sd.cpp
andreili/STM32F4
9054d699ec1f65e7de8aa5dd7d3ee0522dad18dc
[ "MIT" ]
6
2019-04-16T11:38:45.000Z
2020-12-12T16:55:03.000Z
src/stm32_sd.cpp
andreili/STM32F4
9054d699ec1f65e7de8aa5dd7d3ee0522dad18dc
[ "MIT" ]
1
2020-12-15T10:45:53.000Z
2021-02-22T11:59:19.000Z
src/stm32_sd.cpp
andreili/STM32F4
9054d699ec1f65e7de8aa5dd7d3ee0522dad18dc
[ "MIT" ]
2
2019-05-23T03:08:25.000Z
2020-10-10T12:43:06.000Z
#include "stm32_sd.hpp" #ifdef STM32_USE_SD #define DATA_BLOCK_SIZE EDataBlockSize::_512B #define SDIO_STATIC_FLAGS SDIO_STA::EMasks::CCRCFAIL, SDIO_STA::EMasks::DCRCFAIL, \ SDIO_STA::EMasks::CTIMEOUT, SDIO_STA::EMasks::DTIMEOUT, \ SDIO_STA::EMasks::TXUNDERR, SDIO_STA::EMasks::RXOVERR, \ SDIO_STA::EMasks::CMDREND, SDIO_STA::EMasks::CMDSENT, \ SDIO_STA::EMasks::DATAEND, SDIO_STA::EMasks::DBCKEND #define CLKCR_CLEAR_MASK SetBits<(std::uint32_t)STM32_REGS::SDIO::CLKCR::EMasks::CLKDIV, \ (std::uint32_t)STM32_REGS::SDIO::CLKCR::EMasks::PWRSAV, \ (std::uint32_t)STM32_REGS::SDIO::CLKCR::EMasks::BYPASS, \ (std::uint32_t)STM32_REGS::SDIO::CLKCR::EMasks::WIDBUS, \ (std::uint32_t)STM32_REGS::SDIO::CLKCR::EMasks::NEGEDGE, \ (std::uint32_t)STM32_REGS::SDIO::CLKCR::EMasks::HWFC_EN>() #define DCTRL_CLEAR_MASK SetBits<(std::uint32_t)STM32_REGS::SDIO::DCTRL::EMasks::DTEN, \ (std::uint32_t)STM32_REGS::SDIO::DCTRL::EMasks::DTDIR, \ (std::uint32_t)STM32_REGS::SDIO::DCTRL::EMasks::DTMODE, \ (std::uint32_t)STM32_REGS::SDIO::DCTRL::EMasks::DBLOCKSIZE>() #define CMD_CLEAR_MASK SetBits<(std::uint32_t)STM32_REGS::SDIO::CMD::EMasks::CMDINDEX, \ (std::uint32_t)STM32_REGS::SDIO::CMD::EMasks::WAITRESP, \ (std::uint32_t)STM32_REGS::SDIO::CMD::EMasks::WAITINT, \ (std::uint32_t)STM32_REGS::SDIO::CMD::EMasks::WAITPEND, \ (std::uint32_t)STM32_REGS::SDIO::CMD::EMasks::CPSMEN, \ (std::uint32_t)STM32_REGS::SDIO::CMD::EMasks::SDIOSUSPEND>() #define SDIO_INIT_CLK_DIV 0x76U #define SDIO_TRANSFER_CLK_DIV ((uint8_t)0x00U) #define SDIO_CMD0TIMEOUT 0x00010000U #define SD_VOLTAGE_WINDOW_WALID 0x80000000U #define SD_VOLTAGE_WINDOW_SD 0x80100000U #define SD_HIGH_CAPACITY 0x40000000U #define SD_STD_CAPACITY 0x00000000U #define SD_CHECK_PATTERN 0x000001AAU #define SD_MAX_VOLT_TRIAL 0x0000FFFFU #define SD_ALLZERO 0x00000000U #define SD_WIDE_BUS_SUPPORT 0x00040000U #define SD_SINGLE_BUS_SUPPORT 0x00010000U #define SD_CARD_LOCKED 0x02000000U #define SD_DATATIMEOUT 0xFFFFFFFFU #define SD_0TO7BITS 0x000000FFU #define SD_8TO15BITS 0x0000FF00U #define SD_16TO23BITS 0x00FF0000U #define SD_24TO31BITS 0xFF000000U #define SD_MAX_DATA_LENGTH 0x01FFFFFFU #define SD_HALFFIFO ((uint32_t)0x00000008U) #define SD_HALFFIFOBYTES ((uint32_t)0x00000020U) /** * @brief Command Class Supported */ #define SD_CCCC_LOCK_UNLOCK 0x00000080U #define SD_CCCC_WRITE_PROT 0x00000040U #define SD_CCCC_ERASE 0x00000020U using SDIO_STA = STM32_REGS::SDIO::STA; namespace STM32 { SD::ECardType SD::m_card_type; uint16_t SD::m_RCA; uint32_t SD::m_CSD[4]; uint32_t SD::m_CID[4]; SD::CardInfo SD::m_card_info; SD::ESDError SD::init() { init_gpio(); ///TODO init_DMA(); STM32::NVIC::enable_and_set_prior_IRQ(STM32::IRQn::SDIO, 0, 0); init_low(EClockEdge::RISING, EClockBypass::DISABLE, EClockPowerSave::DISABLE, EBusWide::_1B, EHWFlowControl::DISABLE, SDIO_INIT_CLK_DIV); ESDError errorstate; disable_SDIO(); power_state_ON(); STM32::SYSTICK::delay(1); enable_SDIO(); STM32::SYSTICK::delay(2); if ((errorstate = power_ON()) != ESDError::OK) return errorstate; if ((errorstate = initialize_cards()) != ESDError::OK) return errorstate; if ((errorstate = get_card_info()) == ESDError::OK) select_deselect(static_cast<uint32_t>(m_card_info.RCA << 16)); init_low(EClockEdge::RISING, EClockBypass::DISABLE, EClockPowerSave::DISABLE, EBusWide::_1B, EHWFlowControl::DISABLE, STM32_SDIO_CLOCK_DIV); return errorstate; } void SD::deinit() { power_OFF(); STM32::RCC::disable_clk_SDIO(); deinit_gpio(); //TODO deinit DMA STM32::NVIC::disable_IRQ(STM32::IRQn::SDIO); } SD::ESDError SD::wide_bus_config(EBusWide mode) { ESDError errorstate = ESDError::OK; /* MMC Card does not support this feature */ if (m_card_type == ECardType::MULTIMEDIA) return ESDError::UNSUPPORTED_FEATURE; else if ((m_card_type == ECardType::STD_CAPACITY_V1_1) || (m_card_type == ECardType::STD_CAPACITY_V2_0) || (m_card_type == ECardType::HIGH_CAPACITY)) { if (mode == EBusWide::_8B) errorstate = ESDError::UNSUPPORTED_FEATURE; else if (mode == EBusWide::_4B) errorstate = wide_bus_enable(); else if (mode == EBusWide::_1B) errorstate = wide_bus_disable(); else /* mode is not a valid argument*/ errorstate = ESDError::INVALID_PARAMETER; if (errorstate == ESDError::OK) { /* Configure the SDIO peripheral */ init_low(EClockEdge::RISING, EClockBypass::DISABLE, EClockPowerSave::DISABLE, mode, EHWFlowControl::DISABLE, STM32_SDIO_CLOCK_DIV); } } return errorstate; } SD::ETransferState SD::get_status() { ECardState cardstate = ECardState::TRANSFER; cardstate = get_state(); /* Find SD status according to card state*/ if (cardstate == ECardState::TRANSFER) return ETransferState::OK; else if(cardstate == ECardState::ERROR) return ETransferState::ERROR; else return ETransferState::BUSY; } SD::ESDError SD::read_blocks(uint8_t *buf, uint32_t read_addr, uint32_t block_size, uint16_t blocks) { ESDError errorstate = ESDError::OK; uint32_t count = 0U, *tempbuff = reinterpret_cast<uint32_t*>(buf); /* Initialize data control register */ STM32_REGS::SDIO::DCTRL::set(0); if (m_card_type == ECardType::HIGH_CAPACITY) { block_size = 512U; read_addr /= 512U; } /* Set Block Size for Card */ send_command(block_size, ECMD::SET_BLOCKLEN, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SET_BLOCKLEN); if (errorstate != ESDError::OK) return errorstate; /* Configure the SD DPSM (Data Path State Machine) */ data_config(SD_DATATIMEOUT, blocks * block_size, DATA_BLOCK_SIZE, ETransferDir::TO_SDIO, ETransferMode::BLOCK, EDPSM::ENABLE); if (blocks > 1U) { /* Send CMD18 READ_MULT_BLOCK with argument data address */ send_command(read_addr, ECMD::READ_MULT_BLOCK, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); } else { /* Send CMD17 READ_SINGLE_BLOCK */ send_command(read_addr, ECMD::READ_SINGLE_BLOCK, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); } /* Read block(s) in polling mode */ #ifdef STM32_USE_RTOS TCritSect cs; #endif if (blocks > 1U) { /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::READ_MULT_BLOCK); if (errorstate != ESDError::OK) return errorstate; /* Poll on SDIO flags */ #ifdef SDIO_STA_STBITERR while (!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DATAEND, SDIO_STA::EMasks::STBITERR>()) #else /* SDIO_STA_STBITERR not defined */ while (!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DATAEND>()) #endif /* SDIO_STA_STBITERR */ { if (get_flag<SDIO_STA::EMasks::RXFIFOHF>()) { /* Read data from SDIO Rx FIFO */ for (count = 0U; count < 8U; count++) *(tempbuff + count) = read_FIFO(); tempbuff += 8U; } } } else { /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::READ_SINGLE_BLOCK); //xprintf("error 3=%d\n\r", errorstate); if (errorstate != ESDError::OK) return errorstate; /* In case of single block transfer, no need of stop transfer at all */ #ifdef SDIO_STA_STBITERR while (!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND, SDIO_STA::EMasks::STBITERR>()) #else /* SDIO_STA_STBITERR not defined */ while (!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND>()) #endif /* SDIO_STA_STBITERR */ { if (get_flag<SDIO_STA::EMasks::RXFIFOHF>()) { /* Read data from SDIO Rx FIFO */ for (count = 0U; count < 8U; count++) *(tempbuff + count) = read_FIFO(); tempbuff += 8U; } } } /* Send stop transmission command in case of multiblock read */ if (get_flag<SDIO_STA::EMasks::DATAEND>() && (blocks > 1U)) { if ((m_card_type == ECardType::STD_CAPACITY_V1_1) || (m_card_type == ECardType::STD_CAPACITY_V2_0) || (m_card_type == ECardType::HIGH_CAPACITY)) /* Send stop transmission command */ errorstate = stop_transfer(); } /* Get error state */ if (get_flag<SDIO_STA::EMasks::DTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::DTIMEOUT>(); return ESDError::DATA_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::DCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::DCRCFAIL>(); return ESDError::DATA_CRC_FAIL; } else if (get_flag<SDIO_STA::EMasks::RXOVERR>()) { clear_flag<SDIO_STA::EMasks::RXOVERR>(); return ESDError::RX_OVERRUN; } #ifdef SDIO_STA_STBITERR else if (get_flag<SDIO_STA::EMasks::STBITERR>()) { clear_flag<SDIO_STA::EMasks::STBITERR>(); return ESDError::START_BIT_ERR; } #endif /* SDIO_STA_STBITERR */ else { /* No error flag set */ } count = SD_DATATIMEOUT; /* Empty FIFO if there is still any data */ while ((get_flag<SDIO_STA::EMasks::RXDAVL>()) && (count > 0U)) { *tempbuff = read_FIFO(); tempbuff++; count--; } /* Clear all the static flags */ clear_flag<SDIO_STATIC_FLAGS>(); return errorstate; } SD::ESDError SD::write_blocks(uint8_t *buf, uint32_t write_addr, uint32_t block_size, uint16_t blocks) { ESDError errorstate = ESDError::OK; uint32_t totalnumberofbytes = 0U, bytestransferred = 0U, count = 0U, restwords = 0U; uint32_t *tempbuff = reinterpret_cast<uint32_t*>(buf); ECardState cardstate = ECardState::READY; /* Initialize data control register */ STM32_REGS::SDIO::DCTRL::set(0); if (m_card_type == ECardType::HIGH_CAPACITY) { block_size = 512U; write_addr /= 512U; } /* Set Block Size for Card */ send_command(block_size, ECMD::SET_BLOCKLEN, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SET_BLOCKLEN); if (errorstate != ESDError::OK) return errorstate; if (blocks > 1U) /* Send CMD25 WRITE_MULT_BLOCK with argument data address */ send_command(write_addr, ECMD::WRITE_MULT_BLOCK, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); else /* Send CMD24 WRITE_SINGLE_BLOCK */ send_command(write_addr, ECMD::WRITE_SINGLE_BLOCK, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ if (blocks > 1U) errorstate = cmd_resp1_error(ECMD::WRITE_MULT_BLOCK); else errorstate = cmd_resp1_error(ECMD::WRITE_SINGLE_BLOCK); if (errorstate != ESDError::OK) return errorstate; /* Set total number of bytes to write */ totalnumberofbytes = blocks * block_size; /* Configure the SD DPSM (Data Path State Machine) */ data_config(SD_DATATIMEOUT, blocks * block_size, EDataBlockSize::_512B, ETransferDir::TO_CARD, ETransferMode::BLOCK, EDPSM::ENABLE); /* Write block(s) in polling mode */ if (blocks > 1U) { #ifdef SDIO_STA_STBITERR while (!get_flag<SDIO_STA::EMasks::TXUNDERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DATAEND, SDIO_STA::EMasks::STBITERR>()) #else /* SDIO_STA_STBITERR not defined */ while (!get_flag<SDIO_STA::EMasks::TXUNDERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DATAEND>()) #endif /* SDIO_STA_STBITERR */ { if (get_flag<SDIO_STA::EMasks::TXFIFOHE>()) { if ((totalnumberofbytes - bytestransferred) < 32U) { restwords = ((totalnumberofbytes - bytestransferred) % 4U == 0U) ? ((totalnumberofbytes - bytestransferred) / 4U) : (( totalnumberofbytes - bytestransferred) / 4U + 1U); /* Write data to SDIO Tx FIFO */ for (count = 0U; count < restwords; count++) { write_FIFO(tempbuff); tempbuff++; bytestransferred += 4U; } } else { /* Write data to SDIO Tx FIFO */ for (count = 0U; count < 8U; count++) write_FIFO(tempbuff + count); tempbuff += 8U; bytestransferred += 32U; } } } } else { /* In case of single data block transfer no need of stop command at all */ #ifdef SDIO_STA_STBITERR while (!get_flag<SDIO_STA::EMasks::TXUNDERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND, SDIO_STA::EMasks::STBITERR>()) #else /* SDIO_STA_STBITERR not defined */ while (!get_flag<SDIO_STA::EMasks::TXUNDERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND>()) #endif /* SDIO_STA_STBITERR */ { if (get_flag<SDIO_STA::EMasks::TXFIFOHE>()) { if ((totalnumberofbytes - bytestransferred) < 32U) { restwords = ((totalnumberofbytes - bytestransferred) % 4U == 0U) ? ((totalnumberofbytes - bytestransferred) / 4U) : (( totalnumberofbytes - bytestransferred) / 4U + 1U); /* Write data to SDIO Tx FIFO */ for (count = 0U; count < restwords; count++) { write_FIFO(tempbuff); tempbuff++; bytestransferred += 4U; } } else { /* Write data to SDIO Tx FIFO */ for (count = 0U; count < 8U; count++) write_FIFO(tempbuff + count); tempbuff += 8U; bytestransferred += 32U; } } } } /* Send stop transmission command in case of multiblock write */ if (get_flag<SDIO_STA::EMasks::DATAEND>() && (blocks > 1U)) { if ((m_card_type == ECardType::STD_CAPACITY_V1_1) || (m_card_type == ECardType::STD_CAPACITY_V2_0) ||\ (m_card_type == ECardType::HIGH_CAPACITY)) /* Send stop transmission command */ errorstate = stop_transfer(); } /* Get error state */ if (get_flag<SDIO_STA::EMasks::DTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::DTIMEOUT>(); return ESDError::DATA_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::DCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::DCRCFAIL>(); return ESDError::DATA_CRC_FAIL; } else if (get_flag<SDIO_STA::EMasks::TXUNDERR>()) { clear_flag<SDIO_STA::EMasks::TXUNDERR>(); return ESDError::TX_UNDERRUN; } #ifdef SDIO_STA_STBITERR else if (get_flag<SDIO_STA::EMasks::STBITERR>()) { clear_flag<SDIO_STA::EMasks::STBITERR>(); return ESDError::START_BIT_ERR; } #endif /* SDIO_STA_STBITERR */ else { /* No error flag set */ } /* Clear all the static flags */ clear_flag<SDIO_STATIC_FLAGS>(); /* Wait till the card is in programming state */ errorstate = is_card_programming(&cardstate); while ((errorstate == ESDError::OK) && ((cardstate == ECardState::PROGRAMMING) || (cardstate == ECardState::RECEIVING))) errorstate = is_card_programming(&cardstate); return errorstate; } SD::ESDError SD::erase(uint32_t start_addr, uint32_t end_addr) { ESDError errorstate = ESDError::OK; uint32_t delay = 0U; __IO uint32_t maxdelay = 0U; ECardState cardstate = ECardState::READY; /* Check if the card command class supports erase command */ if (((m_CSD[1U] >> 20U) & SD_CCCC_ERASE) == 0U) return ESDError::REQUEST_NOT_APPLICABLE; /* Get max delay value */ maxdelay = 120000U / (((STM32_REGS::SDIO::CLKCR::get()) & 0xFFU) + 2U); if ((get_response1() & SD_CARD_LOCKED) == SD_CARD_LOCKED) return ESDError::LOCK_UNLOCK_FAILED; /* Get start and end block for high capacity cards */ if (m_card_type == ECardType::HIGH_CAPACITY) { start_addr /= 512U; end_addr /= 512U; } /* According to sd-card spec 1.0 ERASE_GROUP_START (CMD32) and erase_group_end(CMD33) */ if ((m_card_type == ECardType::STD_CAPACITY_V1_1) || (m_card_type == ECardType::STD_CAPACITY_V2_0) || (m_card_type == ECardType::HIGH_CAPACITY)) { /* Send CMD32 SD_ERASE_GRP_START with argument as addr */ send_command(start_addr, ECMD::SD_ERASE_GRP_START, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SD_ERASE_GRP_START); if (errorstate != ESDError::OK) return errorstate; /* Send CMD33 SD_ERASE_GRP_END with argument as addr */ send_command(end_addr, ECMD::SD_ERASE_GRP_END, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SD_ERASE_GRP_END); if (errorstate != ESDError::OK) return errorstate; } /* Send CMD38 ERASE */ send_command(0, ECMD::ERASE, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::ERASE); if (errorstate != ESDError::OK) return errorstate; for (; delay < maxdelay; delay++) {} /* Wait until the card is in programming state */ errorstate = is_card_programming(&cardstate); delay = SD_DATATIMEOUT; while ((delay > 0U) && (errorstate == ESDError::OK) && ((cardstate == ECardState::PROGRAMMING) || (cardstate == ECardState::RECEIVING))) { errorstate = is_card_programming(&cardstate); delay--; } return errorstate; } SD::ESDError SD::high_speed() { ESDError errorstate = ESDError::OK; uint8_t SD_hs[64U] = {0U}; uint32_t SD_scr[2U] = {0U, 0U}; uint32_t SD_SPEC = 0U; uint32_t count = 0U, *tempbuff = reinterpret_cast<uint32_t*>(SD_hs); /* Initialize the Data control register */ STM32_REGS::SDIO::DCTRL::set(0); /* Get SCR Register */ errorstate = find_SCR(SD_scr); if (errorstate != ESDError::OK) return errorstate; /* Test the Version supported by the card*/ SD_SPEC = (SD_scr[1U] & 0x01000000U) | (SD_scr[1U] & 0x02000000U); if (SD_SPEC != SD_ALLZERO) { /* Set Block Size for Card */ send_command(64U, ECMD::SET_BLOCKLEN, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SET_BLOCKLEN); if (errorstate != ESDError::OK) return errorstate; /* Configure the SD DPSM (Data Path State Machine) */ data_config(SD_DATATIMEOUT, 64U, EDataBlockSize::_64B, ETransferDir::TO_SDIO, ETransferMode::BLOCK, EDPSM::ENABLE); /* Send CMD6 switch mode */ send_command(0x80FFFF01U, ECMD::HS_SWITCH, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::HS_SWITCH); if (errorstate != ESDError::OK) return errorstate; #ifdef SDIO_STA_STBITERR while (!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND, SDIO_STA::EMasks::STBITERR>()) #else /* SDIO_STA_STBITERR */ while (!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND>()) #endif /* SDIO_STA_STBITERR */ { if (get_flag<SDIO_STA::EMasks::RXFIFOHF>()) { for (count = 0U; count < 8U; count++) *(tempbuff + count) = read_FIFO(); tempbuff += 8U; } } if (get_flag<SDIO_STA::EMasks::DTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::DTIMEOUT>(); return ESDError::DATA_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::DCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::DCRCFAIL>(); return ESDError::DATA_CRC_FAIL; } else if (get_flag<SDIO_STA::EMasks::RXOVERR>()) { clear_flag<SDIO_STA::EMasks::RXOVERR>(); return ESDError::RX_OVERRUN; } #ifdef SDIO_STA_STBITERR else if (get_flag<SDIO_STA::EMasks::STBITERR>()) { clear_flag<SDIO_STA::EMasks::STBITERR>(); return ESDError::START_BIT_ERR; } #endif /* SDIO_STA_STBITERR */ else { /* No error flag set */ } count = SD_DATATIMEOUT; while ((get_flag<SDIO_STA::EMasks::RXDAVL>()) && (count > 0U)) { *tempbuff = read_FIFO(); tempbuff++; count--; } /* Clear all the static flags */ clear_flag<SDIO_STATIC_FLAGS>(); /* Test if the switch mode HS is ok */ if ((SD_hs[13U]& 2U) != 2U) errorstate = ESDError::UNSUPPORTED_FEATURE; } return errorstate; } SD::ESDError SD::send_SD_status(uint32_t *status) { ESDError errorstate = ESDError::OK; uint32_t count = 0U; /* Check SD response */ if ((get_response1() & SD_CARD_LOCKED) == SD_CARD_LOCKED) return ESDError::LOCK_UNLOCK_FAILED; /* Set block size for card if it is not equal to current block size for card */ send_command(64U, ECMD::SET_BLOCKLEN, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SET_BLOCKLEN); if (errorstate != ESDError::OK) return errorstate; /* Send CMD55 */ send_command(static_cast<uint32_t>(m_RCA << 16U), ECMD::APP_CMD, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::APP_CMD); if (errorstate != ESDError::OK) return errorstate; /* Configure the SD DPSM (Data Path State Machine) */ data_config(SD_DATATIMEOUT, 64U, EDataBlockSize::_64B, ETransferDir::TO_SDIO, ETransferMode::BLOCK, EDPSM::ENABLE); /* Send ACMD13 (SD_APP_STATUS) with argument as card's RCA */ send_command(0, ECMD::SD_APP_STATUS, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SD_APP_STATUS); if (errorstate != ESDError::OK) return errorstate; /* Get status data */ #ifdef SDIO_STA_STBITERR while (!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND, SDIO_STA::EMasks::STBITERR>()) #else /* SDIO_STA_STBITERR not defined */ while (!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND>()) #endif /* SDIO_STA_STBITERR */ { if (get_flag<SDIO_STA::EMasks::RXFIFOHF>()) { for (count = 0U; count < 8U; count++) *(status + count) = read_FIFO(); status += 8U; } } if (get_flag<SDIO_STA::EMasks::DTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::DTIMEOUT>(); return ESDError::DATA_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::DCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::DCRCFAIL>(); return ESDError::DATA_CRC_FAIL; } else if (get_flag<SDIO_STA::EMasks::RXOVERR>()) { clear_flag<SDIO_STA::EMasks::RXOVERR>(); return ESDError::RX_OVERRUN; } #ifdef SDIO_STA_STBITERR else if (get_flag<SDIO_STA::EMasks::STBITERR>()) { clear_flag<SDIO_STA::EMasks::STBITERR>(); return ESDError::START_BIT_ERR; } #endif /* SDIO_STA_STBITERR */ else { /* No error flag set */ } count = SD_DATATIMEOUT; while ((get_flag<SDIO_STA::EMasks::RXDAVL>()) && (count > 0U)) { *status = read_FIFO(); status++; count--; } /* Clear all the static status flags*/ clear_flag<SDIO_STATIC_FLAGS>(); return errorstate; } void SD::init_gpio() { STM32::RCC::enable_clk_SDIO(); STM32::RCC::enable_clk_GPIOC(); STM32::RCC::enable_clk_GPIOD(); gpioc.set_config(STM32_GPIO::PIN_8 | STM32_GPIO::PIN_9 | STM32_GPIO::PIN_10 | STM32_GPIO::PIN_11 | STM32_GPIO::PIN_12, STM32_GPIO::EMode::AF_PP, STM32_GPIO::EAF::AF12_SDIO, STM32_GPIO::ESpeed::VERY_HIGH, STM32_GPIO::EPull::NOPULL); gpiod.set_config(STM32_GPIO::PIN_2, STM32_GPIO::EMode::AF_PP, STM32_GPIO::EAF::AF12_SDIO, STM32_GPIO::ESpeed::VERY_HIGH, STM32_GPIO::EPull::NOPULL); } void SD::deinit_gpio() { gpioc.unset_config(STM32_GPIO::PIN_8 | STM32_GPIO::PIN_9 | STM32_GPIO::PIN_10 | STM32_GPIO::PIN_11 | STM32_GPIO::PIN_12); gpiod.unset_config(STM32_GPIO::PIN_2); STM32::RCC::disable_clk_GPIOC(); STM32::RCC::disable_clk_GPIOD(); } void SD::init_low(EClockEdge clock_edge, EClockBypass clock_bypass, EClockPowerSave clock_power_save, EBusWide bus_wide, EHWFlowControl hw_control, uint32_t clock_div) { uint32_t val = STM32_REGS::SDIO::CLKCR::get(); val &= ~(CLKCR_CLEAR_MASK); val |= static_cast<uint32_t>(clock_edge) | static_cast<uint32_t>(clock_bypass) | static_cast<uint32_t>(clock_power_save) | static_cast<uint32_t>(bus_wide) | static_cast<uint32_t>(hw_control) | clock_div; STM32_REGS::SDIO::CLKCR::set(val); } SD::ESDError SD::power_ON() { /* CMD0: GO_IDLE_STATE */ send_command(0, ECMD::GO_IDLE_STATE, EResponse::NO, EWait::NO, ECPSM::ENABLE); ESDError errorstate = cmd_error(); if (errorstate != ESDError::OK) { clear_flag<SDIO_STATIC_FLAGS>(); return errorstate; } /* CMD8: SEND_IF_COND ------------------------------------------------------*/ /* Send CMD8 to verify SD card interface operating condition */ /* Argument: - [31:12]: Reserved (shall be set to '0') - [11:8]: Supply Voltage (VHS) 0x1 (Range: 2.7-3.6 V) - [7:0]: Check Pattern (recommended 0xAA) */ uint32_t sdtype = SD_STD_CAPACITY; send_command(SD_CHECK_PATTERN, ECMD::HS_SEND_EXT_CSD, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); errorstate = cmd_resp7_error(); if (errorstate != ESDError::OK) { m_card_type = ECardType::STD_CAPACITY_V1_1; sdtype = SD_STD_CAPACITY; } else { /* SD Card 2.0 */ m_card_type = ECardType::STD_CAPACITY_V2_0; sdtype = SD_HIGH_CAPACITY; } /* Send CMD55 */ send_command(0, ECMD::APP_CMD, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* If errorstate is Command Timeout, it is a MMC card */ /* If errorstate is ESDError::OK it is a SD card: SD card 2.0 (voltage range mismatch) or SD card 1.x */ uint32_t response = 0; errorstate = cmd_resp1_error(ECMD::APP_CMD); if (errorstate == ESDError::OK) { /* SD CARD */ /* Send ACMD41 SD_APP_OP_COND with Argument 0x80100000 */ uint32_t validvoltage = 0; uint32_t count = 0; while ((!validvoltage) && (count <SD_MAX_VOLT_TRIAL)) { /* SEND CMD55 APP_CMD with RCA as 0 */ send_command(0, ECMD::APP_CMD, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); errorstate = cmd_resp1_error(ECMD::APP_CMD); if (errorstate != ESDError::OK) return errorstate; /* Send CMD41 */ send_command(SD_VOLTAGE_WINDOW_SD | sdtype, ECMD::SD_APP_OP_COND, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); errorstate = cmd_resp3_error(); if (errorstate != ESDError::OK) return errorstate; /* Get command response */ response = get_response1(); validvoltage = ((response & SD_VOLTAGE_WINDOW_WALID) == SD_VOLTAGE_WINDOW_WALID); ++count; } if (count >= SD_MAX_VOLT_TRIAL) return ESDError::INVALID_VOLTRANGE; if ((response & SD_HIGH_CAPACITY) == SD_HIGH_CAPACITY) m_card_type = ECardType::HIGH_CAPACITY; else m_card_type = ECardType::STD_CAPACITY_V2_0; } /* else MMC Card */ else { } return errorstate; } SD::ESDError SD::power_OFF() { power_state_OFF(); return ESDError::OK; } SD::ESDError SD::send_status(uint32_t *card_status) { ESDError errorstate = ESDError::OK; if(card_status == nullptr) return ESDError::INVALID_PARAMETER; /* Send Status command */ send_command(static_cast<uint32_t>(m_RCA << 16U), ECMD::SEND_STATUS, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SEND_STATUS); if(errorstate != ESDError::OK) return errorstate; /* Get SD card status */ *card_status = get_response1(); return errorstate; } SD::ESDError SD::initialize_cards() { ESDError errorstate = ESDError::OK; uint16_t sd_rca = 1; if (get_power_state() == 0) /* Power off */ return ESDError::REQUEST_NOT_APPLICABLE; if (m_card_type != ECardType::SECURE_DIGITAL_IO) { /* Send CMD2 ALL_SEND_CID */ send_command(0, ECMD::ALL_SEND_CID, EResponse::LONG, EWait::NO, ECPSM::ENABLE); if ((errorstate = cmd_resp2_error()) != ESDError::OK) return errorstate; m_CID[0] = get_response1(); m_CID[1] = get_response2(); m_CID[2] = get_response3(); m_CID[3] = get_response4(); } if ((m_card_type == ECardType::STD_CAPACITY_V1_1) || (m_card_type == ECardType::STD_CAPACITY_V2_0) || (m_card_type == ECardType::SECURE_DIGITAL_IO_COMBO) || (m_card_type == ECardType::HIGH_CAPACITY)) { /* Send CMD3 SET_REL_ADDR with argument 0 */ /* SD Card publishes its RCA. */ send_command(0, ECMD::SET_REL_ADDR, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); if ((errorstate = cmd_resp6_error(ECMD::SET_REL_ADDR, &sd_rca)) != ESDError::OK) return errorstate; } if (m_card_type != ECardType::SECURE_DIGITAL_IO) { /* Get the SD card RCA */ m_RCA = sd_rca; /* Send CMD9 SEND_CSD with argument as card's RCA */ send_command(static_cast<uint32_t>(m_RCA << 16), ECMD::SEND_CSD, EResponse::LONG, EWait::NO, ECPSM::ENABLE); if ((errorstate = cmd_resp2_error()) != ESDError::OK) return errorstate; m_CSD[0] = get_response1(); m_CSD[1] = get_response2(); m_CSD[2] = get_response3(); m_CSD[3] = get_response4(); } return errorstate; } void SD::send_command(uint32_t arg, ECMD cmd, EResponse resp, EWait wait_IT, ECPSM cpsm) { STM32_REGS::SDIO::ARG::set(arg); uint32_t val = STM32_REGS::SDIO::CMD::get(); val &= ~(CMD_CLEAR_MASK); val |= static_cast<uint32_t>(cmd) | static_cast<uint32_t>(resp) | static_cast<uint32_t>(wait_IT) | static_cast<uint32_t>(cpsm); STM32_REGS::SDIO::CMD::set(val); } SD::ESDError SD::cmd_error() { WAIT_TIMEOUT_EX((!get_flag<SDIO_STA::EMasks::CMDSENT>()), SDIO_CMD0TIMEOUT, ESDError::CMD_RSP_TIMEOUT); clear_flag<SDIO_STATIC_FLAGS>(); return ESDError::OK; } SD::ESDError SD::cmd_resp7_error() { WAIT_TIMEOUT_EX((!get_flag<SDIO_STA::EMasks::CCRCFAIL, SDIO_STA::EMasks::CMDREND, SDIO_STA::EMasks::CTIMEOUT>()), SDIO_CMD0TIMEOUT, ESDError::CMD_RSP_TIMEOUT); if (get_flag<SDIO_STA::EMasks::CTIMEOUT>()) { /* Card is not V2.0 compliant or card does not support the set voltage range */ clear_flag<SDIO_STA::EMasks::CTIMEOUT>(); return ESDError::CMD_RSP_TIMEOUT; } if (get_flag<SDIO_STA::EMasks::CMDREND>()) { /* Card is SD V2.0 compliant */ clear_flag<SDIO_STA::EMasks::CMDREND>(); return ESDError::OK; } return ESDError::ERROR; } SD::ESDError SD::cmd_resp1_error(ECMD cmd) { while (!get_flag<SDIO_STA::EMasks::CCRCFAIL, SDIO_STA::EMasks::CMDREND, SDIO_STA::EMasks::CTIMEOUT>()) {} if (get_flag<SDIO_STA::EMasks::CTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::CTIMEOUT>(); return ESDError::CMD_RSP_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::CCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::CCRCFAIL>(); return ESDError::CMD_CRC_FAIL; } /* Check response received is of desired command */ if (get_cmd_response() != cmd) return ESDError::CMD_CRC_FAIL; /* Clear all the static flags */ clear_flag<SDIO_STATIC_FLAGS>(); uint32_t response_r1 = get_response1(); if ((response_r1 & EOCRMasks::ERRORBITS) == SD_ALLZERO) return ESDError::OK; if ((response_r1 & EOCRMasks::ADDR_OUT_OF_RANGE)) return ESDError::ADDR_OUT_OF_RANGE; if ((response_r1 & EOCRMasks::ADDR_MISALIGNED)) return ESDError::ADDR_MISALIGNED; if ((response_r1 & EOCRMasks::BLOCK_LEN_ERR)) return ESDError::BLOCK_LEN_ERR; if ((response_r1 & EOCRMasks::ERASE_SEQ_ERR)) return ESDError::ERASE_SEQ_ERR; if ((response_r1 & EOCRMasks::BAD_ERASE_PARAM)) return ESDError::BAD_ERASE_PARAM; if ((response_r1 & EOCRMasks::WRITE_PROT_VIOLATION)) return ESDError::WRITE_PROT_VIOLATION; if ((response_r1 & EOCRMasks::LOCK_UNLOCK_FAILED)) return ESDError::LOCK_UNLOCK_FAILED; if ((response_r1 & EOCRMasks::COM_CRC_FAILED)) return ESDError::COM_CRC_FAILED; /*if ((response_r1 & EOCRMasks::ILLEGAL_CMD)) return ESDError::ILLEGAL_CMD;*/ if ((response_r1 & EOCRMasks::CARD_ECC_FAILED)) return ESDError::CARD_ECC_FAILED; if ((response_r1 & EOCRMasks::CC_ERROR)) return ESDError::CC_ERROR; if ((response_r1 & EOCRMasks::GENERAL_UNKNOWN_ERROR)) return ESDError::GENERAL_UNKNOWN_ERROR; if ((response_r1 & EOCRMasks::STREAM_READ_UNDERRUN)) return ESDError::STREAM_READ_UNDERRUN; if ((response_r1 & EOCRMasks::STREAM_WRITE_OVERRUN)) return ESDError::STREAM_WRITE_OVERRUN; if ((response_r1 & EOCRMasks::CID_CSD_OVERWRITE)) return ESDError::CID_CSD_OVERWRITE; if ((response_r1 & EOCRMasks::WP_ERASE_SKIP)) return ESDError::WP_ERASE_SKIP; if ((response_r1 & EOCRMasks::CARD_ECC_DISABLED)) return ESDError::CARD_ECC_DISABLED; if ((response_r1 & EOCRMasks::ERASE_RESET)) return ESDError::ERASE_RESET; if ((response_r1 & EOCRMasks::AKE_SEQ_ERROR)) return ESDError::AKE_SEQ_ERROR; return ESDError::OK; } SD::ESDError SD::cmd_resp3_error() { while (!get_flag<SDIO_STA::EMasks::CCRCFAIL, SDIO_STA::EMasks::CMDREND, SDIO_STA::EMasks::CTIMEOUT>()) {} if (get_flag<SDIO_STA::EMasks::CTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::CTIMEOUT>(); return ESDError::CMD_RSP_TIMEOUT; } clear_flag<SDIO_STATIC_FLAGS>(); return ESDError::OK; } SD::ESDError SD::cmd_resp2_error() { while (!get_flag<SDIO_STA::EMasks::CCRCFAIL, SDIO_STA::EMasks::CMDREND, SDIO_STA::EMasks::CTIMEOUT>()) {} if (get_flag<SDIO_STA::EMasks::CTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::CTIMEOUT>(); return ESDError::CMD_RSP_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::CCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::CCRCFAIL>(); return ESDError::CMD_CRC_FAIL; } clear_flag<SDIO_STATIC_FLAGS>(); return ESDError::OK; } SD::ESDError SD::cmd_resp6_error(ECMD cmd, uint16_t *pRCA) { while (!get_flag<SDIO_STA::EMasks::CCRCFAIL, SDIO_STA::EMasks::CMDREND, SDIO_STA::EMasks::CTIMEOUT>()) {} if (get_flag<SDIO_STA::EMasks::CTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::CTIMEOUT>(); return ESDError::CMD_RSP_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::CCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::CCRCFAIL>(); return ESDError::CMD_CRC_FAIL; } if (get_cmd_response() != cmd) return ESDError::ILLEGAL_CMD; clear_flag<SDIO_STATIC_FLAGS>(); ER6Msk response_r1 = static_cast<ER6Msk>(get_response1()); if (response_r1 & ER6Msk::GENERAL_UNKNOWN_ERROR_6) return ESDError::GENERAL_UNKNOWN_ERROR; if (response_r1 & ER6Msk::ILLEGAL_CMD_6) return ESDError::ILLEGAL_CMD; if (response_r1 & ER6Msk::COM_CRC_FAILED_6) return ESDError::COM_CRC_FAILED; *pRCA = response_r1 >> 16; return ESDError::OK; } SD::ESDError SD::data_config(uint32_t time_out, uint32_t dat_len, EDataBlockSize block_size, ETransferDir transf_dir, ETransferMode transf_mode, EDPSM DPSM) { STM32_REGS::SDIO::DTIMER::set(time_out); STM32_REGS::SDIO::DLEN::set(dat_len); uint32_t val = STM32_REGS::SDIO::DCTRL::get(); val &= ~(DCTRL_CLEAR_MASK); val |= static_cast<uint32_t>(block_size) | static_cast<uint32_t>(transf_dir) | static_cast<uint32_t>(transf_mode) | static_cast<uint32_t>(DPSM); STM32_REGS::SDIO::DCTRL::set(val); return ESDError::OK; } SD::ESDError SD::stop_transfer() { send_command(0, ECMD::STOP_TRANSMISSION, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); return cmd_resp1_error(ECMD::STOP_TRANSMISSION); } SD::ESDError SD::get_card_info() { ESDError errorstate = ESDError::OK; m_card_info.CardType = static_cast<uint8_t>(m_card_type); m_card_info.RCA = m_RCA; /* Byte 1 */ uint32_t tmp = (m_CSD[0U] & 0x00FF0000U) >> 16U; m_card_info.SD_csd.TAAC = static_cast<uint8_t>(tmp); /* Byte 2 */ tmp = (m_CSD[0U] & 0x0000FF00U) >> 8U; m_card_info.SD_csd.NSAC = static_cast<uint8_t>(tmp); /* Byte 3 */ tmp = m_CSD[0U] & 0x000000FFU; m_card_info.SD_csd.MaxBusClkFrec = static_cast<uint8_t>(tmp); /* Byte 4 */ tmp = (m_CSD[1U] & 0xFF000000U) >> 24U; m_card_info.SD_csd.CardComdClasses = static_cast<uint16_t>(tmp << 4U); /* Byte 5 */ tmp = (m_CSD[1U] & 0x00FF0000U) >> 16U; m_card_info.SD_csd.CardComdClasses |= static_cast<uint16_t>((tmp & 0xF0) >> 4U); m_card_info.SD_csd.RdBlockLen = static_cast<uint8_t>(tmp & 0x0FU); /* Byte 6 */ tmp = (m_CSD[1U] & 0x0000FF00U) >> 8U; m_card_info.SD_csd.PartBlockRead = static_cast<uint8_t>((tmp & 0x80U) >> 7U); m_card_info.SD_csd.WrBlockMisalign = static_cast<uint8_t>((tmp & 0x40U) >> 6U); m_card_info.SD_csd.RdBlockMisalign = static_cast<uint8_t>((tmp & 0x20U) >> 5U); m_card_info.SD_csd.DSRImpl = static_cast<uint8_t>((tmp & 0x10U) >> 4U); m_card_info.SD_csd.Reserved2 = 0U; /*!< Reserved */ if ((m_card_type == ECardType::STD_CAPACITY_V1_1) || (m_card_type == ECardType::STD_CAPACITY_V2_0)) { m_card_info.SD_csd.DeviceSize = (tmp & 0x03U) << 10U; /* Byte 7 */ tmp = static_cast<uint8_t>(m_CSD[1U] & 0x000000FFU); m_card_info.SD_csd.DeviceSize |= (tmp) << 2U; /* Byte 8 */ tmp = static_cast<uint8_t>((m_CSD[2U] & 0xFF000000U) >> 24U); m_card_info.SD_csd.DeviceSize |= (tmp & 0xC0U) >> 6U; m_card_info.SD_csd.MaxRdCurrentVDDMin = (tmp & 0x38U) >> 3U; m_card_info.SD_csd.MaxRdCurrentVDDMax = (tmp & 0x07U); /* Byte 9 */ tmp = static_cast<uint8_t>((m_CSD[2U] & 0x00FF0000U) >> 16U); m_card_info.SD_csd.MaxWrCurrentVDDMin = (tmp & 0xE0U) >> 5U; m_card_info.SD_csd.MaxWrCurrentVDDMax = (tmp & 0x1CU) >> 2U; m_card_info.SD_csd.DeviceSizeMul = static_cast<uint8_t>((tmp & 0x03U) << 1U); /* Byte 10 */ tmp = static_cast<uint8_t>((m_CSD[2U] & 0x0000FF00U) >> 8U); m_card_info.SD_csd.DeviceSizeMul |= (tmp & 0x80U) >> 7U; m_card_info.CardCapacity = (m_card_info.SD_csd.DeviceSize + 1U) ; m_card_info.CardCapacity *= (1U << (m_card_info.SD_csd.DeviceSizeMul + 2U)); m_card_info.CardBlockSize = 1U << (m_card_info.SD_csd.RdBlockLen); m_card_info.CardCapacity *= m_card_info.CardBlockSize; } else if (m_card_type == ECardType::HIGH_CAPACITY) { /* Byte 7 */ tmp = static_cast<uint8_t>(m_CSD[1U] & 0x000000FFU); m_card_info.SD_csd.DeviceSize = (tmp & 0x3FU) << 16U; /* Byte 8 */ tmp = static_cast<uint8_t>((m_CSD[2U] & 0xFF000000U) >> 24U); m_card_info.SD_csd.DeviceSize |= (tmp << 8U); /* Byte 9 */ tmp = static_cast<uint8_t>((m_CSD[2U] & 0x00FF0000U) >> 16U); m_card_info.SD_csd.DeviceSize |= (tmp); /* Byte 10 */ tmp = static_cast<uint8_t>((m_CSD[2U] & 0x0000FF00U) >> 8U); m_card_info.CardCapacity = static_cast<uint64_t>((m_card_info.SD_csd.DeviceSize + 1U) * 512U * 1024U); m_card_info.CardBlockSize = 512U; } else { /* Not supported card type */ errorstate = ESDError::ERROR; } m_card_info.SD_csd.EraseGrSize = (tmp & 0x40U) >> 6U; m_card_info.SD_csd.EraseGrMul = static_cast<uint8_t>((tmp & 0x3FU) << 1U); /* Byte 11 */ tmp = static_cast<uint8_t>(m_CSD[2U] & 0x000000FFU); m_card_info.SD_csd.EraseGrMul |= (tmp & 0x80U) >> 7U; m_card_info.SD_csd.WrProtectGrSize = (tmp & 0x7FU); /* Byte 12 */ tmp = static_cast<uint8_t>((m_CSD[3U] & 0xFF000000U) >> 24U); m_card_info.SD_csd.WrProtectGrEnable = (tmp & 0x80U) >> 7U; m_card_info.SD_csd.ManDeflECC = (tmp & 0x60U) >> 5U; m_card_info.SD_csd.WrSpeedFact = (tmp & 0x1CU) >> 2U; m_card_info.SD_csd.MaxWrBlockLen = static_cast<uint8_t>((tmp & 0x03U) << 2U); /* Byte 13 */ tmp = static_cast<uint8_t>((m_CSD[3U] & 0x00FF0000U) >> 16U); m_card_info.SD_csd.MaxWrBlockLen |= (tmp & 0xC0U) >> 6U; m_card_info.SD_csd.WriteBlockPaPartial = (tmp & 0x20U) >> 5U; m_card_info.SD_csd.Reserved3 = 0U; m_card_info.SD_csd.ContentProtectAppli = (tmp & 0x01U); /* Byte 14 */ tmp = static_cast<uint8_t>((m_CSD[3U] & 0x0000FF00U) >> 8U); m_card_info.SD_csd.FileFormatGrouop = (tmp & 0x80U) >> 7U; m_card_info.SD_csd.CopyFlag = (tmp & 0x40U) >> 6U; m_card_info.SD_csd.PermWrProtect = (tmp & 0x20U) >> 5U; m_card_info.SD_csd.TempWrProtect = (tmp & 0x10U) >> 4U; m_card_info.SD_csd.FileFormat = (tmp & 0x0CU) >> 2U; m_card_info.SD_csd.ECC = (tmp & 0x03U); /* Byte 15 */ tmp = static_cast<uint8_t>(m_CSD[3U] & 0x000000FFU); m_card_info.SD_csd.CSD_CRC = (tmp & 0xFEU) >> 1U; m_card_info.SD_csd.Reserved4 = 1U; /* Byte 0 */ tmp = static_cast<uint8_t>((m_CID[0U] & 0xFF000000U) >> 24U); m_card_info.SD_cid.ManufacturerID = static_cast<uint8_t>(tmp); /* Byte 1 */ tmp = static_cast<uint8_t>((m_CID[0U] & 0x00FF0000U) >> 16U); m_card_info.SD_cid.OEM_AppliID = static_cast<uint8_t>(tmp << 8U); /* Byte 2 */ tmp = static_cast<uint8_t>((m_CID[0U] & 0x0000FF00U) >> 8U); m_card_info.SD_cid.OEM_AppliID |= tmp; /* Byte 3 */ tmp = static_cast<uint8_t>(m_CID[0U] & 0x000000FFU); m_card_info.SD_cid.ProdName1 = tmp << 24U; /* Byte 4 */ tmp = static_cast<uint8_t>((m_CID[1U] & 0xFF000000U) >> 24U); m_card_info.SD_cid.ProdName1 |= tmp << 16U; /* Byte 5 */ tmp = static_cast<uint8_t>((m_CID[1U] & 0x00FF0000U) >> 16U); m_card_info.SD_cid.ProdName1 |= tmp << 8U; /* Byte 6 */ tmp = static_cast<uint8_t>((m_CID[1U] & 0x0000FF00U) >> 8U); m_card_info.SD_cid.ProdName1 |= tmp; /* Byte 7 */ tmp = static_cast<uint8_t>(m_CID[1U] & 0x000000FFU); m_card_info.SD_cid.ProdName2 = static_cast<uint8_t>(tmp); /* Byte 8 */ tmp = static_cast<uint8_t>((m_CID[2U] & 0xFF000000U) >> 24U); m_card_info.SD_cid.ProdRev = static_cast<uint8_t>(tmp); /* Byte 9 */ tmp = static_cast<uint8_t>((m_CID[2U] & 0x00FF0000U) >> 16U); m_card_info.SD_cid.ProdSN = tmp << 24U; /* Byte 10 */ tmp = static_cast<uint8_t>((m_CID[2U] & 0x0000FF00U) >> 8U); m_card_info.SD_cid.ProdSN |= tmp << 16U; /* Byte 11 */ tmp = static_cast<uint8_t>(m_CID[2U] & 0x000000FFU); m_card_info.SD_cid.ProdSN |= tmp << 8U; /* Byte 12 */ tmp = static_cast<uint8_t>((m_CID[3U] & 0xFF000000U) >> 24U); m_card_info.SD_cid.ProdSN |= tmp; /* Byte 13 */ tmp = static_cast<uint8_t>((m_CID[3U] & 0x00FF0000U) >> 16U); m_card_info.SD_cid.Reserved1 |= (tmp & 0xF0U) >> 4U; m_card_info.SD_cid.ManufactDate = static_cast<uint16_t>((tmp & 0x0FU) << 8U); /* Byte 14 */ tmp = static_cast<uint8_t>((m_CID[3U] & 0x0000FF00U) >> 8U); m_card_info.SD_cid.ManufactDate |= tmp; /* Byte 15 */ tmp = static_cast<uint8_t>(m_CID[3U] & 0x000000FFU); m_card_info.SD_cid.CID_CRC = (tmp & 0xFEU) >> 1U; m_card_info.SD_cid.Reserved2 = 1U; return errorstate; } SD::ESDError SD::select_deselect(uint32_t addr) { send_command(addr, ECMD::SEL_DESEL_CARD, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); return cmd_resp1_error(ECMD::SEL_DESEL_CARD); } SD::ESDError SD::is_card_programming(ECardState *status) { ESDError errorstate = ESDError::OK; __IO uint32_t responseR1 = 0U; send_command(static_cast<uint32_t>(m_RCA << 16U), ECMD::SEND_STATUS, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); while (!get_flag<SDIO_STA::EMasks::CCRCFAIL, SDIO_STA::EMasks::CMDREND, SDIO_STA::EMasks::CTIMEOUT>()) {} if (get_flag<SDIO_STA::EMasks::CTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::CTIMEOUT>(); return ESDError::CMD_RSP_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::CCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::CCRCFAIL>(); return ESDError::CMD_CRC_FAIL; } else { /* No error flag set */ } /* Check response received is of desired command */ if (get_cmd_response() != ECMD::SEND_STATUS) return ESDError::ILLEGAL_CMD; /* Clear all the static flags */ clear_flag<SDIO_STATIC_FLAGS>(); /* We have received response, retrieve it for analysis */ responseR1 = get_response1(); /* Find out card status */ *status = static_cast<ECardState>((responseR1 >> 9U) & 0x0000000FU); if ((responseR1 & EOCRMasks::ERRORBITS) == SD_ALLZERO) return errorstate; if ((responseR1 & EOCRMasks::ADDR_OUT_OF_RANGE) == EOCRMasks::ADDR_OUT_OF_RANGE) return(ESDError::ADDR_OUT_OF_RANGE); if ((responseR1 & EOCRMasks::ADDR_MISALIGNED) == EOCRMasks::ADDR_MISALIGNED) return(ESDError::ADDR_MISALIGNED); if ((responseR1 & EOCRMasks::BLOCK_LEN_ERR) == EOCRMasks::BLOCK_LEN_ERR) return(ESDError::BLOCK_LEN_ERR); if ((responseR1 & EOCRMasks::ERASE_SEQ_ERR) == EOCRMasks::ERASE_SEQ_ERR) return(ESDError::ERASE_SEQ_ERR); if ((responseR1 & EOCRMasks::BAD_ERASE_PARAM) == EOCRMasks::BAD_ERASE_PARAM) return(ESDError::BAD_ERASE_PARAM); if ((responseR1 & EOCRMasks::WRITE_PROT_VIOLATION) == EOCRMasks::WRITE_PROT_VIOLATION) return(ESDError::WRITE_PROT_VIOLATION); if ((responseR1 & EOCRMasks::LOCK_UNLOCK_FAILED) == EOCRMasks::LOCK_UNLOCK_FAILED) return(ESDError::LOCK_UNLOCK_FAILED); if ((responseR1 & EOCRMasks::COM_CRC_FAILED) == EOCRMasks::COM_CRC_FAILED) return(ESDError::COM_CRC_FAILED); if ((responseR1 & EOCRMasks::ILLEGAL_CMD) == EOCRMasks::ILLEGAL_CMD) return(ESDError::ILLEGAL_CMD); if ((responseR1 & EOCRMasks::CARD_ECC_FAILED) == EOCRMasks::CARD_ECC_FAILED) return(ESDError::CARD_ECC_FAILED); if ((responseR1 & EOCRMasks::CC_ERROR) == EOCRMasks::CC_ERROR) return(ESDError::CC_ERROR); if ((responseR1 & EOCRMasks::GENERAL_UNKNOWN_ERROR) == EOCRMasks::GENERAL_UNKNOWN_ERROR) return(ESDError::GENERAL_UNKNOWN_ERROR); if ((responseR1 & EOCRMasks::STREAM_READ_UNDERRUN) == EOCRMasks::STREAM_READ_UNDERRUN) return(ESDError::STREAM_READ_UNDERRUN); if ((responseR1 & EOCRMasks::STREAM_WRITE_OVERRUN) == EOCRMasks::STREAM_WRITE_OVERRUN) return(ESDError::STREAM_WRITE_OVERRUN); if ((responseR1 & EOCRMasks::CID_CSD_OVERWRITE) == EOCRMasks::CID_CSD_OVERWRITE) return(ESDError::CID_CSD_OVERWRITE); if ((responseR1 & EOCRMasks::WP_ERASE_SKIP) == EOCRMasks::WP_ERASE_SKIP) return(ESDError::WP_ERASE_SKIP); if ((responseR1 & EOCRMasks::CARD_ECC_DISABLED) == EOCRMasks::CARD_ECC_DISABLED) return(ESDError::CARD_ECC_DISABLED); if ((responseR1 & EOCRMasks::ERASE_RESET) == EOCRMasks::ERASE_RESET) return(ESDError::ERASE_RESET); if ((responseR1 & EOCRMasks::AKE_SEQ_ERROR) == EOCRMasks::AKE_SEQ_ERROR) return(ESDError::AKE_SEQ_ERROR); return errorstate; } SD::ESDError SD::wide_bus_enable() { ESDError errorstate = ESDError::OK; uint32_t scr[2U] = {0U, 0U}; if ((get_response1() & SD_CARD_LOCKED) == SD_CARD_LOCKED) return ESDError::LOCK_UNLOCK_FAILED; /* Get SCR Register */ errorstate = find_SCR(scr); if (errorstate != ESDError::OK) return errorstate; /* If requested card supports wide bus operation */ if ((scr[1U] & SD_WIDE_BUS_SUPPORT) != SD_ALLZERO) { /* Send CMD55 APP_CMD with argument as card's RCA.*/ send_command(static_cast<uint32_t>(m_RCA << 16U), ECMD::APP_CMD, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::APP_CMD); if(errorstate != ESDError::OK) return errorstate; /* Send ACMD6 APP_CMD with argument as 2 for wide bus mode */ send_command(2, ECMD::APP_SD_SET_BUSWIDTH, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::APP_SD_SET_BUSWIDTH); } else return ESDError::REQUEST_NOT_APPLICABLE; return errorstate; } SD::ESDError SD::wide_bus_disable() { ESDError errorstate = ESDError::OK; uint32_t scr[2U] = {0U, 0U}; if ((get_response1() & SD_CARD_LOCKED) == SD_CARD_LOCKED) return ESDError::LOCK_UNLOCK_FAILED; /* Get SCR Register */ errorstate = find_SCR(scr); if (errorstate != ESDError::OK) return errorstate; /* If requested card supports 1 bit mode operation */ if ((scr[1U] & SD_SINGLE_BUS_SUPPORT) != SD_ALLZERO) { /* Send CMD55 APP_CMD with argument as card's RCA */ send_command(static_cast<uint32_t>(m_RCA << 16U), ECMD::APP_CMD, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::APP_CMD); if(errorstate != ESDError::OK) return errorstate; /* Send ACMD6 APP_CMD with argument as 0 for single bus mode */ send_command(0, ECMD::APP_SD_SET_BUSWIDTH, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::APP_SD_SET_BUSWIDTH); } else return ESDError::REQUEST_NOT_APPLICABLE; return errorstate; } SD::ESDError SD::find_SCR(uint32_t *scr) { ESDError errorstate = ESDError::OK; uint32_t index = 0U; uint32_t tempscr[2U] = {0U, 0U}; /* Set Block Size To 8 Bytes */ /* Send CMD55 APP_CMD with argument as card's RCA */ send_command(8, ECMD::SET_BLOCKLEN, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SET_BLOCKLEN); if (errorstate != ESDError::OK) return errorstate; /* Send CMD55 APP_CMD with argument as card's RCA */ send_command(static_cast<uint32_t>(m_RCA << 16U), ECMD::APP_CMD, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::APP_CMD); if (errorstate != ESDError::OK) return errorstate; data_config(SD_DATATIMEOUT, 8U, EDataBlockSize::_8B, ETransferDir::TO_SDIO, ETransferMode::BLOCK, EDPSM::ENABLE); /* Send ACMD51 SD_APP_SEND_SCR with argument as 0 */ send_command(0, ECMD::SD_APP_SEND_SCR, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SD_APP_SEND_SCR); if (errorstate != ESDError::OK) return errorstate; #ifdef SDIO_STA_STBITERR while(!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND, SDIO_STA::EMasks::STBITERR>()) #else /* SDIO_STA_STBITERR not defined */ while(!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND>()) #endif /* SDIO_STA_STBITERR */ { if(get_flag<SDIO_STA::EMasks::RXDAVL>()) { *(tempscr + index) = read_FIFO(); index++; } } if (get_flag<SDIO_STA::EMasks::DTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::DTIMEOUT>(); return ESDError::DATA_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::DCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::DCRCFAIL>(); return ESDError::DATA_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::RXOVERR>()) { clear_flag<SDIO_STA::EMasks::RXOVERR>(); return ESDError::RX_OVERRUN; } #ifdef SDIO_STA_STBITERR else if (get_flag<SDIO_STA::EMasks::STBITERR>()) { clear_flag<SDIO_STA::EMasks::STBITERR>(); return ESDError::START_BIT_ERR; } #endif /* SDIO_STA_STBITERR */ else { /* No error flag set */ } /* Clear all the static flags */ clear_flag<SDIO_STATIC_FLAGS>(); *(scr + 1U) = ((tempscr[0U] & SD_0TO7BITS) << 24U) | ((tempscr[0U] & SD_8TO15BITS) << 8U) | ((tempscr[0U] & SD_16TO23BITS) >> 8U) | ((tempscr[0U] & SD_24TO31BITS) >> 24U); *(scr) = ((tempscr[1U] & SD_0TO7BITS) << 24U) | ((tempscr[1U] & SD_8TO15BITS) << 8U) | ((tempscr[1U] & SD_16TO23BITS) >> 8U) | ((tempscr[1U] & SD_24TO31BITS) >> 24U); return errorstate; } SD::ECardState SD::get_state() { uint32_t resp1 = 0U; if (send_status(&resp1) != ESDError::OK) return ECardState::ERROR; else return static_cast<ECardState>((resp1 >> 9U) & 0x0FU); } } void ISR::SDIO_IRQ() { ///TODO } #endif //STM32_USE_SD
33.231876
125
0.603546
andreili
a8a9e9cada22d02e04ef8d38652d2316a62eb347
1,786
cpp
C++
01-assignment/vigenere/main.cpp
Feqzz/DCS3101-1-20H
dcdccf63d9eaec23e37cda6827ce208f3cb35728
[ "MIT" ]
null
null
null
01-assignment/vigenere/main.cpp
Feqzz/DCS3101-1-20H
dcdccf63d9eaec23e37cda6827ce208f3cb35728
[ "MIT" ]
null
null
null
01-assignment/vigenere/main.cpp
Feqzz/DCS3101-1-20H
dcdccf63d9eaec23e37cda6827ce208f3cb35728
[ "MIT" ]
null
null
null
#include <iostream> #include <string> std::string vigenereEncrypt(std::string plaintext, std::string key) { char tmp[plaintext.size()]; int outOfBoundsCharacters = 0; for (int i = 0; i < plaintext.size(); i++) { bool isLowerCaseInput; bool isLowerCaseKey; if (static_cast<int>(plaintext[i]) > 64 && static_cast<int>(plaintext[i]) < 91) { isLowerCaseInput = false; } else if (static_cast<int>(plaintext[i]) > 96 && static_cast<int>(plaintext[i]) < 123) { isLowerCaseInput = true; } else { tmp[i] = plaintext[i]; outOfBoundsCharacters++; continue; } const int keyIndex = (i - outOfBoundsCharacters) % key.length(); if (static_cast<int>(key[keyIndex]) > 64 && static_cast<int>(key[keyIndex]) < 91) { isLowerCaseKey = false; } else if (static_cast<int>(key[keyIndex]) > 96 && static_cast<int>(key[keyIndex]) < 123) { isLowerCaseKey = true; } else { std::cout << "The key is illegal! Only alphabet characters are allowed." << std::endl; exit(1); } const int asciiGapInput = isLowerCaseInput ? 97 : 65; const int asciiGapKey = isLowerCaseKey ? 97 : 65; const int indexInAlphabetInput = static_cast<int>(plaintext[i]) - asciiGapInput; const int indexInAlphabetKey = static_cast<int>(key[keyIndex]) - asciiGapKey; tmp[i] = static_cast<char>(((indexInAlphabetInput + indexInAlphabetKey) % 26) + asciiGapInput); } return tmp; } void printUsage() { std::cout << "Usage: ./vigenere <text> <key1> ... <key N>" << std::endl; } int main(int argc, char** argv) { if (argc < 3) { printUsage(); exit(1); } std::string text = argv[1]; for (int i = 0; i < (argc - 2); i++) { const std::string key = argv[i + 2]; text = vigenereEncrypt(text, key); } std::cout << text << std::endl; return 0; }
23.194805
97
0.643897
Feqzz
a8aef35415225fc1967e15a145501c3b551bd520
1,235
cpp
C++
test/gtx/gtx_scalar_multiplication.cpp
hrehfeld/glm_working
8dd5acc8ccc1fb8b6557670281c9786ee643e629
[ "MIT" ]
null
null
null
test/gtx/gtx_scalar_multiplication.cpp
hrehfeld/glm_working
8dd5acc8ccc1fb8b6557670281c9786ee643e629
[ "MIT" ]
null
null
null
test/gtx/gtx_scalar_multiplication.cpp
hrehfeld/glm_working
8dd5acc8ccc1fb8b6557670281c9786ee643e629
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2014 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2014-09-22 // Updated : 2014-09-22 // Licence : This source is under MIT licence // File : test/gtx/gtx_scalar_multiplication.cpp /////////////////////////////////////////////////////////////////////////////////////////////////// #include <glm/glm.hpp> #if GLM_HAS_TEMPLATE_ALIASES #include <glm/gtx/scalar_multiplication.hpp> int main() { int Error(0); glm::vec3 v(0.5, 3.1, -9.1); Error += glm::all(glm::equal(v, 1.0 * v)) ? 0 : 1; Error += glm::all(glm::equal(v, 1 * v)) ? 0 : 1; Error += glm::all(glm::equal(v, 1u * v)) ? 0 : 1; glm::mat3 m(1, 2, 3, 4, 5, 6, 7, 8, 9); glm::vec3 w = 0.5f * m * v; Error += glm::all(glm::equal((m*v)/2, w)) ? 0 : 1; Error += glm::all(glm::equal(m*(v/2), w)) ? 0 : 1; Error += glm::all(glm::equal((m/2)*v, w)) ? 0 : 1; Error += glm::all(glm::equal((0.5*m)*v, w)) ? 0 : 1; Error += glm::all(glm::equal(0.5*(m*v), w)) ? 0 : 1; return Error; } #else int main() { return 0; } #endif
28.068182
99
0.434008
hrehfeld
a8b22945fcd3c79673df188e2016fed380cf4809
326
cpp
C++
Module-2/Problem_7c.cpp
farhanmasud/ruet-discrete-mathematics
4c510c48a6e5f3ed8f202a57c4761c6a1f1286ea
[ "MIT" ]
null
null
null
Module-2/Problem_7c.cpp
farhanmasud/ruet-discrete-mathematics
4c510c48a6e5f3ed8f202a57c4761c6a1f1286ea
[ "MIT" ]
null
null
null
Module-2/Problem_7c.cpp
farhanmasud/ruet-discrete-mathematics
4c510c48a6e5f3ed8f202a57c4761c6a1f1286ea
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int sum = 0; int l1 = 0; int u1 = 5; int l2 = 0; int u2 = 10; for(int i = l1; i <= u1; i++) { for(int j = l2; j <= u2; j++) { sum = sum + i + j; } } cout << "The sum is: " << sum; return 0; }
13.583333
37
0.389571
farhanmasud
a8bc210c67bfebf4f0bc8d51a5cbe72c2bbc0e3a
17,616
cpp
C++
source/glbinding/source/gl/functions_d.cpp
j-o/glbinding
c1e3a571ea4ee7058879e46777ba728a58ca2fa8
[ "MIT" ]
null
null
null
source/glbinding/source/gl/functions_d.cpp
j-o/glbinding
c1e3a571ea4ee7058879e46777ba728a58ca2fa8
[ "MIT" ]
null
null
null
source/glbinding/source/gl/functions_d.cpp
j-o/glbinding
c1e3a571ea4ee7058879e46777ba728a58ca2fa8
[ "MIT" ]
null
null
null
#include "../Binding_pch.h" #include <glbinding/gl/functions.h> using namespace glbinding; namespace gl { void glDebugMessageCallback(GLDEBUGPROC callback, const void * userParam) { return Binding::DebugMessageCallback(callback, userParam); } void glDebugMessageCallbackAMD(GLDEBUGPROCAMD callback, void * userParam) { return Binding::DebugMessageCallbackAMD(callback, userParam); } void glDebugMessageCallbackARB(GLDEBUGPROCARB callback, const void * userParam) { return Binding::DebugMessageCallbackARB(callback, userParam); } void glDebugMessageControl(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint * ids, GLboolean enabled) { return Binding::DebugMessageControl(source, type, severity, count, ids, enabled); } void glDebugMessageControlARB(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint * ids, GLboolean enabled) { return Binding::DebugMessageControlARB(source, type, severity, count, ids, enabled); } void glDebugMessageEnableAMD(GLenum category, GLenum severity, GLsizei count, const GLuint * ids, GLboolean enabled) { return Binding::DebugMessageEnableAMD(category, severity, count, ids, enabled); } void glDebugMessageInsert(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar * buf) { return Binding::DebugMessageInsert(source, type, id, severity, length, buf); } void glDebugMessageInsertAMD(GLenum category, GLenum severity, GLuint id, GLsizei length, const GLchar * buf) { return Binding::DebugMessageInsertAMD(category, severity, id, length, buf); } void glDebugMessageInsertARB(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar * buf) { return Binding::DebugMessageInsertARB(source, type, id, severity, length, buf); } void glDeformSGIX(FfdMaskSGIX mask) { return Binding::DeformSGIX(mask); } void glDeformationMap3dSGIX(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble * points) { return Binding::DeformationMap3dSGIX(target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, w1, w2, wstride, worder, points); } void glDeformationMap3fSGIX(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat * points) { return Binding::DeformationMap3fSGIX(target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, w1, w2, wstride, worder, points); } void glDeleteAsyncMarkersSGIX(GLuint marker, GLsizei range) { return Binding::DeleteAsyncMarkersSGIX(marker, range); } void glDeleteBuffers(GLsizei n, const GLuint * buffers) { return Binding::DeleteBuffers(n, buffers); } void glDeleteBuffersARB(GLsizei n, const GLuint * buffers) { return Binding::DeleteBuffersARB(n, buffers); } void glDeleteCommandListsNV(GLsizei n, const GLuint * lists) { return Binding::DeleteCommandListsNV(n, lists); } void glDeleteFencesAPPLE(GLsizei n, const GLuint * fences) { return Binding::DeleteFencesAPPLE(n, fences); } void glDeleteFencesNV(GLsizei n, const GLuint * fences) { return Binding::DeleteFencesNV(n, fences); } void glDeleteFragmentShaderATI(GLuint id) { return Binding::DeleteFragmentShaderATI(id); } void glDeleteFramebuffers(GLsizei n, const GLuint * framebuffers) { return Binding::DeleteFramebuffers(n, framebuffers); } void glDeleteFramebuffersEXT(GLsizei n, const GLuint * framebuffers) { return Binding::DeleteFramebuffersEXT(n, framebuffers); } void glDeleteLists(GLuint list, GLsizei range) { return Binding::DeleteLists(list, range); } void glDeleteMemoryObjectsEXT(GLsizei n, const GLuint * memoryObjects) { return Binding::DeleteMemoryObjectsEXT(n, memoryObjects); } void glDeleteNamedStringARB(GLint namelen, const GLchar * name) { return Binding::DeleteNamedStringARB(namelen, name); } void glDeleteNamesAMD(GLenum identifier, GLuint num, const GLuint * names) { return Binding::DeleteNamesAMD(identifier, num, names); } void glDeleteObjectARB(GLhandleARB obj) { return Binding::DeleteObjectARB(obj); } void glDeleteOcclusionQueriesNV(GLsizei n, const GLuint * ids) { return Binding::DeleteOcclusionQueriesNV(n, ids); } void glDeletePathsNV(GLuint path, GLsizei range) { return Binding::DeletePathsNV(path, range); } void glDeletePerfMonitorsAMD(GLsizei n, GLuint * monitors) { return Binding::DeletePerfMonitorsAMD(n, monitors); } void glDeletePerfQueryINTEL(GLuint queryHandle) { return Binding::DeletePerfQueryINTEL(queryHandle); } void glDeleteProgram(GLuint program) { return Binding::DeleteProgram(program); } void glDeleteProgramPipelines(GLsizei n, const GLuint * pipelines) { return Binding::DeleteProgramPipelines(n, pipelines); } void glDeleteProgramsARB(GLsizei n, const GLuint * programs) { return Binding::DeleteProgramsARB(n, programs); } void glDeleteProgramsNV(GLsizei n, const GLuint * programs) { return Binding::DeleteProgramsNV(n, programs); } void glDeleteQueries(GLsizei n, const GLuint * ids) { return Binding::DeleteQueries(n, ids); } void glDeleteQueriesARB(GLsizei n, const GLuint * ids) { return Binding::DeleteQueriesARB(n, ids); } void glDeleteRenderbuffers(GLsizei n, const GLuint * renderbuffers) { return Binding::DeleteRenderbuffers(n, renderbuffers); } void glDeleteRenderbuffersEXT(GLsizei n, const GLuint * renderbuffers) { return Binding::DeleteRenderbuffersEXT(n, renderbuffers); } void glDeleteSamplers(GLsizei count, const GLuint * samplers) { return Binding::DeleteSamplers(count, samplers); } void glDeleteSemaphoresEXT(GLsizei n, const GLuint * semaphores) { return Binding::DeleteSemaphoresEXT(n, semaphores); } void glDeleteShader(GLuint shader) { return Binding::DeleteShader(shader); } void glDeleteStatesNV(GLsizei n, const GLuint * states) { return Binding::DeleteStatesNV(n, states); } void glDeleteSync(GLsync sync) { return Binding::DeleteSync(sync); } void glDeleteTextures(GLsizei n, const GLuint * textures) { return Binding::DeleteTextures(n, textures); } void glDeleteTexturesEXT(GLsizei n, const GLuint * textures) { return Binding::DeleteTexturesEXT(n, textures); } void glDeleteTransformFeedbacks(GLsizei n, const GLuint * ids) { return Binding::DeleteTransformFeedbacks(n, ids); } void glDeleteTransformFeedbacksNV(GLsizei n, const GLuint * ids) { return Binding::DeleteTransformFeedbacksNV(n, ids); } void glDeleteVertexArrays(GLsizei n, const GLuint * arrays) { return Binding::DeleteVertexArrays(n, arrays); } void glDeleteVertexArraysAPPLE(GLsizei n, const GLuint * arrays) { return Binding::DeleteVertexArraysAPPLE(n, arrays); } void glDeleteVertexShaderEXT(GLuint id) { return Binding::DeleteVertexShaderEXT(id); } void glDepthBoundsEXT(GLclampd zmin, GLclampd zmax) { return Binding::DepthBoundsEXT(zmin, zmax); } void glDepthBoundsdNV(GLdouble zmin, GLdouble zmax) { return Binding::DepthBoundsdNV(zmin, zmax); } void glDepthFunc(GLenum func) { return Binding::DepthFunc(func); } void glDepthMask(GLboolean flag) { return Binding::DepthMask(flag); } void glDepthRange(GLdouble near_, GLdouble far_) { return Binding::DepthRange(near_, far_); } void glDepthRangeArrayv(GLuint first, GLsizei count, const GLdouble * v) { return Binding::DepthRangeArrayv(first, count, v); } void glDepthRangeIndexed(GLuint index, GLdouble n, GLdouble f) { return Binding::DepthRangeIndexed(index, n, f); } void glDepthRangedNV(GLdouble zNear, GLdouble zFar) { return Binding::DepthRangedNV(zNear, zFar); } void glDepthRangef(GLfloat n, GLfloat f) { return Binding::DepthRangef(n, f); } void glDepthRangefOES(GLclampf n, GLclampf f) { return Binding::DepthRangefOES(n, f); } void glDepthRangexOES(GLfixed n, GLfixed f) { return Binding::DepthRangexOES(n, f); } void glDetachObjectARB(GLhandleARB containerObj, GLhandleARB attachedObj) { return Binding::DetachObjectARB(containerObj, attachedObj); } void glDetachShader(GLuint program, GLuint shader) { return Binding::DetachShader(program, shader); } void glDetailTexFuncSGIS(GLenum target, GLsizei n, const GLfloat * points) { return Binding::DetailTexFuncSGIS(target, n, points); } void glDisable(GLenum cap) { return Binding::Disable(cap); } void glDisableClientState(GLenum array) { return Binding::DisableClientState(array); } void glDisableClientStateIndexedEXT(GLenum array, GLuint index) { return Binding::DisableClientStateIndexedEXT(array, index); } void glDisableClientStateiEXT(GLenum array, GLuint index) { return Binding::DisableClientStateiEXT(array, index); } void glDisableIndexedEXT(GLenum target, GLuint index) { return Binding::DisableIndexedEXT(target, index); } void glDisableVariantClientStateEXT(GLuint id) { return Binding::DisableVariantClientStateEXT(id); } void glDisableVertexArrayAttrib(GLuint vaobj, GLuint index) { return Binding::DisableVertexArrayAttrib(vaobj, index); } void glDisableVertexArrayAttribEXT(GLuint vaobj, GLuint index) { return Binding::DisableVertexArrayAttribEXT(vaobj, index); } void glDisableVertexArrayEXT(GLuint vaobj, GLenum array) { return Binding::DisableVertexArrayEXT(vaobj, array); } void glDisableVertexAttribAPPLE(GLuint index, GLenum pname) { return Binding::DisableVertexAttribAPPLE(index, pname); } void glDisableVertexAttribArray(GLuint index) { return Binding::DisableVertexAttribArray(index); } void glDisableVertexAttribArrayARB(GLuint index) { return Binding::DisableVertexAttribArrayARB(index); } void glDisablei(GLenum target, GLuint index) { return Binding::Disablei(target, index); } void glDispatchCompute(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z) { return Binding::DispatchCompute(num_groups_x, num_groups_y, num_groups_z); } void glDispatchComputeGroupSizeARB(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z, GLuint group_size_x, GLuint group_size_y, GLuint group_size_z) { return Binding::DispatchComputeGroupSizeARB(num_groups_x, num_groups_y, num_groups_z, group_size_x, group_size_y, group_size_z); } void glDispatchComputeIndirect(GLintptr indirect) { return Binding::DispatchComputeIndirect(indirect); } void glDrawArrays(GLenum mode, GLint first, GLsizei count) { return Binding::DrawArrays(mode, first, count); } void glDrawArraysEXT(GLenum mode, GLint first, GLsizei count) { return Binding::DrawArraysEXT(mode, first, count); } void glDrawArraysIndirect(GLenum mode, const void * indirect) { return Binding::DrawArraysIndirect(mode, indirect); } void glDrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei instancecount) { return Binding::DrawArraysInstanced(mode, first, count, instancecount); } void glDrawArraysInstancedARB(GLenum mode, GLint first, GLsizei count, GLsizei primcount) { return Binding::DrawArraysInstancedARB(mode, first, count, primcount); } void glDrawArraysInstancedBaseInstance(GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance) { return Binding::DrawArraysInstancedBaseInstance(mode, first, count, instancecount, baseinstance); } void glDrawArraysInstancedEXT(GLenum mode, GLint start, GLsizei count, GLsizei primcount) { return Binding::DrawArraysInstancedEXT(mode, start, count, primcount); } void glDrawBuffer(GLenum buf) { return Binding::DrawBuffer(buf); } void glDrawBuffers(GLsizei n, const GLenum * bufs) { return Binding::DrawBuffers(n, bufs); } void glDrawBuffersARB(GLsizei n, const GLenum * bufs) { return Binding::DrawBuffersARB(n, bufs); } void glDrawBuffersATI(GLsizei n, const GLenum * bufs) { return Binding::DrawBuffersATI(n, bufs); } void glDrawCommandsAddressNV(GLenum primitiveMode, const GLuint64 * indirects, const GLsizei * sizes, GLuint count) { return Binding::DrawCommandsAddressNV(primitiveMode, indirects, sizes, count); } void glDrawCommandsNV(GLenum primitiveMode, GLuint buffer, const GLintptr * indirects, const GLsizei * sizes, GLuint count) { return Binding::DrawCommandsNV(primitiveMode, buffer, indirects, sizes, count); } void glDrawCommandsStatesAddressNV(const GLuint64 * indirects, const GLsizei * sizes, const GLuint * states, const GLuint * fbos, GLuint count) { return Binding::DrawCommandsStatesAddressNV(indirects, sizes, states, fbos, count); } void glDrawCommandsStatesNV(GLuint buffer, const GLintptr * indirects, const GLsizei * sizes, const GLuint * states, const GLuint * fbos, GLuint count) { return Binding::DrawCommandsStatesNV(buffer, indirects, sizes, states, fbos, count); } void glDrawElementArrayAPPLE(GLenum mode, GLint first, GLsizei count) { return Binding::DrawElementArrayAPPLE(mode, first, count); } void glDrawElementArrayATI(GLenum mode, GLsizei count) { return Binding::DrawElementArrayATI(mode, count); } void glDrawElements(GLenum mode, GLsizei count, GLenum type, const void * indices) { return Binding::DrawElements(mode, count, type, indices); } void glDrawElementsBaseVertex(GLenum mode, GLsizei count, GLenum type, const void * indices, GLint basevertex) { return Binding::DrawElementsBaseVertex(mode, count, type, indices, basevertex); } void glDrawElementsIndirect(GLenum mode, GLenum type, const void * indirect) { return Binding::DrawElementsIndirect(mode, type, indirect); } void glDrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount) { return Binding::DrawElementsInstanced(mode, count, type, indices, instancecount); } void glDrawElementsInstancedARB(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei primcount) { return Binding::DrawElementsInstancedARB(mode, count, type, indices, primcount); } void glDrawElementsInstancedBaseInstance(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount, GLuint baseinstance) { return Binding::DrawElementsInstancedBaseInstance(mode, count, type, indices, instancecount, baseinstance); } void glDrawElementsInstancedBaseVertex(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount, GLint basevertex) { return Binding::DrawElementsInstancedBaseVertex(mode, count, type, indices, instancecount, basevertex); } void glDrawElementsInstancedBaseVertexBaseInstance(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance) { return Binding::DrawElementsInstancedBaseVertexBaseInstance(mode, count, type, indices, instancecount, basevertex, baseinstance); } void glDrawElementsInstancedEXT(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei primcount) { return Binding::DrawElementsInstancedEXT(mode, count, type, indices, primcount); } void glDrawMeshArraysSUN(GLenum mode, GLint first, GLsizei count, GLsizei width) { return Binding::DrawMeshArraysSUN(mode, first, count, width); } void glDrawPixels(GLsizei width, GLsizei height, GLenum format, GLenum type, const void * pixels) { return Binding::DrawPixels(width, height, format, type, pixels); } void glDrawRangeElementArrayAPPLE(GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count) { return Binding::DrawRangeElementArrayAPPLE(mode, start, end, first, count); } void glDrawRangeElementArrayATI(GLenum mode, GLuint start, GLuint end, GLsizei count) { return Binding::DrawRangeElementArrayATI(mode, start, end, count); } void glDrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void * indices) { return Binding::DrawRangeElements(mode, start, end, count, type, indices); } void glDrawRangeElementsBaseVertex(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void * indices, GLint basevertex) { return Binding::DrawRangeElementsBaseVertex(mode, start, end, count, type, indices, basevertex); } void glDrawRangeElementsEXT(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void * indices) { return Binding::DrawRangeElementsEXT(mode, start, end, count, type, indices); } void glDrawTextureNV(GLuint texture, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1) { return Binding::DrawTextureNV(texture, sampler, x0, y0, x1, y1, z, s0, t0, s1, t1); } void glDrawTransformFeedback(GLenum mode, GLuint id) { return Binding::DrawTransformFeedback(mode, id); } void glDrawTransformFeedbackInstanced(GLenum mode, GLuint id, GLsizei instancecount) { return Binding::DrawTransformFeedbackInstanced(mode, id, instancecount); } void glDrawTransformFeedbackNV(GLenum mode, GLuint id) { return Binding::DrawTransformFeedbackNV(mode, id); } void glDrawTransformFeedbackStream(GLenum mode, GLuint id, GLuint stream) { return Binding::DrawTransformFeedbackStream(mode, id, stream); } void glDrawTransformFeedbackStreamInstanced(GLenum mode, GLuint id, GLuint stream, GLsizei instancecount) { return Binding::DrawTransformFeedbackStreamInstanced(mode, id, stream, instancecount); } void glDrawVkImageNV(GLuint64 vkImage, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1) { return Binding::DrawVkImageNV(vkImage, sampler, x0, y0, x1, y1, z, s0, t0, s1, t1); } } // namespace gl
28.504854
232
0.770322
j-o
a8c03f48697e81f1d38f294227fc5696fc575a31
23,961
cpp
C++
_studio/enctools/src/mfx_enctools_common.cpp
alexelizarov/oneVPL-intel-gpu
1aecebeea5e73670f194481b4c1402628837506f
[ "MIT" ]
null
null
null
_studio/enctools/src/mfx_enctools_common.cpp
alexelizarov/oneVPL-intel-gpu
1aecebeea5e73670f194481b4c1402628837506f
[ "MIT" ]
null
null
null
_studio/enctools/src/mfx_enctools_common.cpp
alexelizarov/oneVPL-intel-gpu
1aecebeea5e73670f194481b4c1402628837506f
[ "MIT" ]
1
2021-07-13T08:25:02.000Z
2021-07-13T08:25:02.000Z
// Copyright (c) 2019-2021 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. #include "mfx_enctools.h" #include <algorithm> #include <math.h> mfxExtBuffer* Et_GetExtBuffer(mfxExtBuffer** extBuf, mfxU32 numExtBuf, mfxU32 id) { if (extBuf != 0) { for (mfxU16 i = 0; i < numExtBuf; i++) { if (extBuf[i] != 0 && extBuf[i]->BufferId == id) // assuming aligned buffers return (extBuf[i]); } } return 0; } mfxStatus InitCtrl(mfxVideoParam const & par, mfxEncToolsCtrl *ctrl) { MFX_CHECK_NULL_PTR1(ctrl); mfxExtCodingOption *CO = (mfxExtCodingOption *)Et_GetExtBuffer(par.ExtParam, par.NumExtParam, MFX_EXTBUFF_CODING_OPTION); mfxExtCodingOption2 *CO2 = (mfxExtCodingOption2 *)Et_GetExtBuffer(par.ExtParam, par.NumExtParam, MFX_EXTBUFF_CODING_OPTION2); mfxExtCodingOption3 *CO3 = (mfxExtCodingOption3 *)Et_GetExtBuffer(par.ExtParam, par.NumExtParam, MFX_EXTBUFF_CODING_OPTION3); MFX_CHECK_NULL_PTR3(CO, CO2, CO3); ctrl = {}; ctrl->CodecId = par.mfx.CodecId; ctrl->CodecProfile = par.mfx.CodecProfile; ctrl->CodecLevel = par.mfx.CodecLevel; ctrl->FrameInfo = par.mfx.FrameInfo; ctrl->IOPattern = par.IOPattern; ctrl->MaxDelayInFrames = CO2->LookAheadDepth; ctrl->MaxGopSize = par.mfx.GopPicSize; ctrl->MaxGopRefDist = par.mfx.GopRefDist; ctrl->MaxIDRDist = par.mfx.GopPicSize * (par.mfx.IdrInterval + 1); ctrl->BRefType = CO2->BRefType; ctrl->ScenarioInfo = CO3->ScenarioInfo; // Rate control info mfxU32 mult = par.mfx.BRCParamMultiplier ? par.mfx.BRCParamMultiplier : 1; bool BRC = (par.mfx.RateControlMethod == MFX_RATECONTROL_CBR || par.mfx.RateControlMethod == MFX_RATECONTROL_VBR); ctrl->RateControlMethod = par.mfx.RateControlMethod; //CBR, VBR, CRF,CQP if (!BRC) { ctrl->QPLevel[0] = par.mfx.QPI; ctrl->QPLevel[1] = par.mfx.QPP; ctrl->QPLevel[2] = par.mfx.QPB; } else { ctrl->TargetKbps = par.mfx.TargetKbps*mult; ctrl->MaxKbps = par.mfx.MaxKbps*mult; ctrl->HRDConformance = MFX_BRC_NO_HRD; if (!IsOff(CO->NalHrdConformance) && !IsOff(CO->VuiNalHrdParameters)) ctrl->HRDConformance = MFX_BRC_HRD_STRONG; else if (IsOn(CO->NalHrdConformance) && IsOff(CO->VuiNalHrdParameters)) ctrl->HRDConformance = MFX_BRC_HRD_WEAK; if (ctrl->HRDConformance) { ctrl->BufferSizeInKB = par.mfx.BufferSizeInKB*mult; //if HRDConformance is ON ctrl->InitialDelayInKB = par.mfx.InitialDelayInKB*mult; //if HRDConformance is ON } else { ctrl->ConvergencePeriod = 0; //if HRDConformance is OFF, 0 - the period is whole stream, ctrl->Accuracy = 10; //if HRDConformance is OFF } ctrl->WinBRCMaxAvgKbps = CO3->WinBRCMaxAvgKbps*mult; ctrl->WinBRCSize = CO3->WinBRCSize; ctrl->MaxFrameSizeInBytes[0] = CO3->MaxFrameSizeI ? CO3->MaxFrameSizeI : CO2->MaxFrameSize; // MaxFrameSize limitation ctrl->MaxFrameSizeInBytes[1] = CO3->MaxFrameSizeP ? CO3->MaxFrameSizeP : CO2->MaxFrameSize; ctrl->MaxFrameSizeInBytes[2] = CO2->MaxFrameSize; ctrl->MinQPLevel[0] = CO2->MinQPI; //QP range limitations ctrl->MinQPLevel[1] = CO2->MinQPP; ctrl->MinQPLevel[2] = CO2->MinQPB; ctrl->MaxQPLevel[0] = CO2->MaxQPI; //QP range limitations ctrl->MaxQPLevel[1] = CO2->MaxQPP; ctrl->MaxQPLevel[2] = CO2->MaxQPB; ctrl->PanicMode = CO3->BRCPanicMode; } return MFX_ERR_NONE; } inline void SetToolsStatus(mfxExtEncToolsConfig* conf, bool bOn) { conf->SceneChange = conf->AdaptiveI = conf->AdaptiveB = conf->AdaptiveRefP = conf->AdaptiveRefB = conf->AdaptiveLTR = conf->AdaptivePyramidQuantP = conf->AdaptivePyramidQuantB = conf->AdaptiveQuantMatrices = conf->BRCBufferHints = conf->BRC = mfxU16(bOn ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF); } inline void CopyPreEncSCTools(mfxExtEncToolsConfig const & confIn, mfxExtEncToolsConfig* confOut) { confOut->AdaptiveI = confIn.AdaptiveI; confOut->AdaptiveB = confIn.AdaptiveB; confOut->AdaptiveRefP = confIn.AdaptiveRefP; confOut->AdaptiveRefB = confIn.AdaptiveRefB; confOut->AdaptiveLTR = confIn.AdaptiveLTR; confOut->AdaptivePyramidQuantP = confIn.AdaptivePyramidQuantP; confOut->AdaptivePyramidQuantB = confIn.AdaptivePyramidQuantB; } inline void OffPreEncSCDTools(mfxExtEncToolsConfig* conf) { mfxExtEncToolsConfig confIn = {}; SetToolsStatus(&confIn, false); CopyPreEncSCTools(confIn, conf); } inline void CopyPreEncLATools(mfxExtEncToolsConfig const & confIn, mfxExtEncToolsConfig* confOut) { confOut->AdaptiveQuantMatrices = confIn.AdaptiveQuantMatrices; confOut->BRCBufferHints = confIn.BRCBufferHints; confOut->AdaptivePyramidQuantP = confIn.AdaptivePyramidQuantP; confOut->AdaptiveI = confIn.AdaptiveI; } inline void OffPreEncLATools(mfxExtEncToolsConfig* conf) { mfxExtEncToolsConfig confIn = {}; SetToolsStatus(&confIn, false); CopyPreEncLATools(confIn, conf); } inline bool isPreEncSCD(mfxExtEncToolsConfig const & conf, mfxEncToolsCtrl const & ctrl) { return ((IsOn(conf.AdaptiveI) || IsOn(conf.AdaptiveB) || IsOn(conf.AdaptiveRefP) || IsOn(conf.AdaptiveRefB) || IsOn(conf.AdaptiveLTR) || IsOn(conf.AdaptivePyramidQuantP) || IsOn(conf.AdaptivePyramidQuantB)) && ctrl.ScenarioInfo != MFX_SCENARIO_GAME_STREAMING); } inline bool isPreEncLA(mfxExtEncToolsConfig const & conf, mfxEncToolsCtrl const & ctrl) { return ( ctrl.ScenarioInfo == MFX_SCENARIO_GAME_STREAMING && (IsOn(conf.AdaptiveI) || IsOn(conf.AdaptiveQuantMatrices) || IsOn(conf.BRCBufferHints) || IsOn(conf.AdaptivePyramidQuantP))); } mfxStatus EncTools::GetSupportedConfig(mfxExtEncToolsConfig* config, mfxEncToolsCtrl const * ctrl) { MFX_CHECK_NULL_PTR2(config, ctrl); SetToolsStatus(config, false); config->BRC = (mfxU16)((ctrl->RateControlMethod == MFX_RATECONTROL_CBR || ctrl->RateControlMethod == MFX_RATECONTROL_VBR)? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF); if (ctrl->ScenarioInfo != MFX_SCENARIO_GAME_STREAMING) { if (ctrl->MaxGopRefDist == 8 || ctrl->MaxGopRefDist == 4 || ctrl->MaxGopRefDist == 2 || ctrl->MaxGopRefDist == 1) { config->SceneChange = MFX_CODINGOPTION_ON; config->AdaptiveI = MFX_CODINGOPTION_ON; config->AdaptiveB = MFX_CODINGOPTION_ON; config->AdaptiveRefP = MFX_CODINGOPTION_ON; config->AdaptiveRefB = MFX_CODINGOPTION_ON; config->AdaptiveLTR = MFX_CODINGOPTION_ON; config->AdaptivePyramidQuantP = MFX_CODINGOPTION_ON; config->AdaptivePyramidQuantB = MFX_CODINGOPTION_ON; } } #if defined (MFX_ENABLE_ENCTOOLS_LPLA) else { config->AdaptiveQuantMatrices = MFX_CODINGOPTION_ON; config->BRCBufferHints = MFX_CODINGOPTION_ON; config->SceneChange = MFX_CODINGOPTION_ON; config->AdaptivePyramidQuantP = MFX_CODINGOPTION_ON; config->AdaptiveI = MFX_CODINGOPTION_ON; config->AdaptiveB = MFX_CODINGOPTION_ON; config->AdaptivePyramidQuantB = MFX_CODINGOPTION_ON; } #endif return MFX_ERR_NONE; } mfxStatus EncTools::GetActiveConfig(mfxExtEncToolsConfig* pConfig) { MFX_CHECK(m_bInit, MFX_ERR_NOT_INITIALIZED); MFX_CHECK_NULL_PTR1(pConfig); *pConfig = m_config; return MFX_ERR_NONE; } mfxStatus EncTools::GetDelayInFrames(mfxExtEncToolsConfig const * config, mfxEncToolsCtrl const * ctrl, mfxU32 *numFrames) { MFX_CHECK_NULL_PTR3(config, ctrl, numFrames); //to fix: delay should be asked from m_scd *numFrames = (isPreEncSCD(*config, *ctrl)) ? 8 : 0; // #if defined (MFX_ENABLE_ENCTOOLS_LPLA) if (isPreEncLA(*config, *ctrl)) { *numFrames = std::max(*numFrames, (mfxU32)ctrl->MaxDelayInFrames); } #endif return MFX_ERR_NONE; } mfxStatus EncTools::InitVPP(mfxEncToolsCtrl const & ctrl) { MFX_CHECK(!m_bVPPInit, MFX_ERR_UNDEFINED_BEHAVIOR); MFX_CHECK(m_device && m_pAllocator, MFX_ERR_UNDEFINED_BEHAVIOR); mfxStatus sts; if (mfxSession(m_mfxSession) == 0) { mfxInitParam initPar = {}; initPar.Version.Major = 1; initPar.Version.Minor = 0; initPar.Implementation = MFX_IMPL_HARDWARE; initPar.Implementation |= (m_deviceType == MFX_HANDLE_D3D11_DEVICE ? MFX_IMPL_VIA_D3D11 : (m_deviceType == MFX_HANDLE_DIRECT3D_DEVICE_MANAGER9 ? MFX_IMPL_VIA_D3D9 : MFX_IMPL_VIA_VAAPI)); initPar.GPUCopy = MFX_GPUCOPY_DEFAULT; sts = m_mfxSession.InitEx(initPar); MFX_CHECK_STS(sts); } //mfxVersion version; // real API version with which library is initialized //sts = MFXQueryVersion(m_mfxSession, &version); // get real API version of the loaded library //MFX_CHECK_STS(sts); sts = m_mfxSession.SetFrameAllocator(m_pAllocator); MFX_CHECK_STS(sts); sts = m_mfxSession.SetHandle((mfxHandleType)m_deviceType, m_device); MFX_CHECK_STS(sts); m_pmfxVPP.reset(new MFXVideoVPP(m_mfxSession)); MFX_CHECK(m_pmfxVPP, MFX_ERR_MEMORY_ALLOC); sts = InitMfxVppParams(ctrl); MFX_CHECK_STS(sts); mfxExtVPPScaling vppScalingMode = {}; vppScalingMode.Header.BufferId = MFX_EXTBUFF_VPP_SCALING; vppScalingMode.Header.BufferSz = sizeof(vppScalingMode); vppScalingMode.ScalingMode = MFX_SCALING_MODE_LOWPOWER; vppScalingMode.InterpolationMethod = MFX_INTERPOLATION_NEAREST_NEIGHBOR; std::vector<mfxExtBuffer*> extParams; extParams.push_back((mfxExtBuffer *)&vppScalingMode); m_mfxVppParams.ExtParam = extParams.data(); m_mfxVppParams.NumExtParam = (mfxU16)extParams.size(); sts = m_pmfxVPP->Init(&m_mfxVppParams); MFX_CHECK_STS(sts); mfxFrameAllocRequest VppRequest[2]; sts = m_pmfxVPP->QueryIOSurf(&m_mfxVppParams, VppRequest); MFX_CHECK_STS(sts); VppRequest[1].Type |= MFX_MEMTYPE_FROM_DECODE; // ffmpeg's qsv allocator requires MFX_MEMTYPE_FROM_DECODE or MFX_MEMTYPE_FROM_ENCODE sts = m_pAllocator->Alloc(m_pAllocator->pthis, &(VppRequest[1]), &m_VppResponse); MFX_CHECK_STS(sts); m_pIntSurfaces.resize(m_VppResponse.NumFrameActual); for (mfxU32 i = 0; i < (mfxU32)m_pIntSurfaces.size(); i++) { m_pIntSurfaces[i] = {}; m_pIntSurfaces[i].Info = m_mfxVppParams.vpp.Out; m_pIntSurfaces[i].Data.MemId = m_VppResponse.mids[i]; } m_bVPPInit = true; return MFX_ERR_NONE; } mfxStatus EncTools::InitMfxVppParams(mfxEncToolsCtrl const & ctrl) { m_mfxVppParams.IOPattern = ctrl.IOPattern | MFX_IOPATTERN_OUT_VIDEO_MEMORY; m_mfxVppParams.vpp.In = ctrl.FrameInfo; m_mfxVppParams.vpp.Out = m_mfxVppParams.vpp.In; if (isPreEncSCD(m_config, ctrl)) { mfxFrameInfo frameInfo; mfxStatus sts = m_scd.GetInputFrameInfo(frameInfo); MFX_CHECK_STS(sts); m_mfxVppParams.vpp.Out.Width = frameInfo.Width; m_mfxVppParams.vpp.Out.Height = frameInfo.Height; m_mfxVppParams.vpp.Out.CropW = m_mfxVppParams.vpp.Out.Width; m_mfxVppParams.vpp.Out.CropH = m_mfxVppParams.vpp.Out.Height; } #if defined (MFX_ENABLE_ENCTOOLS_LPLA) else // LPLA { if (!m_mfxVppParams.vpp.In.CropW) m_mfxVppParams.vpp.In.CropW = m_mfxVppParams.vpp.In.Width; if (!m_mfxVppParams.vpp.In.CropH) m_mfxVppParams.vpp.In.CropH = m_mfxVppParams.vpp.In.Height; mfxU32 downscale = 0; m_lpLookAhead.GetDownScaleParams(m_mfxVppParams.vpp.Out, downscale); mfxPlatform platform; m_mfxSession.QueryPlatform(&platform); if (platform.CodeName < MFX_PLATFORM_TIGERLAKE) { m_mfxVppParams.vpp.In.CropW = m_mfxVppParams.vpp.In.Width = m_mfxVppParams.vpp.In.CropW & ~0x3F; m_mfxVppParams.vpp.In.CropH = m_mfxVppParams.vpp.In.Height = m_mfxVppParams.vpp.In.CropH & ~0x3F; } } #endif return MFX_ERR_NONE; } mfxStatus EncTools::CloseVPP() { MFX_CHECK(m_bVPPInit, MFX_ERR_NOT_INITIALIZED); mfxStatus sts; if (m_pAllocator) { m_pAllocator->Free(m_pAllocator->pthis, &m_VppResponse); m_pAllocator = nullptr; } if (m_pIntSurfaces.size()) m_pIntSurfaces.clear(); if (m_pmfxVPP) { m_pmfxVPP->Close(); m_pmfxVPP.reset(); } sts = m_mfxSession.Close(); MFX_CHECK_STS(sts); m_bVPPInit = false; return sts; } mfxStatus EncTools::Init(mfxExtEncToolsConfig const * pConfig, mfxEncToolsCtrl const * ctrl) { mfxStatus sts = MFX_ERR_NONE; MFX_CHECK_NULL_PTR2(pConfig, ctrl); MFX_CHECK(!m_bInit, MFX_ERR_UNDEFINED_BEHAVIOR); m_ctrl = *ctrl; mfxU16 crW = ctrl->FrameInfo.CropW ? ctrl->FrameInfo.CropW : ctrl->FrameInfo.Width; bool needVPP = (ctrl->IOPattern & MFX_IOPATTERN_IN_VIDEO_MEMORY) && (isPreEncSCD(*pConfig, *ctrl) || (isPreEncLA(*pConfig, *ctrl) && crW >= 720)); needVPP = needVPP || ((ctrl->IOPattern & MFX_IOPATTERN_IN_SYSTEM_MEMORY) && isPreEncLA(*pConfig, *ctrl)); if (needVPP) { mfxEncToolsCtrlExtDevice *extDevice = (mfxEncToolsCtrlExtDevice *)Et_GetExtBuffer(ctrl->ExtParam, ctrl->NumExtParam, MFX_EXTBUFF_ENCTOOLS_DEVICE); if (extDevice) { m_device = extDevice->DeviceHdl; m_deviceType = extDevice->HdlType; } if (!m_device) return MFX_ERR_UNDEFINED_BEHAVIOR; mfxEncToolsCtrlExtAllocator *extAlloc = (mfxEncToolsCtrlExtAllocator *)Et_GetExtBuffer(ctrl->ExtParam, ctrl->NumExtParam, MFX_EXTBUFF_ENCTOOLS_ALLOCATOR); if (extAlloc) m_pAllocator = extAlloc->pAllocator; if (!m_pAllocator) { MFX_CHECK_NULL_PTR1(m_pETAllocator); sts = m_pETAllocator->Init(m_pmfxAllocatorParams); MFX_CHECK_STS(sts); m_pAllocator = m_pETAllocator; } } SetToolsStatus(&m_config, false); if (IsOn(pConfig->BRC)) { sts = m_brc.Init(*ctrl); MFX_CHECK_STS(sts); m_config.BRC = MFX_CODINGOPTION_ON; } if (isPreEncSCD(*pConfig, *ctrl)) { sts = m_scd.Init(*ctrl, *pConfig); MFX_CHECK_STS(sts); // to add request to m_scd about supported tools CopyPreEncSCTools(*pConfig, &m_config); } #if defined (MFX_ENABLE_ENCTOOLS_LPLA) if (isPreEncLA(*pConfig, *ctrl)) { m_lpLookAhead.SetAllocator(m_pAllocator); sts = m_lpLookAhead.Init(*ctrl, *pConfig); MFX_CHECK_STS(sts); CopyPreEncLATools(*pConfig, &m_config); } #endif if (needVPP) { sts = InitVPP(*ctrl); MFX_CHECK_STS(sts); } m_bInit = true; return sts; } mfxStatus EncTools::Close() { mfxStatus sts = MFX_ERR_NONE; MFX_CHECK(m_bInit, MFX_ERR_NOT_INITIALIZED); if (IsOn(m_config.BRC)) { m_brc.Close(); m_config.BRC = false; } if (isPreEncSCD(m_config, m_ctrl)) { m_scd.Close(); OffPreEncSCDTools(&m_config); } #if defined (MFX_ENABLE_ENCTOOLS_LPLA) if (isPreEncLA(m_config, m_ctrl)) { m_lpLookAhead.Close(); OffPreEncLATools(&m_config); } #endif if (m_bVPPInit) sts = CloseVPP(); m_bInit = false; return sts; } mfxStatus EncTools::Reset(mfxExtEncToolsConfig const * config, mfxEncToolsCtrl const * ctrl) { mfxStatus sts = MFX_ERR_NONE; MFX_CHECK_NULL_PTR2(config,ctrl); MFX_CHECK(m_bInit, MFX_ERR_NOT_INITIALIZED); if (IsOn(config->BRC)) { MFX_CHECK(m_config.BRC, MFX_ERR_UNSUPPORTED); sts = m_brc.Reset(*ctrl); } if (isPreEncSCD(*config, *ctrl)) { // to add check if Close/Init is real needed if (isPreEncSCD(m_config, m_ctrl)) m_scd.Close(); sts = m_scd.Init(*ctrl, *config); } #if defined (MFX_ENABLE_ENCTOOLS_LPLA) if (isPreEncLA(*config, *ctrl)) { // to add check if Close/Init is real needed if (isPreEncLA(m_config, m_ctrl)) m_lpLookAhead.Close(); sts = m_lpLookAhead.Init(*ctrl, *config); } #endif return sts; } #define MSDK_VPP_WAIT_INTERVAL 300000 mfxStatus EncTools::VPPDownScaleSurface(mfxFrameSurface1 *pInSurface, mfxFrameSurface1 *pOutSurface) { mfxStatus sts; MFX_CHECK_NULL_PTR2(pInSurface, pOutSurface); mfxSyncPoint vppSyncp; sts = m_pmfxVPP->RunFrameVPPAsync(pInSurface, pOutSurface, NULL, &vppSyncp); MFX_CHECK_STS(sts); sts = m_mfxSession.SyncOperation(vppSyncp, MSDK_VPP_WAIT_INTERVAL); MFX_CHECK_STS(sts); return MFX_ERR_NONE; } mfxStatus EncTools::Submit(mfxEncToolsTaskParam const * par) { mfxStatus sts = MFX_ERR_NONE; MFX_CHECK_NULL_PTR1(par); MFX_CHECK(m_bInit, MFX_ERR_NOT_INITIALIZED); mfxEncToolsFrameToAnalyze *pFrameData = (mfxEncToolsFrameToAnalyze *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_FRAME_TO_ANALYZE); if (pFrameData) { pFrameData->Surface->Data.FrameOrder = par->DisplayOrder; if (m_bVPPInit && (isPreEncSCD(m_config, m_ctrl) || isPreEncLA(m_config, m_ctrl))) { sts = VPPDownScaleSurface(pFrameData->Surface, m_pIntSurfaces.data()); MFX_CHECK_STS(sts); m_pIntSurfaces[0].Data.FrameOrder = pFrameData->Surface->Data.FrameOrder; if (isPreEncSCD(m_config, m_ctrl)) { m_pAllocator->Lock(m_pAllocator->pthis, m_pIntSurfaces[0].Data.MemId, &m_pIntSurfaces[0].Data); sts = m_scd.SubmitFrame(m_pIntSurfaces.data()); m_pAllocator->Unlock(m_pAllocator->pthis, m_pIntSurfaces[0].Data.MemId, &m_pIntSurfaces[0].Data); } #if defined (MFX_ENABLE_ENCTOOLS_LPLA) else if (isPreEncLA(m_config, m_ctrl)) sts = m_lpLookAhead.Submit(m_pIntSurfaces.data()); #endif } else if (isPreEncSCD(m_config, m_ctrl)) sts = m_scd.SubmitFrame(pFrameData->Surface); #if defined (MFX_ENABLE_ENCTOOLS_LPLA) else if (isPreEncLA(m_config, m_ctrl)) sts = m_lpLookAhead.Submit(pFrameData->Surface); #endif return sts; } mfxEncToolsBRCEncodeResult *pEncRes = (mfxEncToolsBRCEncodeResult *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_BRC_ENCODE_RESULT); if (pEncRes) { m_scd.ReportEncResult(par->DisplayOrder, *pEncRes); } if (pEncRes && IsOn(m_config.BRC)) { return m_brc.ReportEncResult(par->DisplayOrder, *pEncRes); } mfxEncToolsBRCFrameParams *pFrameStruct = (mfxEncToolsBRCFrameParams *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_BRC_FRAME_PARAM ); if (pFrameStruct && IsOn(m_config.BRC)) { sts = m_brc.SetFrameStruct(par->DisplayOrder, *pFrameStruct); MFX_CHECK_STS(sts); } mfxEncToolsBRCBufferHint *pBRCHints = (mfxEncToolsBRCBufferHint *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_BRC_BUFFER_HINT); if (pBRCHints && IsOn(m_config.BRC)) { return m_brc.ReportBufferHints(par->DisplayOrder, *pBRCHints); } mfxEncToolsHintPreEncodeGOP *pPreEncGOP = (mfxEncToolsHintPreEncodeGOP *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_HINT_GOP); if (pPreEncGOP && IsOn(m_config.BRC)) { return m_brc.ReportGopHints(par->DisplayOrder, *pPreEncGOP); } return sts; } mfxStatus EncTools::Query(mfxEncToolsTaskParam* par, mfxU32 /*timeOut*/) { mfxStatus sts = MFX_ERR_NONE; MFX_CHECK_NULL_PTR1(par); MFX_CHECK(m_bInit, MFX_ERR_NOT_INITIALIZED); mfxEncToolsHintPreEncodeSceneChange *pPreEncSC = (mfxEncToolsHintPreEncodeSceneChange *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_HINT_SCENE_CHANGE); if (pPreEncSC) { sts = m_scd.GetSCDecision(par->DisplayOrder, pPreEncSC); MFX_CHECK_STS(sts); } mfxEncToolsHintPreEncodeGOP *pPreEncGOP = (mfxEncToolsHintPreEncodeGOP *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_HINT_GOP); if (pPreEncGOP) { if (isPreEncSCD(m_config, m_ctrl)) sts = m_scd.GetGOPDecision(par->DisplayOrder, pPreEncGOP); #if defined (MFX_ENABLE_ENCTOOLS_LPLA) else { sts = m_lpLookAhead.Query(par->DisplayOrder, pPreEncGOP); if (sts == MFX_ERR_NOT_FOUND) sts = MFX_ERR_NONE; } #endif MFX_CHECK_STS(sts); } mfxEncToolsHintPreEncodeARefFrames *pPreEncARef = (mfxEncToolsHintPreEncodeARefFrames *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_HINT_AREF); if (pPreEncARef) { sts = m_scd.GetARefDecision(par->DisplayOrder, pPreEncARef); MFX_CHECK_STS(sts); } #if defined (MFX_ENABLE_ENCTOOLS_LPLA) mfxEncToolsHintQuantMatrix *pCqmHint = (mfxEncToolsHintQuantMatrix *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_HINT_MATRIX); if (pCqmHint) { sts = m_lpLookAhead.Query(par->DisplayOrder, pCqmHint); if (sts == MFX_ERR_NOT_FOUND) sts = MFX_ERR_NONE; MFX_CHECK_STS(sts); } mfxEncToolsBRCBufferHint *bufferHint = (mfxEncToolsBRCBufferHint *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_BRC_BUFFER_HINT); if (bufferHint) { sts = m_lpLookAhead.Query(par->DisplayOrder, bufferHint); if (sts == MFX_ERR_NOT_FOUND) sts = MFX_ERR_NONE; MFX_CHECK_STS(sts); } #endif mfxEncToolsBRCStatus *pFrameSts = (mfxEncToolsBRCStatus *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_BRC_STATUS); if (pFrameSts && IsOn(m_config.BRC)) { return m_brc.UpdateFrame(par->DisplayOrder, pFrameSts); } mfxEncToolsBRCQuantControl *pFrameQp = (mfxEncToolsBRCQuantControl *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_BRC_QUANT_CONTROL); if (pFrameQp && IsOn(m_config.BRC)) { sts = m_brc.ProcessFrame(par->DisplayOrder, pFrameQp); MFX_CHECK_STS(sts); } mfxEncToolsBRCHRDPos *pHRDPos = (mfxEncToolsBRCHRDPos *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_BRC_HRD_POS); if (pHRDPos && IsOn(m_config.BRC)) { sts = m_brc.GetHRDPos(par->DisplayOrder, pHRDPos); MFX_CHECK_STS(sts); } return sts; } mfxStatus EncTools::Discard(mfxU32 displayOrder) { mfxStatus sts = MFX_ERR_NONE; sts = m_scd.CompleteFrame(displayOrder); return sts; }
34.377331
194
0.683527
alexelizarov
a8c77a8d6511d8e05f53b5006e55b6a009c4a853
1,285
hpp
C++
src/func.hpp
Dlanis/SDLPong
8229aae0d8b80c530a49e98cb6fb91c1f7768929
[ "MIT" ]
null
null
null
src/func.hpp
Dlanis/SDLPong
8229aae0d8b80c530a49e98cb6fb91c1f7768929
[ "MIT" ]
null
null
null
src/func.hpp
Dlanis/SDLPong
8229aae0d8b80c530a49e98cb6fb91c1f7768929
[ "MIT" ]
null
null
null
#pragma once #include <thread> #include <cmath> #include <SDL.h> #include "ball.hpp" #include "paddle.hpp" constexpr float pi = 3.14159; inline void sleep(double seconds) { std::this_thread::sleep_for(std::chrono::duration<double>(seconds)); } inline constexpr bool intersects(float cx, float cy, float radius, float left, float top, float right, float bottom) { float closestX = (cx < left ? left : (cx > right ? right : cx)); float closestY = (cy < top ? top : (cy > bottom ? bottom : cy)); float dx = closestX - cx; float dy = closestY - cy; return ( dx * dx + dy * dy ) <= radius * radius; } inline constexpr bool intersects(const Ball &ball, const Paddle &paddle) { SDL_FRect paddlerect = paddle.getRect(); return intersects(ball.position.x, ball.position.y, ball.radius, paddlerect.x, paddlerect.y, paddlerect.x + paddlerect.w, paddlerect.y + paddlerect.h); } inline constexpr SDL_FPoint rotate_vector(const SDL_FPoint &vector, const double &degree) { SDL_FPoint m_vector = vector; float l = (m_vector.x > 0 ? m_vector.x : 1) * (m_vector.y > 0 ? m_vector.y : 1); double angle = degree / (180 / pi); m_vector.x = l * std::cos(angle); m_vector.y = l * std::sin(angle); return m_vector; }
29.204545
116
0.65214
Dlanis
a8c94980f544f30152f6937a3bfdaa292b7e6feb
19,268
cpp
C++
src/trident/ml/batch.cpp
dkw-aau/trident-clone
18f896db2be05870069ae7b3aa6b4837c74fff0f
[ "Apache-2.0" ]
20
2018-10-17T21:39:40.000Z
2021-11-10T11:07:23.000Z
src/trident/ml/batch.cpp
dkw-aau/trident-clone
18f896db2be05870069ae7b3aa6b4837c74fff0f
[ "Apache-2.0" ]
5
2020-07-06T22:50:04.000Z
2022-03-17T10:34:15.000Z
src/trident/ml/batch.cpp
dkw-aau/trident-clone
18f896db2be05870069ae7b3aa6b4837c74fff0f
[ "Apache-2.0" ]
9
2018-09-18T11:37:35.000Z
2022-03-29T07:46:41.000Z
#include <trident/ml/batch.h> #include <trident/kb/kb.h> #include <trident/kb/querier.h> #include <fstream> #include <algorithm> #include <random> #include <unordered_map> BatchCreator::BatchCreator(string kbdir, uint64_t batchsize, uint16_t nthreads, const float valid, const float test, const bool filter, const bool createBatchFile, std::shared_ptr<Feedback> feedback) : kbdir(kbdir), batchsize(batchsize), /*nthreads(nthreads),*/ valid(valid), test(test), createBatchFile(createBatchFile), filter(filter), feedback(feedback) { KBConfig config; this->kb = new KB(kbdir.c_str(), true, false, false, config); rawtriples = NULL; ntriples = 0; currentidx = 0; usedIndex = IDX_POS; } std::shared_ptr<Feedback> BatchCreator::getFeedback() { return feedback; } string BatchCreator::getValidPath() { return kbdir + "/_batch_valid" + std::to_string(this->usedIndex); } string BatchCreator::getTestPath() { return kbdir + "/_batch_test" + std::to_string(this->usedIndex); } string BatchCreator::getValidPath(string kbdir, int usedIndex) { return kbdir + "/_batch_valid" + std::to_string(usedIndex); } string BatchCreator::getTestPath(string kbdir, int usedIndex) { return kbdir + "/_batch_test" + std::to_string(usedIndex); } void BatchCreator::createInputForBatch(bool createTraining, const float valid, const float test) { Querier *q = kb->query(); auto itr = q->getIterator(this->usedIndex, -1, -1, -1); int64_t s, p, o; ofstream ofs_valid; if (valid > 0) { ofs_valid.open(this->kbdir + "/_batch_valid" + std::to_string(this->usedIndex), ios::out | ios::app | ios::binary); } ofstream ofs_test; if (test > 0) { ofs_test.open(this->kbdir + "/_batch_test" + std::to_string(this->usedIndex), ios::out | ios::app | ios::binary); } std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<float> dis(0.0, 1.0); //Create a file called '_batch' in the maindir with a fixed-length record size ofstream ofs; if (createTraining) { LOG(INFOL) << "Store the input for the batch process in " << kbdir + "/_batch" + std::to_string(this->usedIndex) << " ..."; ofs.open(this->kbdir + "/_batch" + std::to_string(this->usedIndex), ios::out | ios::app | ios::binary); } std::unordered_map<uint64_t, uint64_t> mapPredicates; if (!kb->areRelIDsSeparated()) { size_t i = 0; auto querier = kb->query(); auto itr = querier->getTermList(IDX_POS); while (itr->hasNext()) { itr->next(); auto pname = itr->getKey(); mapPredicates.insert(std::make_pair(pname, i)); i++; } querier->releaseItr(itr); delete querier; } while (itr->hasNext()) { itr->next(); if (this->usedIndex == IDX_SPO) { s = itr->getKey(); p = itr->getValue1(); o = itr->getValue2(); } else if (this->usedIndex == IDX_SOP) { s = itr->getKey(); o = itr->getValue1(); p = itr->getValue2(); } else if (this->usedIndex == IDX_POS) { p = itr->getKey(); o = itr->getValue1(); s = itr->getValue2(); } else if (this->usedIndex == IDX_PSO) { p = itr->getKey(); s = itr->getValue1(); o = itr->getValue2(); } else if (this->usedIndex == IDX_OSP) { o = itr->getKey(); s = itr->getValue1(); p = itr->getValue2(); } else if (this->usedIndex == IDX_OPS) { o = itr->getKey(); p = itr->getValue1(); s = itr->getValue2(); } if (!kb->areRelIDsSeparated()) { p = mapPredicates[p]; } const char *cs = (const char*)&s; const char *cp = (const char*)&p; const char *co = (const char*)&o; if (valid > 0 && dis(gen) < valid) { ofs_valid.write(cs, 5); //Max numbers have 5 bytes ofs_valid.write(cp, 5); ofs_valid.write(co, 5); } else if (test > 0 && dis(gen) < test) { ofs_test.write(cs, 5); //Max numbers have 5 bytes ofs_test.write(cp, 5); ofs_test.write(co, 5); } else if (createTraining) { ofs.write(cs, 5); //Max numbers have 5 bytes ofs.write(cp, 5); ofs.write(co, 5); } } q->releaseItr(itr); if (createTraining) { ofs.close(); } if (valid > 0) { ofs_valid.close(); } if (test > 0) { ofs_test.close(); } delete q; LOG(INFOL) << "Done"; } struct _pso { const char *rawtriples; _pso(const char *rawtriples) : rawtriples(rawtriples) {} bool operator() (const uint64_t idx1, const uint64_t idx2) const { int64_t s1 = *(int64_t*)(rawtriples + idx1 * 15); s1 = s1 & 0xFFFFFFFFFFl; int64_t p1 = *(int64_t*)(rawtriples + idx1 * 15 + 5); p1 = p1 & 0xFFFFFFFFFFl; int64_t o1 = *(int64_t*)(rawtriples + idx1 * 15 + 10); o1 = o1 & 0xFFFFFFFFFFl; int64_t s2 = *(int64_t*)(rawtriples + idx2 * 15); s2 = s2 & 0xFFFFFFFFFFl; int64_t p2 = *(int64_t*)(rawtriples + idx2 * 15 + 5); p2 = p2 & 0xFFFFFFFFFFl; int64_t o2 = *(int64_t*)(rawtriples + idx2 * 15 + 10); o2 = o2 & 0xFFFFFFFFFFl; if (p1 != p2) { return p1 < p2; } else if (s1 != s2) { return s1 < s2; } else { return o1 < o2; } } }; int64_t BatchCreator::findFirstOccurrence(int64_t start, int64_t end, uint64_t x, int offset) { int64_t idxTerm = -1; while (start <= end) { int64_t middle = start + (end - start) / 2; int64_t term = *(int64_t*)(rawtriples + middle * 15 + offset); term = term & 0xFFFFFFFFFFl; if (term < x) { start = middle + 1; } else if (term > x) { end = middle - 1; } else { idxTerm = middle; end = middle - 1; } } return idxTerm; } int64_t BatchCreator::findLastOccurrence(int64_t start, int64_t end, uint64_t x, int offset) { int64_t idxTerm = -1; while (start <= end) { int64_t middle = start + (end - start) / 2; int64_t term = *(int64_t*)(rawtriples + middle * 15 + offset); term = term & 0xFFFFFFFFFFl; if (term < x) { start = middle + 1; } else if (term > x) { end = middle - 1; } else { idxTerm = middle; start = middle + 1; } } return idxTerm; } void BatchCreator::populateIndicesFromQuery(int64_t s, int64_t p, int64_t o) { int64_t start = 0; int64_t end = ntriples; int64_t firstTerm = ~0lu; int offset = 0; if (this->usedIndex == IDX_POS || this->usedIndex == IDX_PSO) { firstTerm = p; offset = 5; } else if (this->usedIndex == IDX_SOP || this->usedIndex == IDX_SPO) { firstTerm = s; offset = 0; } else { firstTerm = o; offset = 10; } int64_t idxStartFirstTerm = -1; if (firstTerm != -1) { idxStartFirstTerm = findFirstOccurrence(start, end, firstTerm, offset); if (idxStartFirstTerm != -1) { int64_t idxEndFirstTerm = findLastOccurrence(idxStartFirstTerm, end, firstTerm, offset); start = idxStartFirstTerm; if (idxEndFirstTerm < end) end = idxEndFirstTerm + 1; } else { start = end = 0; } } int64_t idxStartSecondTerm = -1; if (idxStartFirstTerm != -1) { int64_t secondTerm = ~0lu; if (this->usedIndex == IDX_OPS || this->usedIndex == IDX_SPO) { secondTerm = p; offset = 5; } else if (this->usedIndex == IDX_OSP || this->usedIndex == IDX_PSO) { secondTerm = s; offset = 0; } else { secondTerm = o; offset = 10; } if (secondTerm != -1) { idxStartSecondTerm = findFirstOccurrence(start, end, secondTerm, offset); if (idxStartSecondTerm != -1) { int64_t idxEndSecondTerm = findLastOccurrence(idxStartSecondTerm, end, secondTerm, offset); start = idxStartSecondTerm; if (idxEndSecondTerm < end) end = idxEndSecondTerm + 1; } else { start = end = 0; } } } if (idxStartSecondTerm != -1) { int64_t thirdTerm; if (this->usedIndex == IDX_OPS || this->usedIndex == IDX_POS) { thirdTerm = s; offset = 0; } else if (this->usedIndex == IDX_OSP || this->usedIndex == IDX_SOP) { thirdTerm = p; offset = 5; } else { thirdTerm = o; offset = 10; } if (thirdTerm != -1) { int64_t idxStartThirdTerm = findFirstOccurrence(start, end, thirdTerm, offset); if (idxStartThirdTerm != -1) { start = idxStartThirdTerm; end = start + 1; } else { start = end = 0; } } } //std::cout << "Creating an index with " << (end - start) << std::endl; //Populate indices this->indices.resize(end - start); uint64_t i = 0; while (start < end) { indices[i++] = start++; } } uint64_t BatchCreator::getNBatches() { int64_t n = indices.size() / this->batchsize; if ((indices.size() % this->batchsize) != 0) { return n + 1; } else { return n; } } void BatchCreator::start(int64_t s, int64_t p, int64_t o) { //Get index for s,p,o this->usedIndex = IDX_POS; if (s != -1 || p != -1 || o != -1) { if (valid != 0 || test != 0) { LOG(ERRORL) << "Query-based batching works only if the entire KB is used for training"; throw 10; } Querier *q = kb->query(); this->usedIndex = q->getIndex(s, p, o); delete q; } //First check if the file exists string fin = this->kbdir + "/_batch" + std::to_string(this->usedIndex); if (Utils::exists(fin)) { } else { if (createBatchFile) { LOG(INFOL) << "Could not find the input file for the batch." " I will create it and store it in a file called '_batch'"; createInputForBatch(createBatchFile, valid, test); } } if (createBatchFile) { //Load the file into a memory-mapped file this->mappedFile = std::unique_ptr<MemoryMappedFile>(new MemoryMappedFile( fin)); this->rawtriples = this->mappedFile->getData(); this->ntriples = this->mappedFile->getLength() / 15; } else { this->kbbatch = std::unique_ptr<KBBatch>(new KBBatch(kb)); this->kbbatch->populateCoordinates(); this->ntriples = this->kbbatch->ntriples(); } LOG(DEBUGL) << "Creating index array ..."; if (s != -1 || p != -1 || o != -1) { assert(createBatchFile); //Put in indices only the triples that satisfy the query populateIndicesFromQuery(s, p, o); } else { this->indices.resize(this->ntriples); for(int64_t i = 0; i < this->ntriples; ++i) { this->indices[i] = i; } } LOG(DEBUGL) << "Shuffling array ..."; shuffle(); LOG(DEBUGL) << "Done"; } void BatchCreator::shuffle() { std::shuffle(this->indices.begin(), this->indices.end(), engine); this->currentidx = 0; } bool BatchCreator::getBatch(std::vector<uint64_t> &output) { int64_t i = 0; output.resize(this->batchsize * 3); //The output vector is already supposed to contain batchsize elements. Otherwise, resize it while (i < batchsize && currentidx < indices.size()) { int64_t idx = indices[currentidx]; uint64_t s,p,o; if (createBatchFile) { s = *(uint64_t*)(rawtriples + idx * 15); s = s & 0xFFFFFFFFFFl; p = *(uint64_t*)(rawtriples + idx * 15 + 5); p = p & 0xFFFFFFFFFFl; o = *(uint64_t*)(rawtriples + idx * 15 + 10); o = o & 0xFFFFFFFFFFl; } else { kbbatch->getAt(idx, s, p, o); } if (filter && shouldBeUsed(s,p,o)) { output[i*3] = s; output[i*3+1] = p; output[i*3+2] = o; i+=1; } currentidx++; } if (i < batchsize) { output.resize(i*3); } return i > 0; } bool BatchCreator::shouldBeUsed(int64_t s, int64_t p, int64_t o) { return feedback->shouldBeIncluded(s, p, o); } bool BatchCreator::getBatchNr(uint64_t nr, std::vector<uint64_t> &output1, std::vector<uint64_t> &output2, std::vector<uint64_t> &output3) { output1.resize(this->batchsize); output2.resize(this->batchsize); output3.resize(this->batchsize); //Try to get up to batchsize triples int64_t i = 0; int64_t cidx = nr * this->batchsize; while (i < batchsize && cidx < indices.size()) { int64_t idx = indices[cidx]; uint64_t s, p, o; if (createBatchFile) { s = *(uint64_t *)(rawtriples + idx * 15); s = s & 0xFFFFFFFFFFl; p = *(uint64_t *)(rawtriples + idx * 15 + 5); p = p & 0xFFFFFFFFFFl; o = *(uint64_t *)(rawtriples + idx * 15 + 10); o = o & 0xFFFFFFFFFFl; } else { kbbatch->getAt(idx, s, p, o); } if (!filter || shouldBeUsed(s,p,o)) { output1[i] = s; output2[i] = p; output3[i] = o; i+=1; } cidx++; } if (i < this->batchsize) { output1.resize(i); output2.resize(i); output3.resize(i); } return i > 0; } bool BatchCreator::getBatch(std::vector<uint64_t> &output1, std::vector<uint64_t> &output2, std::vector<uint64_t> &output3) { int64_t i = 0; output1.resize(this->batchsize); output2.resize(this->batchsize); output3.resize(this->batchsize); //The output vector is already supposed to contain batchsize elements. //Otherwise, resize it while (i < batchsize && currentidx < indices.size()) { int64_t idx = indices[currentidx]; uint64_t s,p,o; if (createBatchFile) { s = *(uint64_t *)(rawtriples + idx * 15); s = s & 0xFFFFFFFFFFl; p = *(uint64_t *)(rawtriples + idx * 15 + 5); p = p & 0xFFFFFFFFFFl; o = *(uint64_t *)(rawtriples + idx * 15 + 10); o = o & 0xFFFFFFFFFFl; } else { kbbatch->getAt(idx, s, p, o); } if (!filter || shouldBeUsed(s,p,o)) { output1[i] = s; output2[i] = p; output3[i] = o; i+=1; } currentidx++; } if (i < batchsize) { output1.resize(i); output2.resize(i); output3.resize(i); } return i > 0; } void BatchCreator::loadTriples(string path, std::vector<uint64_t> &output) { MemoryMappedFile mf(path); char *start = mf.getData(); char *end = start + mf.getLength(); while (start < end) { int64_t s = *(int64_t*)(start); s = s & 0xFFFFFFFFFFl; int64_t p = *(int64_t*)(start + 5); p = p & 0xFFFFFFFFFFl; int64_t o = *(int64_t*)(start + 10); o = o & 0xFFFFFFFFFFl; output.push_back(s); output.push_back(p); output.push_back(o); start += 15; } } BatchCreator::KBBatch::KBBatch(KB *kb) : kb(kb) { this->querier = std::unique_ptr<Querier>(kb->query()); } void BatchCreator::KBBatch::populateCoordinates() { //Load all files allposfiles = kb->openAllFiles(IDX_POS); auto itr = (TermItr*)querier->getTermList(IDX_POS); string kbdir = kb->getPath(); string posdir = kbdir + "/p" + to_string(IDX_POS); //Get all the predicates uint64_t current = 0; while (itr->hasNext()) { itr->next(); uint64_t pred = itr->getKey(); uint64_t card = itr->getCount(); PredCoordinates info; info.pred = pred; info.boundary = current + card; //Get beginning of the table short currentFile = itr->getCurrentFile(); int64_t currentMark = itr->getCurrentMark(); string fdidx = posdir + "/" + to_string(currentFile) + ".idx"; if (Utils::exists(fdidx)) { ifstream idxfile(fdidx); idxfile.seekg(8 + 11 * currentMark); char buffer[5]; idxfile.read(buffer, 5); int64_t pos = Utils::decode_longFixedBytes(buffer, 5); info.buffer = allposfiles[currentFile] + pos; } else { LOG(ERRORL) << "Cannot happen!"; throw 10; } char currentStrat = itr->getCurrentStrat(); int storageType = StorageStrat::getStorageType(currentStrat); if (storageType == NEWCOLUMN_ITR) { //Get reader and offset char header1 = info.buffer[0]; char header2 = info.buffer[1]; const uint8_t bytesPerStartingPoint = header2 & 7; const uint8_t bytesPerCount = (header2 >> 3) & 7; const uint8_t remBytes = bytesPerCount + bytesPerStartingPoint; const uint8_t bytesPerFirstEntry = (header1 >> 3) & 7; const uint8_t bytesPerSecondEntry = (header1) & 7; info.offset = remBytes; //update the buffer int offset = 2; info.nfirstterms = Utils::decode_vlong2(info.buffer, &offset); Utils::decode_vlong2(info.buffer, &offset); info.buffer = info.buffer + offset; FactoryNewColumnTable::get12Reader(bytesPerFirstEntry, bytesPerSecondEntry, &info.reader); } else if (storageType == NEWROW_ITR) { const char nbytes1 = (currentStrat >> 3) & 3; const char nbytes2 = (currentStrat >> 1) & 3; FactoryNewRowTable::get12Reader(nbytes1, nbytes2, &info.reader); } else { LOG(ERRORL) << "Not supported"; throw 10; } predicates.push_back(info); current += card; } querier->releaseItr(itr); } void BatchCreator::KBBatch::getAt(uint64_t pos, uint64_t &s, uint64_t &p, uint64_t &o) { auto itr = predicates.begin(); uint64_t offset = 0; while(itr != predicates.end() && pos >= itr->boundary) { offset = itr->boundary; itr++; } pos -= offset; if (itr != predicates.end()) { //Take the reader and read the values itr->reader(itr->nfirstterms, itr->offset, itr->buffer, pos, o, s); p = itr->pred; } } BatchCreator::KBBatch::~KBBatch() { querier = NULL; } uint64_t BatchCreator::KBBatch::ntriples() { return kb->getSize(); }
31.847934
123
0.535344
dkw-aau
a8c978333b4cc8f14c54e1d6a096d8ba09193dc3
6,495
inl
C++
qbase/include/util/Iterators.inl
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
36
2015-03-09T16:47:14.000Z
2021-02-04T08:32:04.000Z
qbase/include/util/Iterators.inl
jeanlemotan/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
42
2017-02-11T11:15:51.000Z
2019-12-28T16:00:44.000Z
qbase/include/util/Iterators.inl
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
5
2015-10-15T05:46:48.000Z
2020-05-11T17:40:36.000Z
////////////////////////////////////////////////////////////////////////// template<class T> Const_Ptr_Iterator<T>::Const_Ptr_Iterator(uint8_t const* data, size_type stride, size_type count) : m_begin(data) , m_end(data ? data + stride*count : nullptr) , m_ptr(data) , m_stride(stride) { QASSERT(stride > 0); } template<class T> Const_Ptr_Iterator<T>::Const_Ptr_Iterator(uint8_t const* data, size_type count) : m_begin(data) , m_end(data ? data + sizeof(T)*count : nullptr) , m_ptr(data) , m_stride(sizeof(T)) { } template<class T> typename Const_Ptr_Iterator<T>::value_type const& Const_Ptr_Iterator<T>::operator*() const { QASSERT(m_ptr <= m_end); return *reinterpret_cast<T const*>(m_ptr); } template<class T> Const_Ptr_Iterator<T>::Const_Ptr_Iterator(Const_Ptr_Iterator<T> const& other) : m_begin(other.m_begin) , m_end(other.m_end) , m_ptr(other.m_ptr) , m_stride(other.m_stride) { } template<class T> Const_Ptr_Iterator<T>& Const_Ptr_Iterator<T>::operator=(Const_Ptr_Iterator<T> const& other) { m_begin = other.m_begin; m_end = other.m_end; m_ptr = other.m_ptr; m_stride = other.m_stride; return *this; } template<class T> Const_Ptr_Iterator<T>& Const_Ptr_Iterator<T>::operator++() { QASSERT(m_ptr + m_stride <= m_end); m_ptr += m_stride; return *this; } template<class T> Const_Ptr_Iterator<T> Const_Ptr_Iterator<T>::operator++(int) { QASSERT(m_ptr + m_stride <= m_end); Const_Ptr_Iterator<T> p(*this); m_ptr += m_stride; return p; } template<class T> Const_Ptr_Iterator<T>& Const_Ptr_Iterator<T>::operator+=(size_type i) { QASSERT(m_ptr + m_stride*i <= m_end); m_ptr += m_stride*i; return *this; } template<class T> Const_Ptr_Iterator<T> Const_Ptr_Iterator<T>::operator+(size_type i) const { Const_Ptr_Iterator<T> x(*this); x += i; return x; } template<class T> Const_Ptr_Iterator<T>& Const_Ptr_Iterator<T>::operator--() { QASSERT(m_ptr - m_stride >= m_begin); m_ptr -= m_stride; return *this; } template<class T> Const_Ptr_Iterator<T> Const_Ptr_Iterator<T>::operator--(int) { QASSERT(m_ptr - m_stride >= m_begin); Const_Ptr_Iterator<T> p(*this); m_ptr -= m_stride; return p; } template<class T> Const_Ptr_Iterator<T>& Const_Ptr_Iterator<T>::operator-=(size_type i) { QASSERT(m_ptr - m_stride*i >= m_begin); m_ptr -= m_stride*i; return *this; } template<class T> Const_Ptr_Iterator<T> Const_Ptr_Iterator<T>::operator-(size_type i) const { Const_Ptr_Iterator<T> x(*this); x -= i; return x; } template<class T> typename Const_Ptr_Iterator<T>::difference_type Const_Ptr_Iterator<T>::operator-(Const_Ptr_Iterator const& other) const { return static_cast<difference_type>(m_ptr - other.m_ptr); } template<class T> bool Const_Ptr_Iterator<T>::operator==(Const_Ptr_Iterator<T> const& other) const { return m_ptr == other.m_ptr; } template<class T> bool Const_Ptr_Iterator<T>::operator!=(Const_Ptr_Iterator<T> const& other) const { return !operator==(other); } template<class T> bool Const_Ptr_Iterator<T>::operator<(Const_Ptr_Iterator<T> const& other) const { return m_ptr < other.m_ptr; } template<class T> bool Const_Ptr_Iterator<T>::is_valid() const { return m_ptr != nullptr; } template<class T> T const* Const_Ptr_Iterator<T>::get() const { QASSERT(m_ptr <= m_end); return reinterpret_cast<T const*>(m_ptr); } ////////////////////////////////////////////////////////////////////////// template<class T> Ptr_Iterator<T>::Ptr_Iterator(uint8_t* data, size_type stride, size_type count) : m_begin(data) , m_end(data ? data + stride*count : nullptr) , m_ptr(data) , m_stride(stride) { QASSERT(stride > 0); } template<class T> Ptr_Iterator<T>::Ptr_Iterator(uint8_t* data, size_type count) : m_begin(data) , m_end(data ? data + sizeof(T)*count : nullptr) , m_ptr(data) , m_stride(sizeof(T)) { } template<class T> typename Ptr_Iterator<T>::value_type& Ptr_Iterator<T>::operator*() { QASSERT(m_ptr <= m_end); return *reinterpret_cast<T*>(m_ptr); } template<class T> Ptr_Iterator<T>::Ptr_Iterator(Ptr_Iterator const& other) : m_begin(other.m_begin) , m_end(other.m_end) , m_ptr(other.m_ptr) , m_stride(other.m_stride) { } template<class T> Ptr_Iterator<T>& Ptr_Iterator<T>::operator=(Ptr_Iterator<T> const& other) { m_begin = other.m_begin; m_end = other.m_end; m_ptr = other.m_ptr; m_stride = other.m_stride; return *this; } template<class T> Ptr_Iterator<T>& Ptr_Iterator<T>::operator++() { QASSERT(m_ptr + m_stride <= m_end); m_ptr += m_stride; return *this; } template<class T> Ptr_Iterator<T> Ptr_Iterator<T>::operator++(int) { QASSERT(m_ptr + m_stride <= m_end); Ptr_Iterator<T> p(*this); m_ptr += m_stride; return p; } template<class T> Ptr_Iterator<T>& Ptr_Iterator<T>::operator+=(size_type i) { QASSERT(m_ptr + m_stride*i <= m_end); m_ptr += m_stride*i; return *this; } template<class T> Ptr_Iterator<T> Ptr_Iterator<T>::operator+(size_type i) const { Ptr_Iterator<T> x(*this); x += i; return x; } template<class T> Ptr_Iterator<T>& Ptr_Iterator<T>::operator--() { QASSERT(m_ptr - m_stride >= m_begin); m_ptr -= m_stride; return *this; } template<class T> Ptr_Iterator<T> Ptr_Iterator<T>::operator--(int) { QASSERT(m_ptr - m_stride >= m_begin); Ptr_Iterator<T> p(*this); m_ptr -= m_stride; return p; } template<class T> Ptr_Iterator<T>& Ptr_Iterator<T>::operator-=(size_type i) { QASSERT(m_ptr - m_stride*i >= m_begin); m_ptr -= m_stride*i; return *this; } template<class T> Ptr_Iterator<T> Ptr_Iterator<T>::operator-(size_type i) const { Ptr_Iterator<T> x(*this); x -= i; return x; } template<class T> typename Ptr_Iterator<T>::difference_type Ptr_Iterator<T>::operator-(Ptr_Iterator const& other) const { return static_cast<difference_type>(m_ptr - other.m_ptr); } template<class T> bool Ptr_Iterator<T>::operator==(Ptr_Iterator<T> const& other) const { return m_ptr == other.m_ptr; } template<class T> bool Ptr_Iterator<T>::operator!=(Ptr_Iterator<T> const& other) const { return !operator==(other); } template<class T> bool Ptr_Iterator<T>::operator<(Ptr_Iterator<T> const& other) const { return m_ptr < other.m_ptr; } template<class T> bool Ptr_Iterator<T>::is_valid() const { return m_ptr != nullptr; } template<class T> T* Ptr_Iterator<T>::get() { QASSERT(m_ptr <= m_end); return reinterpret_cast<T*>(m_ptr); }
24.602273
120
0.676982
jeanleflambeur
a8c9b6217d453f3fcfc699a816d4107dac77435c
9,935
cpp
C++
chapter21/chapter21_drill.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
170
2015-05-02T18:08:38.000Z
2018-07-31T11:35:17.000Z
chapter21/chapter21_drill.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
7
2018-08-29T15:43:14.000Z
2021-09-23T21:56:49.000Z
chapter21/chapter21_drill.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
105
2015-05-28T11:52:19.000Z
2018-07-17T14:11:25.000Z
// Chapter 21, drill #include "../lib_files/std_lib_facilities.h" #include<map> #include<numeric> //------------------------------------------------------------------------------ struct Item { string name; int iid; double value; Item() :name(), iid(0), value(0) { } Item(string n, int i, double v) :name(n), iid(i), value(v) { } }; //------------------------------------------------------------------------------ istream& operator>>(istream& is, Item& it) { string name; int iid; double value; is >> name >> iid >> value; if (!is) return is; it = Item(name,iid,value); return is; } //------------------------------------------------------------------------------ ostream& operator<<(ostream& os, const Item& it) { return os << it.name << '\t' << it.iid << '\t' << it.value; } //------------------------------------------------------------------------------ struct Comp_by_name { bool operator()(const Item& a, const Item& b) const { return a.name < b.name; } }; //------------------------------------------------------------------------------ struct Comp_by_iid { bool operator()(const Item& a, const Item& b) const { return a.iid < b.iid; } }; //------------------------------------------------------------------------------ bool comp_by_value(const Item& a, const Item& b) { return a.value < b.value; } //------------------------------------------------------------------------------ class Find_by_name { string name; public: Find_by_name(const string& s) :name(s) { } bool operator()(const Item& it) const { return it.name == name; } }; //------------------------------------------------------------------------------ class Find_by_iid { int iid; public: Find_by_iid(int i) :iid(i) { } bool operator()(const Item& it) const { return it.iid == iid; } }; //------------------------------------------------------------------------------ template<class iter> void print(iter first, iter last) { while (first!=last) { cout << *first << '\n'; ++first; } } //------------------------------------------------------------------------------ void f1() { cout << "First round: vector\n"; vector<Item> vi; const string ifname = "pics_and_txt/chapter21_drill_in.txt"; // 1.1 cout << "1.1: fill with ten items from file\n"; { ifstream ifs(ifname.c_str()); if (!ifs) error("can't open ",ifname); Item i; while (ifs>>i) vi.insert(vi.end(),i); } print(vi.begin(),vi.end()); // 1.2 cout << "\n1.2: sort by name\n"; sort(vi.begin(),vi.end(),Comp_by_name()); print(vi.begin(),vi.end()); // 1.3 cout << "\n1.3: sort by iid\n"; sort(vi.begin(),vi.end(),Comp_by_iid()); print(vi.begin(),vi.end()); // 1.4 - use function instead of function object cout << "\n1.4: sort by value, print in decreasing order\n"; sort(vi.begin(),vi.end(),comp_by_value); reverse(vi.begin(),vi.end()); print(vi.begin(),vi.end()); // 1.5 - use function instead of function object cout << "\n1.5: insert two items\n"; vi.insert(vi.end(),Item("Horsesh",99,12.34)); vi.insert(vi.end(),Item("C S400",9988,499.95)); sort(vi.begin(),vi.end(),comp_by_value); reverse(vi.begin(),vi.end()); print(vi.begin(),vi.end()); // 1.6 cout << "\n1.6: remove two items identified by name\n"; vector<Item>::iterator vi_it = find_if(vi.begin(),vi.end(),Find_by_name("GoPro")); vi.erase(vi_it); vi_it = find_if(vi.begin(),vi.end(),Find_by_name("Xbox")); vi.erase(vi_it); print(vi.begin(),vi.end()); // 1.7 cout << "\n1.7: remove two tems identified by iid\n"; vi_it = find_if(vi.begin(),vi.end(),Find_by_iid(14910)); vi.erase(vi_it); vi_it = find_if(vi.begin(),vi.end(),Find_by_iid(754)); vi.erase(vi_it); print(vi.begin(),vi.end()); } //------------------------------------------------------------------------------ void f2() { cout << "\nSecond round: list\n"; list<Item> li; const string ifname = "pics_and_txt/chapter21_drill_in.txt"; // 1.1 cout << "1.1: fill with ten items from file\n"; { ifstream ifs(ifname.c_str()); if (!ifs) error("can't open ",ifname); Item i; while (ifs>>i) li.insert(li.end(),i); } print(li.begin(),li.end()); // 1.2 cout << "\n1.2: sort by name\n"; li.sort(Comp_by_name()); print(li.begin(),li.end()); // 1.3 cout << "\n1.3: sort by iid\n"; li.sort(Comp_by_iid()); print(li.begin(),li.end()); // 1.4 - use function instead of function object cout << "\n1.4: sort by value, print in decreasing order\n"; li.sort(comp_by_value); reverse(li.begin(),li.end()); print(li.begin(),li.end()); // 1.5 - use function instead of function object cout << "\n1.5: insert two items\n"; li.insert(li.end(),Item("Horsesh",99,12.34)); li.insert(li.end(),Item("C S400",9988,499.95)); li.sort(comp_by_value); reverse(li.begin(),li.end()); print(li.begin(),li.end()); // 1.6 cout << "\n1.6: remove two items identified by name\n"; list<Item>::iterator li_it = find_if(li.begin(),li.end(),Find_by_name("GoPro")); li.erase(li_it); li_it = find_if(li.begin(),li.end(),Find_by_name("Xbox")); li.erase(li_it); print(li.begin(),li.end()); // 1.7 cout << "\n1.7: remove two tems identified by iid\n"; li_it = find_if(li.begin(),li.end(),Find_by_iid(14910)); li.erase(li_it); li_it = find_if(li.begin(),li.end(),Find_by_iid(754)); li.erase(li_it); print(li.begin(),li.end()); } //------------------------------------------------------------------------------ // 2.5 void read_pair(map<string,int>& msi) { string s; int i; cin >> s >> i; if (!cin) error("Problem reading from cin"); msi[s] = i; } //------------------------------------------------------------------------------ template<class T, class U> ostream& operator<<(ostream& os, const pair<T,U>& p) { os << setw(12) << left << p.first << '\t' << p.second; return os; } //------------------------------------------------------------------------------ template<class T> struct Map_add { T operator()(T v, const pair<string,T>& p) { return v + p.second; } }; //------------------------------------------------------------------------------ void f3() { // 2.1 map<string,int> msi; // 2.2 msi["lecture"] = 21; msi["university"] = 35; msi["education"] = 15; msi["school"] = 99; msi["kindergarten"] = 105; msi["river"] = 5; msi["city"] = 10; msi["capital"] = 70; msi["software"] = 88; msi["hardware"] = 43; // 2.3 print(msi.begin(),msi.end()); // 2.4 typedef map<string,int>::const_iterator MI; MI p = msi.begin(); while (p!=msi.end()) p = msi.erase(p); cout << "Size of map after deleting: " << msi.size() << '\n'; // 2.6 cout << "Enter 10 (string,int) pairs, separated by space:\n"; for (int i = 0; i<10; ++i) read_pair(msi); // 2.7 cout << '\n'; print(msi.begin(),msi.end()); // 2.8 int msi_sum = 0; msi_sum = accumulate(msi.begin(),msi.end(),msi_sum,Map_add<int>()); cout << "\nSum of all ints in msi: " << msi_sum << '\n'; // 2.9 map<int,string> mis; // 2.10 for (p = msi.begin(); p!=msi.end(); ++p) mis[p->second] = p->first; // 2.11 cout << "\nContents of mis:\n"; print(mis.begin(),mis.end()); } //------------------------------------------------------------------------------ template<class T> class Less_than { T v; public: Less_than(T val) :v(val) { } bool operator()(T x) const { return x < v; } }; //class Less_than { // double v; //public: // Less_than(double val) :v(val) { } // bool operator()(double x) const { return x < v; } //}; //------------------------------------------------------------------------------ void f4() { // 3.1 const string fname = "pics_and_txt/chapter21_drill_in2.txt"; ifstream ifs(fname.c_str()); if (!ifs) error("can't open ",fname); vector<double> vd; double d; while (ifs>>d) vd.push_back(d); // 3.2 cout << "vd:\n"; print(vd.begin(),vd.end()); // 3.3 vector<int> vi(vd.size()); copy(vd.begin(),vd.end(),vi.begin()); // 3.4 cout << "\n(vd,vi) pairs:\n"; for (int i = 0; i<vd.size(); ++i) { cout << '(' << vd[i] << ',' << vi[i] << ")\n"; } // 3.5 double sum_vd = 0; sum_vd = accumulate(vd.begin(),vd.end(),sum_vd); cout << "\nSum of the elements of vd: " << sum_vd << '\n'; // 3.6 int sum_vi = 0; sum_vi = accumulate(vi.begin(),vi.end(),sum_vi); cout << "Difference of sum_vd and sum_vi: " << sum_vd - sum_vi << '\n'; // 3.7 reverse(vd.begin(),vd.end()); cout << "\nvd after reverse:\n"; print(vd.begin(),vd.end()); // 3.8 double vd_mean = sum_vd / vd.size(); cout << "\nMean value of elements in vd: " << vd_mean << '\n'; // 3.9 vector<double> vd2(count_if(vd.begin(),vd.end(),Less_than<double>(vd_mean))); copy_if(vd.begin(),vd.end(),vd2.begin(),Less_than<double>(vd_mean)); cout << "\nvd2:\n"; print(vd2.begin(),vd2.end()); // 3.10 sort(vd.begin(),vd.end()); cout << "\nvd:\n"; print(vd.begin(),vd.end()); } //------------------------------------------------------------------------------ int main() try { f1(); // 1.8 f2(); f3(); f4(); } catch (Range_error& re) { cerr << "bad index: " << re.index << "\n"; } catch (exception& e) { cerr << "exception: " << e.what() << endl; } catch (...) { cerr << "exception\n"; } //------------------------------------------------------------------------------
24.899749
81
0.459386
TingeOGinge
a8d2a313ad5617fefbde1f293e387688f997fe2d
7,966
cpp
C++
source/rx/Font.cpp
zhiayang/sim-thing
8d9d5163146e2bdde15f4eadefa85453f12fac18
[ "Apache-2.0" ]
1
2021-02-07T08:40:11.000Z
2021-02-07T08:40:11.000Z
source/rx/Font.cpp
zhiayang/sim-thing
8d9d5163146e2bdde15f4eadefa85453f12fac18
[ "Apache-2.0" ]
null
null
null
source/rx/Font.cpp
zhiayang/sim-thing
8d9d5163146e2bdde15f4eadefa85453f12fac18
[ "Apache-2.0" ]
null
null
null
// Font.cpp // Copyright (c) 2014 - 2017, [email protected] // Licensed under the Apache License Version 2.0. #include <map> #include <algorithm> #include <stdio.h> #include <sys/stat.h> #include "rx.h" #include <glbinding/gl/gl.h> #define STB_RECT_PACK_IMPLEMENTATION #include "stb/stb_pack_rect.h" #define STB_TRUETYPE_IMPLEMENTATION #include "stb/stb_truetype.h" namespace rx { typedef std::pair<std::string, size_t> FontTuple; static std::map<FontTuple, Font*> fontMap; Font* getFont(std::string name, size_t pixelSize, uint32_t firstChar, size_t numChars, size_t oversampleH, size_t oversampleV) { FontTuple tup(name, pixelSize); if(fontMap.find(tup) != fontMap.end()) { return fontMap[tup]; } std::string path = AssetLoader::getResourcePath() + "fonts/" + name + ".ttf"; uint8_t* ttfbuffer = 0; size_t ttfSize = 0; { struct stat st; int err = stat(path.c_str(), &st); if(err != 0) ERROR("fstat failed with: errno = %d\n", errno); size_t expected = st.st_size; FILE* f = fopen(path.c_str(), "r"); ttfbuffer = new uint8_t[expected]; size_t done = fread(ttfbuffer, 1, expected, f); if(done != expected) ERROR("failure in reading file: expected %zu, got %zu bytes (errno = %d)\n", expected, done, errno); ttfSize = done; fclose(f); } Font* font = new Font(name); font->pixelSize = pixelSize; font->ttfBuffer = ttfbuffer; font->ttfBufferSize = ttfSize; font->firstChar = firstChar; font->numChars = numChars; font->horzOversample = oversampleH; font->vertOversample = oversampleV; // determine how large, approximately, the atlas needs to be. size_t maxpixsize = std::max(oversampleH * pixelSize, oversampleV * pixelSize); size_t numperside = (size_t) (sqrt(numChars) + 1); { size_t atlasWidth = numperside * maxpixsize; size_t atlasHeight = numperside * maxpixsize; uint8_t* atlasBuffer = new uint8_t[atlasWidth * atlasHeight]; assert(atlasBuffer && "failed to allocate memory for atlas"); memset(atlasBuffer, 0, atlasWidth * atlasHeight); // autotex = false -- we want to generate the texture ourselves. font->fontAtlas = new Texture(atlasBuffer, atlasWidth, atlasHeight, ImageFormat::GREYSCALE, false); } LOG("Allocated a %s font atlas (%zux%zu) for font '%s' at size %zupx", Units::formatWithUnits(font->fontAtlas->width * font->fontAtlas->height, 1, "B").c_str(), font->fontAtlas->width, font->fontAtlas->height, name.c_str(), pixelSize); stbtt_InitFont(&font->fontInfo, font->ttfBuffer, 0); // begin stb_truetype stuff { stbtt_pack_context context; if(!stbtt_PackBegin(&context, font->fontAtlas->surf->data, font->fontAtlas->width, font->fontAtlas->height, 0, 1, nullptr)) ERROR("Failed to initialise font '%s'", name.c_str()); font->charInfo = new stbtt_packedchar[font->numChars]; memset(font->charInfo, 0, sizeof(stbtt_packedchar) * font->numChars); stbtt_PackSetOversampling(&context, font->horzOversample, font->vertOversample); if(!stbtt_PackFontRange(&context, font->ttfBuffer, 0, pixelSize, font->firstChar, font->numChars, (stbtt_packedchar*) font->charInfo)) { ERROR("Failed to pack font '%s' into atlas", name.c_str()); } stbtt_PackEnd(&context); // make the opengl texture { using namespace gl; glGenTextures(1, &font->fontAtlas->glTextureID); glBindTexture(GL_TEXTURE_2D, font->fontAtlas->glTextureID); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // minification is more important, since we usually oversample and down-scale for better-looking text glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); float maxAnisotropicFiltering = 0; glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxAnisotropicFiltering); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropicFiltering); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, font->fontAtlas->width, font->fontAtlas->height, 0, GL_RED, GL_UNSIGNED_BYTE, font->fontAtlas->surf->data); glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST); glGenerateMipmap(GL_TEXTURE_2D); } } int ascent = 0; int descent = 0; int linegap = 0; stbtt_GetFontVMetrics(&font->fontInfo, &ascent, &descent, &linegap); font->ascent = ascent * stbtt_ScaleForPixelHeight(&font->fontInfo, font->pixelSize); font->descent = descent * stbtt_ScaleForPixelHeight(&font->fontInfo, font->pixelSize); // make some VBOs that contain all the vertex and UV coordinates { using namespace gl; font->renderObject = new RenderObject(); glBindVertexArray(font->renderObject->vertexArrayObject); GLuint uvBuffer = 0; glGenBuffers(1, &uvBuffer); GLuint vertBuffer = 0; glGenBuffers(1, &vertBuffer); font->renderObject->buffers = { uvBuffer, vertBuffer }; std::vector<lx::fvec2> verts; std::vector<lx::fvec2> uvs; // make the VBO. for(uint32_t ch = firstChar; ch < firstChar + numChars; ch++) { auto fgp = font->getGlyphMetrics(ch); verts.push_back(lx::round(lx::fvec2(fgp.x1, fgp.y0))); // 3 verts.push_back(lx::round(lx::fvec2(fgp.x0, fgp.y1))); // 2 verts.push_back(lx::round(lx::fvec2(fgp.x0, fgp.y0))); // 1 verts.push_back(lx::round(lx::fvec2(fgp.x0, fgp.y1))); verts.push_back(lx::round(lx::fvec2(fgp.x1, fgp.y0))); verts.push_back(lx::round(lx::fvec2(fgp.x1, fgp.y1))); uvs.push_back(lx::fvec2(fgp.u1, fgp.v0)); // 3 uvs.push_back(lx::fvec2(fgp.u0, fgp.v1)); // 2 uvs.push_back(lx::fvec2(fgp.u0, fgp.v0)); // 1 uvs.push_back(lx::fvec2(fgp.u0, fgp.v1)); uvs.push_back(lx::fvec2(fgp.u1, fgp.v0)); uvs.push_back(lx::fvec2(fgp.u1, fgp.v1)); } glEnableVertexAttribArray(0); { glBindBuffer(GL_ARRAY_BUFFER, vertBuffer); glBufferData(GL_ARRAY_BUFFER, verts.size() * sizeof(lx::fvec2), &verts[0], GL_STATIC_DRAW); glVertexAttribPointer( 0, // location 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); } glEnableVertexAttribArray(1); { glBindBuffer(GL_ARRAY_BUFFER, uvBuffer); glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(lx::fvec2), &uvs[0], GL_STATIC_DRAW); glVertexAttribPointer( 1, // location 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); } font->renderObject->arrayLength = verts.size(); font->renderObject->renderType = RenderType::Text; font->renderObject->material = Material(util::colour::white(), font->fontAtlas, font->fontAtlas, 1); glBindVertexArray(0); } fontMap[tup] = font; return font; } FontGlyphPos Font::getGlyphMetrics(uint32_t character) { auto it = this->coordCache.find(character); if(it != this->coordCache.end()) return (*it).second; float xpos = 0; float ypos = 0; // stbtt_aligned_quad quad; stbtt_GetPackedQuad(this->charInfo, this->fontAtlas->width, this->fontAtlas->height, character - this->firstChar, &xpos, &ypos, &quad, 0); auto x0 = quad.x0; auto x1 = quad.x1; auto y0 = quad.y1; auto y1 = quad.y0; FontGlyphPos ret; ret.x0 = x0; ret.y0 = y0; ret.x1 = x1; ret.y1 = y1; // note that we flip the vertical tex coords, since opengl works with (0, 0) at bottom-left // but stb_truetype gives us (0, 0) at top-left. ret.u0 = quad.s0; ret.v0 = quad.t1; ret.u1 = quad.s1; ret.v1 = quad.t0; // fprintf(stderr, "glyph ('%c'):\nxy0: (%f, %f)\nxy1: (%f, %f)\n\n", character, x0, y0, x1, y1); ret.xAdvance = this->charInfo->xadvance; ret.descent = -y0; this->coordCache[character] = ret; return ret; } void closeAllFonts() { for(auto pair : fontMap) { delete[] pair.second->ttfBuffer; delete[] pair.second->fontAtlas; delete[] ((stbtt_packedchar*) pair.second->charInfo); } } }
27.37457
127
0.6765
zhiayang
a8d3237a56ea3587567abea6faf254e185968081
1,671
hpp
C++
program/object-detection-armnn-tflite/includes/detect.hpp
steffenlarsen/armnn-mlperf
c7da4c51f62af7c4e5c43e83345fa23df2fb0bc6
[ "MIT" ]
23
2019-04-24T15:12:40.000Z
2022-01-06T16:10:34.000Z
program/object-detection-armnn-tflite/includes/detect.hpp
steffenlarsen/armnn-mlperf
c7da4c51f62af7c4e5c43e83345fa23df2fb0bc6
[ "MIT" ]
5
2019-06-04T11:07:52.000Z
2022-01-06T16:45:40.000Z
program/object-detection-armnn-tflite/includes/detect.hpp
steffenlarsen/armnn-mlperf
c7da4c51f62af7c4e5c43e83345fa23df2fb0bc6
[ "MIT" ]
8
2019-10-31T11:55:36.000Z
2021-11-21T04:33:34.000Z
/* * Copyright (c) 2019 dividiti Ltd. * Copyright (c) 2019 Arm Ltd. * * SPDX-License-Identifier: MIT. */ #ifndef DETECT_H #define DETECT_H #include <iomanip> #include <vector> #include <iterator> #include "armnn/ArmNN.hpp" #include "armnn/Exceptions.hpp" #include "armnn/Tensor.hpp" #include "armnn/INetwork.hpp" #include "armnnTfLiteParser/ITfLiteParser.hpp" #define OBJECT_DETECTION_ARMNN_TFLITE #include "settings.h" #include "non_max_suppression.h" #include "benchmark.h" using namespace std; using namespace CK; template <typename TData, typename TInConverter, typename TOutConverter> class ArmNNBenchmark : public Benchmark<TData, TInConverter, TOutConverter> { public: ArmNNBenchmark(Settings* settings, TData *in_ptr, TData *boxes_ptr, TData *scores_ptr ) : Benchmark<TData, TInConverter, TOutConverter>(settings, in_ptr, boxes_ptr, scores_ptr) { } }; armnn::InputTensors MakeInputTensors(const std::pair<armnn::LayerBindingId, armnn::TensorInfo>& input, const void* inputTensorData) { return { {input.first, armnn::ConstTensor(input.second, inputTensorData) } }; } armnn::OutputTensors MakeOutputTensors(const std::pair<armnn::LayerBindingId, armnn::TensorInfo>& output, void* outputTensorData) { return { {output.first, armnn::Tensor(output.second, outputTensorData) } }; } void AddTensorToOutput(armnn::OutputTensors &v, const std::pair<armnn::LayerBindingId, armnn::TensorInfo>& output, void* outputTensorData ) { v.push_back({output.first, armnn::Tensor(output.second, outputTensorData) }); } #endif //DETECT_H
28.322034
102
0.708558
steffenlarsen
a8d33ad75224dd08756dc3270497cc6a0db5532e
328
cpp
C++
lessons/06-objects/src/main_item_v2_sol.cpp
chemphys/LearnCPP
025a6e043c6eadb61324c261168bbd0478d9690b
[ "BSD-3-Clause" ]
null
null
null
lessons/06-objects/src/main_item_v2_sol.cpp
chemphys/LearnCPP
025a6e043c6eadb61324c261168bbd0478d9690b
[ "BSD-3-Clause" ]
null
null
null
lessons/06-objects/src/main_item_v2_sol.cpp
chemphys/LearnCPP
025a6e043c6eadb61324c261168bbd0478d9690b
[ "BSD-3-Clause" ]
null
null
null
#include "item_v2_sol.h" int main() { Item myItem; std::cout << "Setting name to `chocolate`\n" << " price to `$1.15`\n" << " num_items to `10`\n"; myItem.SetName("chocolate"); myItem.SetPrice(1.15); myItem.SetNumItems(10); myItem.PrintItem(); return 0; }
16.4
51
0.521341
chemphys
a8d482b137992070a001f7aba4e957db268c238b
6,659
cpp
C++
Libtorch eval/VGG16/vgg16eighty.cpp
atcp1520/soter4
2c2273e1b4788bf30dc93c5590daf77c6b10fb65
[ "MIT" ]
null
null
null
Libtorch eval/VGG16/vgg16eighty.cpp
atcp1520/soter4
2c2273e1b4788bf30dc93c5590daf77c6b10fb65
[ "MIT" ]
null
null
null
Libtorch eval/VGG16/vgg16eighty.cpp
atcp1520/soter4
2c2273e1b4788bf30dc93c5590daf77c6b10fb65
[ "MIT" ]
1
2022-01-14T07:59:21.000Z
2022-01-14T07:59:21.000Z
// VGG16 - 80% in CUDA #include "cuda_runtime.h" #include "device_launch_parameters.h" #include <torch/library.h> #include <torch/script.h> #include <torch/torch.h> #include <ATen/ATen.h> #include <iostream> #include <random> #include <string> #include <io.h> #include <memory> #include <vector> #include <time.h> #include <sys/time.h> namespace F = torch::nn::functional; struct part1 : public torch::nn::Module { torch::nn::Conv2d C1; part1(): C1(torch::nn::Conv2d(torch::nn::Conv2dOptions(3, 64, 3).padding(1))) { register_module("C1", C1); } torch::Tensor fwd_p1(torch::Tensor input) { auto x = F::relu(C1(input)); return x; } }; struct part2 : public torch::nn::Module { torch::nn::Conv2d C3; part2(): C3(torch::nn::Conv2d(torch::nn::Conv2dOptions(64, 64, 3).padding(1))) { register_module("C3", C3); } torch::Tensor fwd_p2(torch::Tensor input) { auto x = F::max_pool2d(F::relu(C3(input)), F::MaxPool2dFuncOptions(2)); return x; } }; struct part3 : public torch::nn::Module { torch::nn::Conv2d C6; part3(): C6(torch::nn::Conv2d(torch::nn::Conv2dOptions(64, 128, 3).padding(1))) { register_module("C6", C6); } torch::Tensor fwd_p3(torch::Tensor input) { auto x = F::relu(C6(input)); return x; } }; struct part4 : public torch::nn::Module { torch::nn::Conv2d C8; part4(): C8(torch::nn::Conv2d(torch::nn::Conv2dOptions(128, 128, 3).padding(1))) { register_module("C8", C8); } torch::Tensor fwd_p4(torch::Tensor input) { auto x = F::max_pool2d(F::relu(C8(input)), F::MaxPool2dFuncOptions(2)); return x; } }; struct part5 : public torch::nn::Module { torch::nn::Conv2d C11; part5(): C11(torch::nn::Conv2d(torch::nn::Conv2dOptions(128, 256, 3).padding(1))) { register_module("C11", C11); } torch::Tensor fwd_p5(torch::Tensor input) { auto x = F::relu(C11(input)); return x; } }; struct part6 : public torch::nn::Module { torch::nn::Conv2d C13; torch::nn::Conv2d C15; torch::nn::Conv2d C18; torch::nn::Conv2d C20; torch::nn::Conv2d C22; torch::nn::Conv2d C25; torch::nn::Conv2d C27; torch::nn::Conv2d C29; torch::nn::Linear FC32; torch::nn::Linear FC35; torch::nn::Linear FC38; part6(): C13(torch::nn::Conv2d(torch::nn::Conv2dOptions(256, 256, 3).padding(1))), C15(torch::nn::Conv2d(torch::nn::Conv2dOptions(256, 256, 3).padding(1))), C18(torch::nn::Conv2d(torch::nn::Conv2dOptions(256, 512, 3).padding(1))), C20(torch::nn::Conv2d(torch::nn::Conv2dOptions(512, 512, 3).padding(1))), C22(torch::nn::Conv2d(torch::nn::Conv2dOptions(512, 512, 3).padding(1))), C25(torch::nn::Conv2d(torch::nn::Conv2dOptions(512, 512, 3).padding(1))), C27(torch::nn::Conv2d(torch::nn::Conv2dOptions(512, 512, 3).padding(1))), C29(torch::nn::Conv2d(torch::nn::Conv2dOptions(512, 512, 3).padding(1))), FC32(torch::nn::Linear(512 * 7 * 7, 4096)), FC35(torch::nn::Linear(4096, 4096)), FC38(torch::nn::Linear(4096, 1000)) { register_module("C13", C13); register_module("C15", C15); register_module("C18", C18); register_module("C20", C20); register_module("C22", C22); register_module("C25", C25); register_module("C27", C27); register_module("C29", C29); register_module("FC32", FC32); register_module("FC35", FC35); register_module("FC38", FC38); } torch::Tensor fwd_p6(torch::Tensor input) { auto x = F::max_pool2d(F::relu(C15(F::relu(C13(input)))), F::MaxPool2dFuncOptions(2)); x = F::max_pool2d(F::relu(C22(F::relu(C20(F::relu(C18(x)))))), F::MaxPool2dFuncOptions(2)); x = F::max_pool2d(F::relu(C29(F::relu(C27(F::relu(C25(x)))))), F::MaxPool2dFuncOptions(2)); x = x.view({ -1, num_flat_features(x) }); x = F::relu(FC32(x)); x = F::relu(FC35(x)); x = FC38(x); return x; } long num_flat_features(torch::Tensor x) { // To except the batch dimension for vgg16_bn: // auto size = x.size()[1:] // For vgg16: auto size = x.sizes(); auto num_features = 1; for (auto s : size) { num_features *= s; } return num_features; } }; struct vgg16_eighty_split { part1 p1; part2 p2; part3 p3; part4 p4; part5 p5; part6 p6; torch::Tensor forward(torch::Tensor input) { input = input.to(at::kCPU); p1.to(at::kCPU); auto x = p1.fwd_p1(input); x = x.to(at::kCUDA); p2.to(at::kCUDA); x = p2.fwd_p2(x); x = x.to(at::kCPU); p3.to(at::kCPU); x = p3.fwd_p3(x); x = x.to(at::kCUDA); p4.to(at::kCUDA); x = p4.fwd_p4(x); x = x.to(at::kCPU); p5.to(at::kCPU); x = p5.fwd_p5(x); x = x.to(at::kCUDA); p6.to(at::kCUDA); x = p6.fwd_p6(x); return x; } }; int main() { std::cout << "vgg16 - 80% outsourced to CUDA version." << std::endl; vgg16_eighty_split model; int count1 = 1000; int count_warmup = 3000; torch::Tensor input = torch::rand({1, 3, 224, 224}); torch::Tensor output; for (size_t i = 0; i < count_warmup; i++) { output = model.forward(input); } cudaEvent_t start, stop; float esp_time_gpu; cudaEventCreate(&start); cudaEventCreate(&stop); float total = 0; for (size_t i = 0; i < count1; i++) { cudaEventRecord(start, 0); output = model.forward(input); cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&esp_time_gpu, start, stop); total += esp_time_gpu; } float latency; latency = total / ((float)count1); std::cout << "For " << count1 << " inferences..." << std::endl; std::cout << "Time elapsed: " << total << " ms." << std::endl; std::cout << "Time consuming: " << latency << " ms per instance." << std::endl; return 0; }
26.636
100
0.526055
atcp1520
a8d4fe181bcec3f99675a7a771839ca38b3db16f
458
hpp
C++
telnetpp/include/telnetpp/options/msdp/detail/decoder.hpp
CalielOfSeptem/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
1
2017-03-30T14:31:33.000Z
2017-03-30T14:31:33.000Z
telnetpp/include/telnetpp/options/msdp/detail/decoder.hpp
HoraceWeebler/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
null
null
null
telnetpp/include/telnetpp/options/msdp/detail/decoder.hpp
HoraceWeebler/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
null
null
null
#pragma once #include "telnetpp/options/msdp/variable.hpp" namespace telnetpp { namespace options { namespace msdp { namespace detail { //* ========================================================================= /// \brief Decode a byte stream into a list of MSDP variables. //* ========================================================================= std::vector<telnetpp::options::msdp::variable> decode( telnetpp::u8stream const &stream); }}}}
32.714286
77
0.4869
CalielOfSeptem
a8d8972bac80e68d05e8e6b1cd9287ae3f9dbe91
685
cpp
C++
lab2/Lab2Task4Var4/Lab2Task4Var4/Lab2Task4Var4.cpp
AlexanderChibirev/OOP
e30adebbf961d9573a2d14981e5d8b92466207fd
[ "MIT" ]
null
null
null
lab2/Lab2Task4Var4/Lab2Task4Var4/Lab2Task4Var4.cpp
AlexanderChibirev/OOP
e30adebbf961d9573a2d14981e5d8b92466207fd
[ "MIT" ]
9
2016-02-17T09:08:02.000Z
2016-05-19T12:02:59.000Z
lab2/Lab2Task4Var4/Lab2Task4Var4/Lab2Task4Var4.cpp
AlexanderChibirev/OOP
e30adebbf961d9573a2d14981e5d8b92466207fd
[ "MIT" ]
null
null
null
// Lab2Task4Var4.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "GeneratePrimeNumbersSet.h" int main(int argc, char** argv) { if (argc != 2) { std::cout << "Wrong amount of arguments was proposed\nEnter a correct arguments amount please, for example:\n'upperBound < 0 or upperBound > 10000000'"; return 1; } int upperBound = atoi("asasddd"); //auto upperBound = boost::lexical_cast<int>(argv[1]); if (upperBound < 0 || upperBound > 100000000) { std::cout << "Wrong number\n"; return 1; } std::set<int> primeSet = GeneratePrimeNumbersSet(upperBound); for (int x : primeSet) { std::cout << x << " "; } return 0; }
22.096774
154
0.670073
AlexanderChibirev
a8d8c005a64253a10cb9005070a72d00ef246a2c
9,993
cpp
C++
src/monStaGen/incrementalDeterministicGraphGenerator.cpp
tyrex-team/gmark
e9f16c06d2c9fb76167077a3839d2f10585bc546
[ "MIT" ]
8
2020-01-04T15:12:36.000Z
2021-12-15T16:26:52.000Z
src/monStaGen/incrementalDeterministicGraphGenerator.cpp
tyrex-team/gmark
e9f16c06d2c9fb76167077a3839d2f10585bc546
[ "MIT" ]
2
2019-12-17T18:29:57.000Z
2020-04-09T14:01:37.000Z
src/monStaGen/incrementalDeterministicGraphGenerator.cpp
tyrex-team/gmark
e9f16c06d2c9fb76167077a3839d2f10585bc546
[ "MIT" ]
5
2020-02-22T20:20:13.000Z
2022-01-19T21:12:47.000Z
/* * incrementalDeterministicGraphGenerator.cpp * * Created on: Sep 16, 2016 * Author: wilcovanleeuwen */ #include <vector> #include <algorithm> // std::set_intersection, std::sort #include <chrono> #include "incrementalDeterministicGraphGenerator.h" #include "graphNode.h" namespace std { incrementalDeterministicGraphGenerator::incrementalDeterministicGraphGenerator() { randomGenerator.seed((unsigned int) chrono::system_clock::now().time_since_epoch().count()); // randomGenerator.seed(22); } incrementalDeterministicGraphGenerator::~incrementalDeterministicGraphGenerator() { } void incrementalDeterministicGraphGenerator::addEdge(graphNode &sourceNode, graphNode &targetNode, int predicate) { sourceNode.decrementOpenInterfaceConnections(); targetNode.decrementOpenInterfaceConnections(); edge2 newEdge; newEdge.subjectIterationId = sourceNode.iterationId; newEdge.objectIterationId = targetNode.iterationId; newEdge.subjectId = sourceNode.id; newEdge.predicate = predicate; newEdge.objectId = targetNode.id; newEdge.createdInGraph = graphNumber; edges.push_back(newEdge); } void incrementalDeterministicGraphGenerator::fixSchemaInequality(config::edge & edgeType) { double evOutDistribution = getMeanICsPerNode(edgeType.outgoing_distrib, conf.types[edgeType.subject_type].size[graphNumber]) + outDistrShift; double evInDistribution = getMeanICsPerNode(edgeType.incoming_distrib, conf.types[edgeType.object_type].size[graphNumber]) + inDistrShift; if ((conf.types[edgeType.subject_type].size[graphNumber] * evOutDistribution) > (conf.types[edgeType.object_type].size[graphNumber] * evInDistribution)) { performInDistributionShift(edgeType); } else { performOutDistributionShift(edgeType); } } vector<int> constructNodesVector(vector<graphNode> & nodes) { vector<int> nodesVector; for (graphNode & n: nodes) { // cout << "node" << n.iterationId << " has " << n.getNumberOfOpenInterfaceConnections() << " openICs" << endl; for (int i=0; i<n.getNumberOfOpenInterfaceConnections(); i++) { nodesVector.push_back(n.iterationId); } } return nodesVector; } vector<int> constructNodesVectorMinusOne(vector<graphNode> & nodes) { vector<int> nodesVector; for (graphNode & n: nodes) { // cout << "node" << n.iterationId << " has " << n.getNumberOfOpenInterfaceConnections() << " openICs" << endl; for (int i=0; i<n.getNumberOfOpenInterfaceConnections()-1; i++) { nodesVector.push_back(n.iterationId); } } return nodesVector; } vector<int> constructNodesVectorLastOne(vector<graphNode> & nodes) { vector<int> nodesVector; for (graphNode & n: nodes) { if(n.getNumberOfOpenInterfaceConnections() > 0) { nodesVector.push_back(n.iterationId); } } return nodesVector; } void incrementalDeterministicGraphGenerator::generateEdges(config::edge & edgeType, double prob) { if (edgeType.scale_factor > 0 || !conf.types[edgeType.subject_type].scalable || !conf.types[edgeType.object_type].scalable || edgeType.outgoing_distrib.type == DISTRIBUTION::ZIPFIAN || edgeType.incoming_distrib.type == DISTRIBUTION::ZIPFIAN) { vector<int> subjectNodeIdVector = constructNodesVector(nodes.first); vector<int> objectNodeIdVector = constructNodesVector(nodes.second); if (edgeType.outgoing_distrib.type == DISTRIBUTION::ZIPFIAN || edgeType.incoming_distrib.type == DISTRIBUTION::ZIPFIAN) { performFixingShiftForZipfian(edgeType, subjectNodeIdVector, objectNodeIdVector); } shuffle(subjectNodeIdVector.begin(), subjectNodeIdVector.end(), randomGenerator); shuffle(objectNodeIdVector.begin(), objectNodeIdVector.end(), randomGenerator); for (size_t i=0; i<min(subjectNodeIdVector.size(), objectNodeIdVector.size()); i++) { addEdge(nodes.first[subjectNodeIdVector[i]], nodes.second[objectNodeIdVector[i]], edgeType.predicate); } } else { // Create vectors vector<int> subjectNodeIdVectorMinusOne = constructNodesVectorMinusOne(nodes.first); vector<int> objectNodeIdVectorMinusOne = constructNodesVectorMinusOne(nodes.second); vector<int> subjectNodeIdVectorLastOne = constructNodesVectorLastOne(nodes.first); vector<int> objectNodeIdVectorLastOne = constructNodesVectorLastOne(nodes.second); // Shuffle small vectors shuffle(subjectNodeIdVectorLastOne.begin(), subjectNodeIdVectorLastOne.end(), randomGenerator); shuffle(objectNodeIdVectorLastOne.begin(), objectNodeIdVectorLastOne.end(), randomGenerator); // Add the difference in the lastOne-vector to the minusOne-vector if (subjectNodeIdVectorLastOne.size() > objectNodeIdVectorLastOne.size()) { for (size_t i=objectNodeIdVectorLastOne.size(); i<subjectNodeIdVectorLastOne.size(); i++) { subjectNodeIdVectorMinusOne.push_back(subjectNodeIdVectorLastOne[i]); } } else { for (size_t i=subjectNodeIdVectorLastOne.size(); i<objectNodeIdVectorLastOne.size(); i++) { objectNodeIdVectorMinusOne.push_back(objectNodeIdVectorLastOne[i]); } } // Shuffle large vectors shuffle(subjectNodeIdVectorMinusOne.begin(), subjectNodeIdVectorMinusOne.end(), randomGenerator); shuffle(objectNodeIdVectorMinusOne.begin(), objectNodeIdVectorMinusOne.end(), randomGenerator); // Create edges for (size_t i=0; i<min(subjectNodeIdVectorMinusOne.size(), objectNodeIdVectorMinusOne.size()); i++) { addEdge(nodes.first[subjectNodeIdVectorMinusOne[i]], nodes.second[objectNodeIdVectorMinusOne[i]], edgeType.predicate); } for (size_t i=0; i<min(subjectNodeIdVectorLastOne.size(), objectNodeIdVectorLastOne.size()); i++) { double randomValue = uniformDistr(randomGenerator); if (randomValue > prob) { addEdge(nodes.first[subjectNodeIdVectorLastOne[i]], nodes.second[objectNodeIdVectorLastOne[i]], edgeType.predicate); } } } } void incrementalDeterministicGraphGenerator::incrementGraph(config::edge & edgeType) { // Perform the shifting of the distribution as indecated by the user in the schema if (graphNumber > 0) { performSchemaIndicatedShift(edgeType); if ((conf.types.at(edgeType.subject_type).scalable ^ conf.types.at(edgeType.object_type).scalable) && edgeType.outgoing_distrib.type != DISTRIBUTION::ZIPFIAN && edgeType.incoming_distrib.type != DISTRIBUTION::ZIPFIAN) { performShiftForNonScalableNodes(edgeType); } } // Add subject and object nodes to the graph // Specify the current shift to get the wright amound of ICs nodeGen.addSubjectNodes(edgeType, outDistrShift, graphNumber); nodeGen.addObjectNodes(edgeType, inDistrShift, graphNumber); // Update the ICs for the Zipfian distribution to satisfy the property that influecer nodes will get more ICs when the graph grows if (edgeType.outgoing_distrib.type == DISTRIBUTION::ZIPFIAN) { updateInterfaceConnectionsForZipfianDistributions(edgeType.outgoing_distrib, true); } if (edgeType.incoming_distrib.type == DISTRIBUTION::ZIPFIAN) { updateInterfaceConnectionsForZipfianDistributions(edgeType.incoming_distrib, false); } double prob = 0.25; if (edgeType.correlated_with.size() == 0) { generateEdges(edgeType, prob); } else { vector<edge2> possibleEdges = generateCorrelatedEdgeSet(edgeType); generateCorrelatedEdges(edgeType, prob, possibleEdges); } } int incrementalDeterministicGraphGenerator::processEdgeTypeSingleGraph(config::config configuration, config::edge & edgeType, ofstream & outputFile, string outputFileName_, int graphNumber_, bool printNodeProperties) { cout << "Processing graph " << graphNumber_ << " edge type " << edgeType.edge_type_id << endl; // cout << endl << endl; this->conf = configuration; this->graphNumber = graphNumber_; this->outputFileName = outputFileName_; // cout << "Number of nodes: " << conf.nb_nodes[graphNumber] << endl; if (edgeType.outgoing_distrib.type == DISTRIBUTION::ZIPFIAN && outDistrShift == 0) { outDistrShift = 1; } if (edgeType.incoming_distrib.type == DISTRIBUTION::ZIPFIAN && inDistrShift == 0) { inDistrShift = 1; } if (graphNumber == 0 && edgeType.outgoing_distrib.type != DISTRIBUTION::ZIPFIAN && edgeType.incoming_distrib.type != DISTRIBUTION::ZIPFIAN) { fixSchemaInequality(edgeType); } nodeGen = nodeGenerator(edgeType, nodes.first.size(), nodes.second.size(), &randomGenerator, &nodes, &conf); if (edgeType.correlated_with.size() > 0) { cout << "Assume the following edge-type have been generated: " << endl; for (int etId: edgeType.correlated_with) { cout << " - " << etId << endl; } } incrementGraph(edgeType); // Materialize the edge // cout << "Number of edges: " << edges.size() << endl; for (size_t i=0; i<edges.size(); i++) { edge2 e = edges[i]; outputFile << e.subjectId << " "; if (conf.print_alias) { outputFile << conf.predicates[e.predicate].alias; } else { outputFile << e.predicate; } outputFile << " " << e.objectId << " | " << e.createdInGraph <<"\n"; } outputFile.flush(); if (printNodeProperties) { string subjectsNodesFileName = outputFileName + "_subjects_edgeType" + to_string(edgeType.edge_type_id) + "graphNumber" + to_string(graphNumber_) +".txt"; ofstream subjectNodes; subjectNodes.open(subjectsNodesFileName); subjectNodes << "Global node id, local node id, degree in the graph\n"; for (graphNode subject: nodes.first) { subjectNodes << subject.id << ", " << subject.iterationId << ", " << subject.numberOfInterfaceConnections-subject.numberOfOpenInterfaceConnections << "\n"; } subjectNodes.flush(); string objectsNodesFileName = outputFileName + "_objects_edgeType" + to_string(edgeType.edge_type_id) + "graphNumber" + to_string(graphNumber_) +".txt"; ofstream objectNodes; objectNodes.open(objectsNodesFileName); objectNodes << "Global node id, local node id, degree in the graph\n"; for (graphNode object: nodes.second) { objectNodes << object.id << ", " << object.iterationId << ", " << object.numberOfInterfaceConnections-object.numberOfOpenInterfaceConnections << "\n"; } objectNodes.flush(); } cout << endl; return 0; } } /* namespace std */
35.18662
158
0.749925
tyrex-team
a8da46207fb40fcd8b6a5cda7b0bfc146bef0671
7,681
cpp
C++
bullet-2.81-rev2613/src/BulletFluids/btFluidHfRigidDynamicsWorld.cpp
rtrius/Bullet-FLUIDS
b58dbc5108512e5a4bb0a532284a98128fd8f8ce
[ "Zlib" ]
19
2015-01-18T09:34:48.000Z
2021-07-22T08:00:17.000Z
bullet-2.81-rev2613/src/BulletFluids/btFluidHfRigidDynamicsWorld.cpp
rtrius/Bullet-FLUIDS
b58dbc5108512e5a4bb0a532284a98128fd8f8ce
[ "Zlib" ]
null
null
null
bullet-2.81-rev2613/src/BulletFluids/btFluidHfRigidDynamicsWorld.cpp
rtrius/Bullet-FLUIDS
b58dbc5108512e5a4bb0a532284a98128fd8f8ce
[ "Zlib" ]
8
2015-02-09T08:03:04.000Z
2021-07-22T08:01:54.000Z
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Experimental Buoyancy fluid demo written by John McCutchan */ //This is an altered source version based on the HeightFieldFluidDemo included with Bullet Physics 2.80(bullet-2.80-rev2531). #include "btFluidHfRigidDynamicsWorld.h" #include <stdio.h> #include "LinearMath/btQuickprof.h" #include "LinearMath/btIDebugDraw.h" #include "BulletCollision/CollisionShapes/btCollisionShape.h" #include "Hf/btFluidHf.h" #include "Hf/btFluidHfBuoyantConvexShape.h" btFluidHfRigidDynamicsWorld::btFluidHfRigidDynamicsWorld(btDispatcher* dispatcher, btBroadphaseInterface* pairCache, btConstraintSolver* constraintSolver, btCollisionConfiguration* collisionConfiguration, btFluidSphSolver* sphSolver) : btFluidRigidDynamicsWorld(dispatcher, pairCache, constraintSolver, collisionConfiguration, sphSolver) { m_drawMode = DRAWMODE_NORMAL; m_bodyDrawMode = BODY_DRAWMODE_NORMAL; } void btFluidHfRigidDynamicsWorld::internalSingleStepSimulation(btScalar timeStep) { btFluidRigidDynamicsWorld::internalSingleStepSimulation(timeStep); { BT_PROFILE("updateHfFluids"); for(int i = 0; i < m_hfFluids.size(); i++) { btFluidHf* hfFluid = m_hfFluids[i]; hfFluid->stepSimulation(timeStep); } } } void btFluidHfRigidDynamicsWorld::addFluidHf(btFluidHf* body) { m_hfFluids.push_back(body); btCollisionWorld::addCollisionObject(body, btBroadphaseProxy::DefaultFilter, btBroadphaseProxy::AllFilter); } void btFluidHfRigidDynamicsWorld::removeFluidHf(btFluidHf* body) { m_hfFluids.remove(body); btCollisionWorld::removeCollisionObject(body); } void btFluidHfRigidDynamicsWorld::drawFluidHfGround (btIDebugDraw* debugDraw, btFluidHf* fluid) { btVector3 com = fluid->getWorldTransform().getOrigin(); btVector3 color = btVector3(btScalar(0.13f), btScalar(0.13f), btScalar(0.0)); for (int i = 1; i < fluid->getNumNodesX()-1; i++) { for (int j = 1; j < fluid->getNumNodesZ()-1; j++) { int sw = fluid->arrayIndex (i, j); int se = fluid->arrayIndex (i+1, j); int nw = fluid->arrayIndex (i, j+1); int ne = fluid->arrayIndex (i+1, j+1); btVector3 swV = btVector3 (fluid->getCellPosX (i), fluid->getGroundHeight(sw), fluid->getCellPosZ (j)); btVector3 seV = btVector3 (fluid->getCellPosX (i+1), fluid->getGroundHeight(se), fluid->getCellPosZ (j)); btVector3 nwV = btVector3 (fluid->getCellPosX (i), fluid->getGroundHeight(nw), fluid->getCellPosZ (j+1)); btVector3 neV = btVector3 (fluid->getCellPosX (i+1), fluid->getGroundHeight(ne), fluid->getCellPosZ (j+1)); debugDraw->drawTriangle (swV+com, seV+com, nwV+com, color, btScalar(1.0f)); debugDraw->drawTriangle (seV+com, neV+com, nwV+com, color, btScalar(1.0f)); } } } void btFluidHfRigidDynamicsWorld::drawFluidHfVelocity (btIDebugDraw* debugDraw, btFluidHf* fluid) { const btVector3& origin = fluid->getWorldTransform().getOrigin(); const btVector3 red = btVector3(btScalar(1.0f), btScalar(0.0f), btScalar(0.0)); const btVector3 green = btVector3(btScalar(0.0f), btScalar(1.0f), btScalar(0.0)); for (int i = 1; i < fluid->getNumNodesX()-1; i++) { for (int j = 1; j < fluid->getNumNodesZ()-1; j++) { int index = fluid->arrayIndex (i, j); if( !fluid->isActive(index) ) continue; btVector3 from = btVector3 ( fluid->getCellPosX(i), fluid->getCombinedHeight(index) + btScalar(0.1f), fluid->getCellPosZ(j) ); btVector3 velocity( fluid->getVelocityX(index), btScalar(0.0), fluid->getVelocityZ(index) ); velocity.normalize(); btVector3 to = from + velocity; debugDraw->drawLine (from+origin, to+origin, red, green); } } } void btFluidHfRigidDynamicsWorld::drawFluidHfBuoyantConvexShape (btIDebugDraw* debugDrawer, btCollisionObject* object, btFluidHfBuoyantConvexShape* buoyantShape, int voxelDraw) { if (voxelDraw) { const btTransform& xform = object->getWorldTransform(); for (int i = 0; i < buoyantShape->getNumVoxels(); i++) { btVector3 p = xform * buoyantShape->getVoxelPosition(i); debugDrawer->drawSphere( p, buoyantShape->getVoxelRadius(), btVector3(1.0, 0.0, 0.0) ); } } else { btVector3 color(btScalar(255.),btScalar(255.),btScalar(255.)); switch(object->getActivationState()) { case ACTIVE_TAG: color = btVector3(btScalar(255.),btScalar(255.),btScalar(255.)); break; case ISLAND_SLEEPING: color = btVector3(btScalar(0.),btScalar(255.),btScalar(0.));break; case WANTS_DEACTIVATION: color = btVector3(btScalar(0.),btScalar(255.),btScalar(255.));break; case DISABLE_DEACTIVATION: color = btVector3(btScalar(255.),btScalar(0.),btScalar(0.));break; case DISABLE_SIMULATION: color = btVector3(btScalar(255.),btScalar(255.),btScalar(0.));break; default: { color = btVector3(btScalar(255.),btScalar(0.),btScalar(0.)); } }; btConvexShape* convexShape = ((btFluidHfBuoyantConvexShape*)object->getCollisionShape())->getConvexShape(); debugDrawObject(object->getWorldTransform(),(btCollisionShape*)convexShape,color); } } void btFluidHfRigidDynamicsWorld::drawFluidHfNormal (btIDebugDraw* debugDraw, btFluidHf* fluid) { const btVector3& com = fluid->getWorldTransform().getOrigin(); for (int i = 0; i < fluid->getNumNodesX()-1; i++) { for (int j = 0; j < fluid->getNumNodesZ()-1; j++) { int sw = fluid->arrayIndex (i, j); btScalar h = fluid->getFluidHeight(sw); btScalar g = fluid->getGroundHeight(sw); if( h < btScalar(0.03f) ) continue; btVector3 boxMin = btVector3(fluid->getCellPosX (i), g, fluid->getCellPosZ(j)); btVector3 boxMax = btVector3(fluid->getCellPosX(i+1), g+h, fluid->getCellPosZ(j+1)); boxMin += com; boxMax += com; debugDraw->drawBox (boxMin, boxMax, btVector3(btScalar(0.0f), btScalar(0.0f), btScalar(1.0f))); } } } void btFluidHfRigidDynamicsWorld::debugDrawWorld() { if (getDebugDrawer()) { int i; for ( i=0;i<this->m_hfFluids.size();i++) { btFluidHf* phh=(btFluidHf*)this->m_hfFluids[i]; switch (m_drawMode) { case DRAWMODE_NORMAL: //drawFluidHfGround (m_debugDrawer, phh); //drawFluidHfNormal (m_debugDrawer, phh); break; case DRAWMODE_VELOCITY: //drawFluidHfGround (m_debugDrawer, phh); //drawFluidHfNormal (m_debugDrawer, phh); drawFluidHfVelocity (m_debugDrawer, phh); break; default: btAssert (0); break; } } for (i = 0; i < this->m_collisionObjects.size(); i++) { btCollisionShape* shape = m_collisionObjects[i]->getCollisionShape(); if (shape->getShapeType() == HFFLUID_BUOYANT_CONVEX_SHAPE_PROXYTYPE) { btFluidHfBuoyantConvexShape* buoyantShape = (btFluidHfBuoyantConvexShape*)shape; drawFluidHfBuoyantConvexShape (m_debugDrawer, m_collisionObjects[i], buoyantShape, m_bodyDrawMode); } } } btFluidRigidDynamicsWorld::debugDrawWorld(); }
36.402844
243
0.728291
rtrius
a8df659c0231eab9f7ce36fbe8fe6c5553ba3673
9,504
cc
C++
src/arg_parse.cc
dstrain115/Stim
82a161741c05d637fe16ea20b1d99a48b4ca4750
[ "Apache-2.0" ]
2
2021-07-24T13:56:07.000Z
2021-11-17T11:03:51.000Z
src/arg_parse.cc
ephxyscj1996/Stim
1f35e36c33a6dba244318e904c35b63a3d82977a
[ "Apache-2.0" ]
null
null
null
src/arg_parse.cc
ephxyscj1996/Stim
1f35e36c33a6dba244318e904c35b63a3d82977a
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 Google LLC // // 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 "arg_parse.h" #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> using namespace stim_internal; const char *stim_internal::require_find_argument(const char *name, int argc, const char **argv) { const char *result = find_argument(name, argc, argv); if (result == 0) { fprintf(stderr, "\033[31mMissing command line argument: '%s'\033[0m\n", name); exit(EXIT_FAILURE); } return result; } const char *stim_internal::find_argument(const char *name, int argc, const char **argv) { // Respect that the "--" argument terminates flags. size_t flag_count = 1; while (flag_count < (size_t)argc && strcmp(argv[flag_count], "--") != 0) { flag_count++; } // Search for the desired flag. size_t n = strlen(name); for (size_t i = 1; i < flag_count; i++) { // Check if argument starts with expected flag. const char *loc = strstr(argv[i], name); if (loc != argv[i] || (loc[n] != '\0' && loc[n] != '=')) { continue; } // If the flag is alone and followed by the end or another flag, no // argument was provided. Return the empty string to indicate this. if (loc[n] == '\0' && ((int)i == argc - 1 || (argv[i + 1][0] == '-' && !isdigit(argv[i + 1][1])))) { return argv[i] + n; } // If the flag value is specified inline with '=', return a pointer to // the start of the value within the flag string. if (loc[n] == '=') { // Argument provided inline. return loc + n + 1; } // The argument value is specified by the next command line argument. return argv[i + 1]; } // Not found. return 0; } void stim_internal::check_for_unknown_arguments( const std::vector<const char *> &known_arguments, const char *for_mode, int argc, const char **argv) { for (int i = 1; i < argc; i++) { // Respect that the "--" argument terminates flags. if (!strcmp(argv[i], "--")) { break; } // Check if there's a matching command line argument. int matched = 0; for (size_t j = 0; j < known_arguments.size(); j++) { const char *loc = strstr(argv[i], known_arguments[j]); size_t n = strlen(known_arguments[j]); if (loc == argv[i] && (loc[n] == '\0' || loc[n] == '=')) { // Skip words that are values for a previous flag. if (loc[n] == '\0' && i < argc - 1 && argv[i + 1][0] != '-') { i++; } matched = 1; break; } } // Print error and exit if flag is not recognized. if (!matched) { if (for_mode == nullptr) { fprintf(stderr, "\033[31mUnrecognized command line argument %s.\n", argv[i]); fprintf(stderr, "Recognized command line arguments:\n"); } else { fprintf(stderr, "\033[31mUnrecognized command line argument %s for mode %s.\n", argv[i], for_mode); fprintf(stderr, "Recognized command line arguments for mode %s:\n", for_mode); } for (size_t j = 0; j < known_arguments.size(); j++) { fprintf(stderr, " %s\n", known_arguments[j]); } fprintf(stderr, "\033[0m"); exit(EXIT_FAILURE); } } } bool stim_internal::find_bool_argument(const char *name, int argc, const char **argv) { const char *text = find_argument(name, argc, argv); if (text == nullptr) { return false; } if (text[0] == '\0') { return true; } fprintf(stderr, "\033[31mGot non-empty value '%s' for boolean flag '%s'.\033[0m\n", text, name); exit(EXIT_FAILURE); } bool parse_int64(const char *data, int64_t *out) { char c = *data; if (c == 0) { return false; } bool negate = false; if (c == '-') { negate = true; data++; c = *data; } uint64_t accumulator = 0; while (c) { if (!(c >= '0' && c <= '9')) { return false; } uint64_t digit = c - '0'; uint64_t next = accumulator * 10 + digit; if (accumulator != (next - digit) / 10) { return false; // Overflow. } accumulator = next; data++; c = *data; } if (negate && accumulator == (uint64_t)INT64_MAX + uint64_t{1}) { *out = INT64_MIN; return true; } if (accumulator > INT64_MAX) { return false; } *out = (int64_t)accumulator; if (negate) { *out *= -1; } return true; } int64_t stim_internal::find_int64_argument( const char *name, int64_t default_value, int64_t min_value, int64_t max_value, int argc, const char **argv) { const char *text = find_argument(name, argc, argv); if (text == nullptr || text[0] == '\0') { if (default_value < min_value || default_value > max_value) { fprintf( stderr, "\033[31m" "Must specify a value for int flag '%s'.\n" "\033[0m", name); exit(EXIT_FAILURE); } return default_value; } // Attempt to parse. int64_t i; if (!parse_int64(text, &i)) { fprintf(stderr, "\033[31mGot non-int64 value '%s' for int64 flag '%s'.\033[0m\n", text, name); exit(EXIT_FAILURE); } // In range? if (i < min_value || i > max_value) { std::cerr << "\033[31mInteger value '" << text << "' for flag '" << name << "' doesn't satisfy " << min_value << " <= " << i << " <= " << max_value << ".\033[0m\n"; exit(EXIT_FAILURE); } return i; } float stim_internal::find_float_argument( const char *name, float default_value, float min_value, float max_value, int argc, const char **argv) { const char *text = find_argument(name, argc, argv); if (text == nullptr) { if (default_value < min_value || default_value > max_value) { fprintf( stderr, "\033[31m" "Must specify a value for float flag '%s'.\n" "\033[0m", name); exit(EXIT_FAILURE); } return default_value; } // Attempt to parse. char *processed; float f = strtof(text, &processed); if (*processed != '\0') { fprintf(stderr, "\033[31mGot non-float value '%s' for float flag '%s'.\033[0m\n", text, name); exit(EXIT_FAILURE); } // In range? if (f < min_value || f > max_value || f != f) { fprintf( stderr, "\033[31mFloat value '%s' for flag '%s' doesn't satisfy %f <= %f <= %f.\033[0m\n", text, name, min_value, f, max_value); exit(EXIT_FAILURE); } return f; } FILE *stim_internal::find_open_file_argument( const char *name, FILE *default_file, const char *mode, int argc, const char **argv) { const char *path = find_argument(name, argc, argv); if (path == nullptr) { if (default_file == nullptr) { std::cerr << "\033[31mMissing command line argument: '" << name << "'\033[0m\n"; exit(EXIT_FAILURE); } return default_file; } if (*path == '\0') { std::cerr << "\033[31mCommand line argument '" << name << "' can't be empty. It's supposed to be a file path.\033[0m\n"; exit(EXIT_FAILURE); } FILE *file = fopen(path, mode); if (file == nullptr) { std::cerr << "\033[31mFailed to open '" << path << "'\033[0m\n"; exit(EXIT_FAILURE); } return file; } ostream_else_cout::ostream_else_cout(std::unique_ptr<std::ostream> &&held) : held(std::move(held)) { } std::ostream &ostream_else_cout::stream() { if (held) { return *held; } else { return std::cout; } } ostream_else_cout stim_internal::find_output_stream_argument( const char *name, bool default_std_out, int argc, const char **argv) { const char *path = find_argument(name, argc, argv); if (path == nullptr) { if (!default_std_out) { std::cerr << "\033[31mMissing command line argument: '" << name << "'\033[0m\n"; exit(EXIT_FAILURE); } return {nullptr}; } if (*path == '\0') { std::cerr << "\033[31mCommand line argument '" << name << "' can't be empty. It's supposed to be a file path.\033[0m\n"; exit(EXIT_FAILURE); } std::unique_ptr<std::ostream> f(new std::ofstream(path)); if (f->fail()) { std::cerr << "\033[31mFailed to open '" << path << "'\033[0m\n"; exit(EXIT_FAILURE); } return {std::move(f)}; }
32.216949
117
0.539983
dstrain115
a8e1a3df1922b5c8d625de3942b1b5e1f9824e29
20,621
hpp
C++
include/vuk/Image.hpp
zacharycarter/vuk
db3808fbbebcbf1912f060b54aad083e0e0168ae
[ "MIT" ]
173
2020-02-25T08:35:12.000Z
2022-03-28T07:48:39.000Z
include/vuk/Image.hpp
zacharycarter/vuk
db3808fbbebcbf1912f060b54aad083e0e0168ae
[ "MIT" ]
42
2020-10-15T12:48:29.000Z
2022-03-19T17:08:58.000Z
include/vuk/Image.hpp
zacharycarter/vuk
db3808fbbebcbf1912f060b54aad083e0e0168ae
[ "MIT" ]
13
2020-05-28T13:28:46.000Z
2022-02-06T09:34:50.000Z
#pragma once #include "Types.hpp" #include "../src/CreateInfo.hpp" namespace vuk { using Image = VkImage; using Sampler = Handle<VkSampler>; enum class ImageTiling { eOptimal = VK_IMAGE_TILING_OPTIMAL, eLinear = VK_IMAGE_TILING_LINEAR, eDrmFormatModifierEXT = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT }; enum class ImageType { e1D = VK_IMAGE_TYPE_1D, e2D = VK_IMAGE_TYPE_2D, e3D = VK_IMAGE_TYPE_3D }; enum class ImageUsageFlagBits : VkImageUsageFlags { eTransferSrc = VK_IMAGE_USAGE_TRANSFER_SRC_BIT, eTransferDst = VK_IMAGE_USAGE_TRANSFER_DST_BIT, eSampled = VK_IMAGE_USAGE_SAMPLED_BIT, eStorage = VK_IMAGE_USAGE_STORAGE_BIT, eColorAttachment = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, eDepthStencilAttachment = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, eTransientAttachment = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT, eInputAttachment = VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, eShadingRateImageNV = VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV, eFragmentDensityMapEXT = VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT }; using ImageUsageFlags = Flags<ImageUsageFlagBits>; inline constexpr ImageUsageFlags operator|(ImageUsageFlagBits bit0, ImageUsageFlagBits bit1) noexcept { return ImageUsageFlags(bit0) | bit1; } inline constexpr ImageUsageFlags operator&(ImageUsageFlagBits bit0, ImageUsageFlagBits bit1) noexcept { return ImageUsageFlags(bit0) & bit1; } inline constexpr ImageUsageFlags operator^(ImageUsageFlagBits bit0, ImageUsageFlagBits bit1) noexcept { return ImageUsageFlags(bit0) ^ bit1; } enum class ImageCreateFlagBits : VkImageCreateFlags { eSparseBinding = VK_IMAGE_CREATE_SPARSE_BINDING_BIT, eSparseResidency = VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT, eSparseAliased = VK_IMAGE_CREATE_SPARSE_ALIASED_BIT, eMutableFormat = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, eCubeCompatible = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT, eAlias = VK_IMAGE_CREATE_ALIAS_BIT, eSplitInstanceBindRegions = VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT, e2DArrayCompatible = VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT, eBlockTexelViewCompatible = VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT, eExtendedUsage = VK_IMAGE_CREATE_EXTENDED_USAGE_BIT, eProtected = VK_IMAGE_CREATE_PROTECTED_BIT, eDisjoint = VK_IMAGE_CREATE_DISJOINT_BIT, eCornerSampledNV = VK_IMAGE_CREATE_CORNER_SAMPLED_BIT_NV, eSampleLocationsCompatibleDepthEXT = VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT, eSubsampledEXT = VK_IMAGE_CREATE_SUBSAMPLED_BIT_EXT, e2DArrayCompatibleKHR = VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR, eAliasKHR = VK_IMAGE_CREATE_ALIAS_BIT_KHR, eBlockTexelViewCompatibleKHR = VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT_KHR, eDisjointKHR = VK_IMAGE_CREATE_DISJOINT_BIT_KHR, eExtendedUsageKHR = VK_IMAGE_CREATE_EXTENDED_USAGE_BIT_KHR, eSplitInstanceBindRegionsKHR = VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR }; using ImageCreateFlags = Flags<ImageCreateFlagBits>; inline constexpr ImageCreateFlags operator|(ImageCreateFlagBits bit0, ImageCreateFlagBits bit1) noexcept { return ImageCreateFlags(bit0) | bit1; } inline constexpr ImageCreateFlags operator&(ImageCreateFlagBits bit0, ImageCreateFlagBits bit1) noexcept { return ImageCreateFlags(bit0) & bit1; } inline constexpr ImageCreateFlags operator^(ImageCreateFlagBits bit0, ImageCreateFlagBits bit1) noexcept { return ImageCreateFlags(bit0) ^ bit1; } enum class ImageLayout { eUndefined = VK_IMAGE_LAYOUT_UNDEFINED, eGeneral = VK_IMAGE_LAYOUT_GENERAL, eColorAttachmentOptimal = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, eDepthStencilAttachmentOptimal = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, eDepthStencilReadOnlyOptimal = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, eShaderReadOnlyOptimal = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, eTransferSrcOptimal = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, eTransferDstOptimal = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, ePreinitialized = VK_IMAGE_LAYOUT_PREINITIALIZED, eDepthReadOnlyStencilAttachmentOptimal = VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL, eDepthAttachmentStencilReadOnlyOptimal = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL, eDepthAttachmentOptimal = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, eDepthReadOnlyOptimal = VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL, eStencilAttachmentOptimal = VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL, eStencilReadOnlyOptimal = VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL, ePresentSrcKHR = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, eSharedPresentKHR = VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR, eShadingRateOptimalNV = VK_IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV, eFragmentDensityMapOptimalEXT = VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT, eDepthAttachmentOptimalKHR = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL_KHR, eDepthAttachmentStencilReadOnlyOptimalKHR = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL_KHR, eDepthReadOnlyOptimalKHR = VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL_KHR, eDepthReadOnlyStencilAttachmentOptimalKHR = VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL_KHR, eStencilAttachmentOptimalKHR = VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL_KHR, eStencilReadOnlyOptimalKHR = VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL_KHR }; enum class SharingMode { eExclusive = VK_SHARING_MODE_EXCLUSIVE, eConcurrent = VK_SHARING_MODE_CONCURRENT }; struct ImageCreateInfo { static constexpr VkStructureType structureType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; VkStructureType sType = structureType; const void* pNext = {}; ImageCreateFlags flags = {}; ImageType imageType = ImageType::e2D; Format format = Format::eUndefined; Extent3D extent = {}; uint32_t mipLevels = 1; uint32_t arrayLayers = 1; SampleCountFlagBits samples = SampleCountFlagBits::e1; ImageTiling tiling = ImageTiling::eOptimal; ImageUsageFlags usage = {}; SharingMode sharingMode = SharingMode::eExclusive; uint32_t queueFamilyIndexCount = {}; const uint32_t* pQueueFamilyIndices = {}; ImageLayout initialLayout = ImageLayout::eUndefined; operator VkImageCreateInfo const& () const noexcept { return *reinterpret_cast<const VkImageCreateInfo*>(this); } operator VkImageCreateInfo& () noexcept { return *reinterpret_cast<VkImageCreateInfo*>(this); } bool operator==(ImageCreateInfo const& rhs) const noexcept { return (sType == rhs.sType) && (pNext == rhs.pNext) && (flags == rhs.flags) && (imageType == rhs.imageType) && (format == rhs.format) && (extent == rhs.extent) && (mipLevels == rhs.mipLevels) && (arrayLayers == rhs.arrayLayers) && (samples == rhs.samples) && (tiling == rhs.tiling) && (usage == rhs.usage) && (sharingMode == rhs.sharingMode) && (queueFamilyIndexCount == rhs.queueFamilyIndexCount) && (pQueueFamilyIndices == rhs.pQueueFamilyIndices) && (initialLayout == rhs.initialLayout); } bool operator!=(ImageCreateInfo const& rhs) const noexcept { return !operator==(rhs); } }; static_assert(sizeof(ImageCreateInfo) == sizeof(VkImageCreateInfo), "struct and wrapper have different size!"); static_assert(std::is_standard_layout<ImageCreateInfo>::value, "struct wrapper is not a standard layout!"); enum class ImageViewCreateFlagBits : VkImageViewCreateFlags { eFragmentDensityMapDynamicEXT = VK_IMAGE_VIEW_CREATE_FRAGMENT_DENSITY_MAP_DYNAMIC_BIT_EXT }; enum class ImageViewType { e1D = VK_IMAGE_VIEW_TYPE_1D, e2D = VK_IMAGE_VIEW_TYPE_2D, e3D = VK_IMAGE_VIEW_TYPE_3D, eCube = VK_IMAGE_VIEW_TYPE_CUBE, e1DArray = VK_IMAGE_VIEW_TYPE_1D_ARRAY, e2DArray = VK_IMAGE_VIEW_TYPE_2D_ARRAY, eCubeArray = VK_IMAGE_VIEW_TYPE_CUBE_ARRAY }; using ImageViewCreateFlags = Flags<ImageViewCreateFlagBits>; enum class ComponentSwizzle { eIdentity = VK_COMPONENT_SWIZZLE_IDENTITY, eZero = VK_COMPONENT_SWIZZLE_ZERO, eOne = VK_COMPONENT_SWIZZLE_ONE, eR = VK_COMPONENT_SWIZZLE_R, eG = VK_COMPONENT_SWIZZLE_G, eB = VK_COMPONENT_SWIZZLE_B, eA = VK_COMPONENT_SWIZZLE_A }; struct ComponentMapping { ComponentSwizzle r = ComponentSwizzle::eIdentity; ComponentSwizzle g = ComponentSwizzle::eIdentity; ComponentSwizzle b = ComponentSwizzle::eIdentity; ComponentSwizzle a = ComponentSwizzle::eIdentity; operator VkComponentMapping const& () const noexcept { return *reinterpret_cast<const VkComponentMapping*>(this); } operator VkComponentMapping& () noexcept { return *reinterpret_cast<VkComponentMapping*>(this); } bool operator==(ComponentMapping const& rhs) const noexcept { return (r == rhs.r) && (g == rhs.g) && (b == rhs.b) && (a == rhs.a); } bool operator!=(ComponentMapping const& rhs) const noexcept { return !operator==(rhs); } }; static_assert(sizeof(ComponentMapping) == sizeof(VkComponentMapping), "struct and wrapper have different size!"); static_assert(std::is_standard_layout<ComponentMapping>::value, "struct wrapper is not a standard layout!"); enum class ImageAspectFlagBits : VkImageAspectFlags { eColor = VK_IMAGE_ASPECT_COLOR_BIT, eDepth = VK_IMAGE_ASPECT_DEPTH_BIT, eStencil = VK_IMAGE_ASPECT_STENCIL_BIT, eMetadata = VK_IMAGE_ASPECT_METADATA_BIT, ePlane0 = VK_IMAGE_ASPECT_PLANE_0_BIT, ePlane1 = VK_IMAGE_ASPECT_PLANE_1_BIT, ePlane2 = VK_IMAGE_ASPECT_PLANE_2_BIT, eMemoryPlane0EXT = VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT, eMemoryPlane1EXT = VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT, eMemoryPlane2EXT = VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT, eMemoryPlane3EXT = VK_IMAGE_ASPECT_MEMORY_PLANE_3_BIT_EXT, ePlane0KHR = VK_IMAGE_ASPECT_PLANE_0_BIT_KHR, ePlane1KHR = VK_IMAGE_ASPECT_PLANE_1_BIT_KHR, ePlane2KHR = VK_IMAGE_ASPECT_PLANE_2_BIT_KHR }; using ImageAspectFlags = Flags<ImageAspectFlagBits>; inline constexpr ImageAspectFlags operator|(ImageAspectFlagBits bit0, ImageAspectFlagBits bit1) noexcept { return ImageAspectFlags(bit0) | bit1; } inline constexpr ImageAspectFlags operator&(ImageAspectFlagBits bit0, ImageAspectFlagBits bit1) noexcept { return ImageAspectFlags(bit0) & bit1; } inline constexpr ImageAspectFlags operator^(ImageAspectFlagBits bit0, ImageAspectFlagBits bit1) noexcept { return ImageAspectFlags(bit0) ^ bit1; } struct ImageSubresourceRange { ImageAspectFlags aspectMask = {}; uint32_t baseMipLevel = 0; uint32_t levelCount = 1; uint32_t baseArrayLayer = 0; uint32_t layerCount = 1; operator VkImageSubresourceRange const& () const noexcept { return *reinterpret_cast<const VkImageSubresourceRange*>(this); } operator VkImageSubresourceRange& () noexcept { return *reinterpret_cast<VkImageSubresourceRange*>(this); } bool operator==(ImageSubresourceRange const& rhs) const noexcept { return (aspectMask == rhs.aspectMask) && (baseMipLevel == rhs.baseMipLevel) && (levelCount == rhs.levelCount) && (baseArrayLayer == rhs.baseArrayLayer) && (layerCount == rhs.layerCount); } bool operator!=(ImageSubresourceRange const& rhs) const noexcept { return !operator==(rhs); } }; static_assert(sizeof(ImageSubresourceRange) == sizeof(VkImageSubresourceRange), "struct and wrapper have different size!"); static_assert(std::is_standard_layout<ImageSubresourceRange>::value, "struct wrapper is not a standard layout!"); struct ImageViewCreateInfo { static constexpr VkStructureType structureType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; VkStructureType sType = structureType; const void* pNext = {}; ImageViewCreateFlags flags = {}; Image image = {}; ImageViewType viewType = ImageViewType::e2D; Format format = Format::eUndefined; ComponentMapping components = {}; ImageSubresourceRange subresourceRange = {}; operator VkImageViewCreateInfo const& () const noexcept { return *reinterpret_cast<const VkImageViewCreateInfo*>(this); } operator VkImageViewCreateInfo& () noexcept { return *reinterpret_cast<VkImageViewCreateInfo*>(this); } bool operator==(ImageViewCreateInfo const& rhs) const noexcept { return (sType == rhs.sType) && (pNext == rhs.pNext) && (flags == rhs.flags) && (image == rhs.image) && (viewType == rhs.viewType) && (format == rhs.format) && (components == rhs.components) && (subresourceRange == rhs.subresourceRange); } bool operator!=(ImageViewCreateInfo const& rhs) const noexcept { return !operator==(rhs); } }; static_assert(sizeof(ImageViewCreateInfo) == sizeof(VkImageViewCreateInfo), "struct and wrapper have different size!"); static_assert(std::is_standard_layout<ImageViewCreateInfo>::value, "struct wrapper is not a standard layout!"); struct ImageView { VkImageView payload = VK_NULL_HANDLE; VkImage image; // 64 bits Format format; //32 bits uint32_t id : 29; ImageViewType type : 3; uint32_t base_mip : 4; uint32_t mip_count : 4; uint32_t base_layer : 11; uint32_t layer_count : 11; ComponentMapping components; bool operator==(const ImageView& other) const noexcept { return payload == other.payload; } }; //static_assert(sizeof(ImageView) == 64); template<> class Unique<ImageView> { Context* context; ImageView payload; public: using element_type = ImageView; Unique() : context(nullptr) {} explicit Unique(vuk::Context& ctx, ImageView payload) : context(&ctx), payload(std::move(payload)) {} Unique(Unique const&) = delete; Unique(Unique&& other) noexcept : context(other.context), payload(other.release()) {} ~Unique() noexcept; Unique& operator=(Unique const&) = delete; Unique& operator=(Unique&& other) noexcept { auto tmp = other.context; reset(other.release()); context = tmp; return *this; } explicit operator bool() const noexcept { return payload.payload == VK_NULL_HANDLE; } ImageView const* operator->() const noexcept { return &payload; } ImageView* operator->() noexcept { return &payload; } ImageView const& operator*() const noexcept { return payload; } ImageView& operator*() noexcept { return payload; } const ImageView& get() const noexcept { return payload; } ImageView& get() noexcept { return payload; } void reset(ImageView value = ImageView()) noexcept; ImageView release() noexcept { context = nullptr; return std::move(payload); } void swap(Unique<ImageView>& rhs) noexcept { std::swap(payload, rhs.payload); std::swap(context, rhs.context); } struct SubrangeBuilder { vuk::Context* ctx; vuk::ImageView iv; vuk::ImageViewType type = vuk::ImageViewType(0xdeadbeef); uint32_t base_mip = 0xdeadbeef; // 0xdeadbeef is an out of band value for all uint32_t mip_count = 0xdeadbeef; uint32_t base_layer = 0xdeadbeef; uint32_t layer_count = 0xdeadbeef; SubrangeBuilder& layer_subrange(uint32_t base_layer, uint32_t layer_count) { this->base_layer = base_layer; this->layer_count = layer_count; return *this; } SubrangeBuilder& mip_subrange(uint32_t base_mip, uint32_t mip_count) { this->base_mip = base_mip; this->mip_count = mip_count; return *this; } SubrangeBuilder& view_as(ImageViewType type) { this->type = type; return *this; } Unique<ImageView> apply(); }; // external builder fns SubrangeBuilder layer_subrange(uint32_t base_layer, uint32_t layer_count) { return { .ctx = context, .iv = payload, .base_layer = base_layer, .layer_count = layer_count }; } SubrangeBuilder mip_subrange(uint32_t base_mip, uint32_t mip_count) { return { .ctx = context, .iv = payload, .base_mip = base_mip, .mip_count = mip_count }; } }; enum class SamplerCreateFlagBits : VkSamplerCreateFlags { eSubsampledEXT = VK_SAMPLER_CREATE_SUBSAMPLED_BIT_EXT, eSubsampledCoarseReconstructionEXT = VK_SAMPLER_CREATE_SUBSAMPLED_COARSE_RECONSTRUCTION_BIT_EXT }; using SamplerCreateFlags = Flags<SamplerCreateFlagBits>; enum class Filter { eNearest = VK_FILTER_NEAREST, eLinear = VK_FILTER_LINEAR, eCubicIMG = VK_FILTER_CUBIC_IMG, eCubicEXT = VK_FILTER_CUBIC_EXT }; enum class SamplerMipmapMode { eNearest = VK_SAMPLER_MIPMAP_MODE_NEAREST, eLinear = VK_SAMPLER_MIPMAP_MODE_LINEAR }; enum class SamplerAddressMode { eRepeat = VK_SAMPLER_ADDRESS_MODE_REPEAT, eMirroredRepeat = VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT, eClampToEdge = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, eClampToBorder = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, eMirrorClampToEdge = VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE, eMirrorClampToEdgeKHR = VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE_KHR }; enum class CompareOp { eNever = VK_COMPARE_OP_NEVER, eLess = VK_COMPARE_OP_LESS, eEqual = VK_COMPARE_OP_EQUAL, eLessOrEqual = VK_COMPARE_OP_LESS_OR_EQUAL, eGreater = VK_COMPARE_OP_GREATER, eNotEqual = VK_COMPARE_OP_NOT_EQUAL, eGreaterOrEqual = VK_COMPARE_OP_GREATER_OR_EQUAL, eAlways = VK_COMPARE_OP_ALWAYS }; enum class BorderColor { eFloatTransparentBlack = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK, eIntTransparentBlack = VK_BORDER_COLOR_INT_TRANSPARENT_BLACK, eFloatOpaqueBlack = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK, eIntOpaqueBlack = VK_BORDER_COLOR_INT_OPAQUE_BLACK, eFloatOpaqueWhite = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE, eIntOpaqueWhite = VK_BORDER_COLOR_INT_OPAQUE_WHITE, eFloatCustomEXT = VK_BORDER_COLOR_FLOAT_CUSTOM_EXT, eIntCustomEXT = VK_BORDER_COLOR_INT_CUSTOM_EXT }; struct SamplerCreateInfo { static constexpr VkStructureType structureType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; VkStructureType sType = structureType; const void* pNext = {}; SamplerCreateFlags flags = {}; Filter magFilter = Filter::eNearest; Filter minFilter = Filter::eNearest; SamplerMipmapMode mipmapMode = SamplerMipmapMode::eNearest; SamplerAddressMode addressModeU = SamplerAddressMode::eRepeat; SamplerAddressMode addressModeV = SamplerAddressMode::eRepeat; SamplerAddressMode addressModeW = SamplerAddressMode::eRepeat; float mipLodBias = {}; Bool32 anisotropyEnable = {}; float maxAnisotropy = {}; Bool32 compareEnable = {}; CompareOp compareOp = CompareOp::eNever; float minLod = 0.f; float maxLod = VK_LOD_CLAMP_NONE; BorderColor borderColor = BorderColor::eFloatTransparentBlack; Bool32 unnormalizedCoordinates = {}; operator VkSamplerCreateInfo const& () const noexcept { return *reinterpret_cast<const VkSamplerCreateInfo*>(this); } operator VkSamplerCreateInfo& () noexcept { return *reinterpret_cast<VkSamplerCreateInfo*>(this); } bool operator==(SamplerCreateInfo const& rhs) const noexcept { return (sType == rhs.sType) && (pNext == rhs.pNext) && (flags == rhs.flags) && (magFilter == rhs.magFilter) && (minFilter == rhs.minFilter) && (mipmapMode == rhs.mipmapMode) && (addressModeU == rhs.addressModeU) && (addressModeV == rhs.addressModeV) && (addressModeW == rhs.addressModeW) && (mipLodBias == rhs.mipLodBias) && (anisotropyEnable == rhs.anisotropyEnable) && (maxAnisotropy == rhs.maxAnisotropy) && (compareEnable == rhs.compareEnable) && (compareOp == rhs.compareOp) && (minLod == rhs.minLod) && (maxLod == rhs.maxLod) && (borderColor == rhs.borderColor) && (unnormalizedCoordinates == rhs.unnormalizedCoordinates); } bool operator!=(SamplerCreateInfo const& rhs) const noexcept { return !operator==(rhs); } }; static_assert(sizeof(SamplerCreateInfo) == sizeof(VkSamplerCreateInfo), "struct and wrapper have different size!"); static_assert(std::is_standard_layout<SamplerCreateInfo>::value, "struct wrapper is not a standard layout!"); template<> struct create_info<Sampler> { using type = vuk::SamplerCreateInfo; }; struct Texture { Unique<Image> image; Unique<ImageView> view; Extent3D extent; Format format; Samples sample_count; }; inline vuk::ImageAspectFlags format_to_aspect(vuk::Format format) noexcept { switch (format) { case vuk::Format::eD16Unorm: case vuk::Format::eD32Sfloat: case vuk::Format::eX8D24UnormPack32: return vuk::ImageAspectFlagBits::eDepth; case vuk::Format::eD16UnormS8Uint: case vuk::Format::eD24UnormS8Uint: case vuk::Format::eD32SfloatS8Uint: return vuk::ImageAspectFlagBits::eDepth | vuk::ImageAspectFlagBits::eStencil; case vuk::Format::eS8Uint: return vuk::ImageAspectFlagBits::eStencil; default: return vuk::ImageAspectFlagBits::eColor; } } }; namespace std { template<> struct hash<vuk::ImageView> { size_t operator()(vuk::ImageView const& x) const noexcept { size_t h = 0; hash_combine(h, x.id, reinterpret_cast<uint64_t>(x.payload)); return h; } }; }
34.83277
124
0.772513
zacharycarter
a8e2677a71bad7cf97c3dcd5ab12238ebcdaf3ab
33,487
cc
C++
zircon/system/ulib/paver/paver.cc
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
zircon/system/ulib/paver/paver.cc
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
zircon/system/ulib/paver/paver.cc
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "paver.h" #include <dirent.h> #include <fcntl.h> #include <lib/fdio/directory.h> #include <lib/fidl-async/cpp/bind.h> #include <lib/fidl/epitaph.h> #include <lib/fzl/vmo-mapper.h> #include <lib/zx/channel.h> #include <lib/zx/time.h> #include <lib/zx/vmo.h> #include <libgen.h> #include <stddef.h> #include <string.h> #include <zircon/device/block.h> #include <zircon/errors.h> #include <zircon/status.h> #include <zircon/syscalls.h> #include <memory> #include <utility> #include <fbl/algorithm.h> #include <fbl/alloc_checker.h> #include <fbl/span.h> #include <fbl/auto_call.h> #include <fbl/unique_fd.h> #include <fs-management/fvm.h> #include <fs-management/mount.h> #include <zxcrypt/fdio-volume.h> #include "fvm.h" #include "pave-logging.h" #include "stream-reader.h" #include "vmo-reader.h" #define ZXCRYPT_DRIVER_LIB "/boot/driver/zxcrypt.so" namespace paver { namespace { using ::llcpp::fuchsia::paver::Asset; using ::llcpp::fuchsia::paver::Configuration; // Get the architecture of the currently running platform. inline constexpr Arch GetCurrentArch() { #if defined(__x86_64__) return Arch::kX64; #elif defined(__aarch64__) return Arch::kArm64; #else #error "Unknown arch" #endif } Partition PartitionType(Configuration configuration, Asset asset) { switch (asset) { case Asset::KERNEL: { switch (configuration) { case Configuration::A: return Partition::kZirconA; case Configuration::B: return Partition::kZirconB; case Configuration::RECOVERY: return Partition::kZirconR; }; break; } case Asset::VERIFIED_BOOT_METADATA: { switch (configuration) { case Configuration::A: return Partition::kVbMetaA; case Configuration::B: return Partition::kVbMetaB; case Configuration::RECOVERY: return Partition::kVbMetaR; }; break; } }; return Partition::kUnknown; } // Best effort attempt to see if payload contents match what is already inside // of the partition. bool CheckIfSame(PartitionClient* partition, const zx::vmo& vmo, size_t payload_size, size_t block_size) { const size_t payload_size_aligned = fbl::round_up(payload_size, block_size); zx::vmo read_vmo; auto status = zx::vmo::create(fbl::round_up(payload_size_aligned, ZX_PAGE_SIZE), 0, &read_vmo); if (status != ZX_OK) { ERROR("Failed to create VMO: %s\n", zx_status_get_string(status)); return false; } if ((status = partition->Read(read_vmo, payload_size_aligned)) != ZX_OK) { return false; } fzl::VmoMapper first_mapper; fzl::VmoMapper second_mapper; status = first_mapper.Map(vmo, 0, 0, ZX_VM_PERM_READ); if (status != ZX_OK) { ERROR("Error mapping vmo: %s\n", zx_status_get_string(status)); return false; } status = second_mapper.Map(read_vmo, 0, 0, ZX_VM_PERM_READ); if (status != ZX_OK) { ERROR("Error mapping vmo: %s\n", zx_status_get_string(status)); return false; } return memcmp(first_mapper.start(), second_mapper.start(), payload_size) == 0; } #if 0 // Checks first few bytes of buffer to ensure it is a ZBI. // Also validates architecture in kernel header matches the target. bool ValidateKernelZbi(const uint8_t* buffer, size_t size, Arch arch) { const auto payload = reinterpret_cast<const zircon_kernel_t*>(buffer); const uint32_t expected_kernel = (arch == Arch::X64) ? ZBI_TYPE_KERNEL_X64 : ZBI_TYPE_KERNEL_ARM64; const auto crc_valid = [](const zbi_header_t* hdr) { const uint32_t crc = crc32(0, reinterpret_cast<const uint8_t*>(hdr + 1), hdr->length); return hdr->crc32 == crc; }; return size >= sizeof(zircon_kernel_t) && // Container header payload->hdr_file.type == ZBI_TYPE_CONTAINER && payload->hdr_file.extra == ZBI_CONTAINER_MAGIC && (payload->hdr_file.length - offsetof(zircon_kernel_t, hdr_kernel)) <= size && payload->hdr_file.magic == ZBI_ITEM_MAGIC && payload->hdr_file.flags == ZBI_FLAG_VERSION && payload->hdr_file.crc32 == ZBI_ITEM_NO_CRC32 && // Kernel header payload->hdr_kernel.type == expected_kernel && (payload->hdr_kernel.length - offsetof(zircon_kernel_t, data_kernel)) <= size && payload->hdr_kernel.magic == ZBI_ITEM_MAGIC && (payload->hdr_kernel.flags & ZBI_FLAG_VERSION) == ZBI_FLAG_VERSION && ((payload->hdr_kernel.flags & ZBI_FLAG_CRC32) ? crc_valid(&payload->hdr_kernel) : payload->hdr_kernel.crc32 == ZBI_ITEM_NO_CRC32); } // Parses a partition and validates that it matches the expected format. zx_status_t ValidateKernelPayload(const fzl::ResizeableVmoMapper& mapper, size_t vmo_size, Partition partition_type, Arch arch) { // TODO(surajmalhotra): Re-enable this as soon as we have a good way to // determine whether the payload is signed or not. (Might require bootserver // changes). if (false) { const auto* buffer = reinterpret_cast<uint8_t*>(mapper.start()); switch (partition_type) { case Partition::kZirconA: case Partition::kZirconB: case Partition::kZirconR: if (!ValidateKernelZbi(buffer, vmo_size, arch)) { ERROR("Invalid ZBI payload!"); return ZX_ERR_BAD_STATE; } break; default: // TODO(surajmalhotra): Validate non-zbi payloads as well. LOG("Skipping validation as payload is not a ZBI\n"); break; } } return ZX_OK; } #endif // Returns a client for the FVM partition. If the FVM volume doesn't exist, a new // volume will be created, without any associated children partitions. zx_status_t GetFvmPartition(const DevicePartitioner& partitioner, std::unique_ptr<PartitionClient>* client) { constexpr Partition partition = Partition::kFuchsiaVolumeManager; zx_status_t status = partitioner.FindPartition(partition, client); if (status != ZX_OK) { if (status != ZX_ERR_NOT_FOUND) { ERROR("Failure looking for FVM partition: %s\n", zx_status_get_string(status)); return status; } LOG("Could not find FVM Partition on device. Attemping to add new partition\n"); if ((status = partitioner.AddPartition(partition, client)) != ZX_OK) { ERROR("Failure creating FVM partition: %s\n", zx_status_get_string(status)); return status; } } else { LOG("FVM Partition already exists\n"); } return ZX_OK; } zx_status_t FvmPave(const fbl::unique_fd& devfs_root, const DevicePartitioner& partitioner, std::unique_ptr<fvm::ReaderInterface> payload) { LOG("Paving FVM partition.\n"); std::unique_ptr<PartitionClient> partition; zx_status_t status = GetFvmPartition(partitioner, &partition); if (status != ZX_OK) { return status; } if (partitioner.IsFvmWithinFtl()) { LOG("Attempting to format FTL...\n"); status = partitioner.WipeFvm(); if (status != ZX_OK) { ERROR("Failed to format FTL: %s\n", zx_status_get_string(status)); } else { LOG("Formatted partition successfully!\n"); } } LOG("Streaming partitions to FVM...\n"); status = FvmStreamPartitions(devfs_root, std::move(partition), std::move(payload)); if (status != ZX_OK) { ERROR("Failed to stream partitions to FVM: %s\n", zx_status_get_string(status)); return status; } LOG("Completed FVM paving successfully\n"); return ZX_OK; } // Formats the FVM partition and returns a channel to the new volume. zx_status_t FormatFvm(const fbl::unique_fd& devfs_root, const DevicePartitioner& partitioner, zx::channel* channel) { std::unique_ptr<PartitionClient> partition; zx_status_t status = GetFvmPartition(partitioner, &partition); if (status != ZX_OK) { return status; } // TODO(39753): Configuration values should come from the build or environment. fvm::sparse_image_t header = {}; header.slice_size = 1 << 20; fbl::unique_fd fvm_fd( FvmPartitionFormat(devfs_root, partition->block_fd(), header, BindOption::Reformat)); if (!fvm_fd) { ERROR("Couldn't format FVM partition\n"); return ZX_ERR_IO; } status = AllocateEmptyPartitions(devfs_root, fvm_fd); if (status != ZX_OK) { ERROR("Couldn't allocate empty partitions\n"); return status; } status = fdio_get_service_handle(fvm_fd.release(), channel->reset_and_get_address()); if (status != ZX_OK) { ERROR("Couldn't get fvm handle\n"); return ZX_ERR_IO; } return ZX_OK; } // Reads an image from disk into a vmo. zx_status_t PartitionRead(const DevicePartitioner& partitioner, Partition partition_type, zx::vmo* out_vmo, size_t* out_vmo_size) { LOG("Reading partition \"%s\".\n", PartitionName(partition_type)); std::unique_ptr<PartitionClient> partition; if (zx_status_t status = partitioner.FindPartition(partition_type, &partition); status != ZX_OK) { ERROR("Could not find \"%s\" Partition on device: %s\n", PartitionName(partition_type), zx_status_get_string(status)); return status; } uint64_t partition_size; if (zx_status_t status = partition->GetPartitionSize(&partition_size); status != ZX_OK) { ERROR("Error getting partition \"%s\" size: %s\n", PartitionName(partition_type), zx_status_get_string(status)); return status; } zx::vmo vmo; if (zx_status_t status = zx::vmo::create(fbl::round_up(partition_size, ZX_PAGE_SIZE), 0, &vmo); status != ZX_OK) { ERROR("Error creating vmo for \"%s\": %s\n", PartitionName(partition_type), zx_status_get_string(status)); return status; } if (zx_status_t status = partition->Read(vmo, static_cast<size_t>(partition_size)); status != ZX_OK) { ERROR("Error writing partition data for \"%s\": %s\n", PartitionName(partition_type), zx_status_get_string(status)); return status; } *out_vmo = std::move(vmo); *out_vmo_size = static_cast<size_t>(partition_size); LOG("Completed successfully\n"); return ZX_OK; } zx_status_t ValidatePartitionPayload(const DevicePartitioner& partitioner, const zx::vmo& payload_vmo, size_t payload_size, Partition partition_type) { fzl::VmoMapper payload_mapper; zx_status_t status = payload_mapper.Map(payload_vmo, 0, 0, ZX_VM_PERM_READ); if (status != ZX_OK) { ERROR("Could not map payload into memory: %s\n", zx_status_get_string(status)); return status; } ZX_ASSERT(payload_mapper.size() >= payload_size); auto payload = fbl::Span<const uint8_t>(static_cast<const uint8_t*>(payload_mapper.start()), payload_size); return partitioner.ValidatePayload(partition_type, payload); } // Paves an image onto the disk. zx_status_t PartitionPave(const DevicePartitioner& partitioner, zx::vmo payload_vmo, size_t payload_size, Partition partition_type) { LOG("Paving partition \"%s\".\n", PartitionName(partition_type)); // Perform basic safety checking on the partition before we attempt to write it. zx_status_t status = ValidatePartitionPayload(partitioner, payload_vmo, payload_size, partition_type); if (status != ZX_OK) { ERROR("Failed to validate partition \"%s\": %s\n", PartitionName(partition_type), zx_status_get_string(status)); return status; } // Find or create the appropriate partition. std::unique_ptr<PartitionClient> partition; if ((status = partitioner.FindPartition(partition_type, &partition)) != ZX_OK) { if (status != ZX_ERR_NOT_FOUND) { ERROR("Failure looking for partition \"%s\": %s\n", PartitionName(partition_type), zx_status_get_string(status)); return status; } LOG("Could not find \"%s\" Partition on device. Attemping to add new partition\n", PartitionName(partition_type)); if ((status = partitioner.AddPartition(partition_type, &partition)) != ZX_OK) { ERROR("Failure creating partition \"%s\": %s\n", PartitionName(partition_type), zx_status_get_string(status)); return status; } } else { LOG("Partition \"%s\" already exists\n", PartitionName(partition_type)); } size_t block_size_bytes; if ((status = partition->GetBlockSize(&block_size_bytes)) != ZX_OK) { ERROR("Couldn't get partition \"%s\" block size\n", PartitionName(partition_type)); return status; } if (CheckIfSame(partition.get(), payload_vmo, payload_size, block_size_bytes)) { LOG("Skipping write as partition \"%s\" contents match payload.\n", PartitionName(partition_type)); } else { // Pad payload with 0s to make it block size aligned. if (payload_size % block_size_bytes != 0) { const size_t remaining_bytes = block_size_bytes - (payload_size % block_size_bytes); size_t vmo_size; if ((status = payload_vmo.get_size(&vmo_size)) != ZX_OK) { ERROR("Couldn't get vmo size for \"%s\"\n", PartitionName(partition_type)); return status; } // Grow VMO if it's too small. if (vmo_size < payload_size + remaining_bytes) { const auto new_size = fbl::round_up(payload_size + remaining_bytes, ZX_PAGE_SIZE); status = payload_vmo.set_size(new_size); if (status != ZX_OK) { ERROR("Couldn't grow vmo for \"%s\"\n", PartitionName(partition_type)); return status; } } auto buffer = std::make_unique<uint8_t[]>(remaining_bytes); memset(buffer.get(), 0, remaining_bytes); status = payload_vmo.write(buffer.get(), payload_size, remaining_bytes); if (status != ZX_OK) { ERROR("Failed to write padding to vmo for \"%s\"\n", PartitionName(partition_type)); return status; } payload_size += remaining_bytes; } if ((status = partition->Write(payload_vmo, payload_size)) != ZX_OK) { ERROR("Error writing partition \"%s\" data: %s\n", PartitionName(partition_type), zx_status_get_string(status)); return status; } } if ((status = partitioner.FinalizePartition(partition_type)) != ZX_OK) { ERROR("Failed to finalize partition \"%s\"\n", PartitionName(partition_type)); return status; } LOG("Completed paving partition \"%s\" successfully\n", PartitionName(partition_type)); return ZX_OK; } zx::channel OpenServiceRoot() { zx::channel request, service_root; if (zx::channel::create(0, &request, &service_root) != ZX_OK) { return zx::channel(); } if (fdio_service_connect("/svc/.", request.release()) != ZX_OK) { return zx::channel(); } return service_root; } bool IsBootable(const abr::SlotData& slot) { return slot.priority > 0 && (slot.tries_remaining > 0 || slot.successful_boot); } std::optional<Configuration> GetActiveConfiguration(const abr::Client& abr_client) { const bool config_a_bootable = IsBootable(abr_client.Data().slots[0]); const bool config_b_bootable = IsBootable(abr_client.Data().slots[1]); const uint8_t config_a_priority = abr_client.Data().slots[0].priority; const uint8_t config_b_priority = abr_client.Data().slots[1].priority; // A wins on ties. if (config_a_bootable && (config_a_priority >= config_b_priority || !config_b_bootable)) { return Configuration::A; } else if (config_b_bootable) { return Configuration::B; } else { return std::nullopt; } } } // namespace void Paver::FindDataSink(zx::channel data_sink, FindDataSinkCompleter::Sync _completer) { // Use global devfs if one wasn't injected via set_devfs_root. if (!devfs_root_) { devfs_root_ = fbl::unique_fd(open("/dev", O_RDONLY)); } if (!svc_root_) { svc_root_ = OpenServiceRoot(); } DataSink::Bind(dispatcher_, devfs_root_.duplicate(), std::move(svc_root_), std::move(data_sink)); } void Paver::UseBlockDevice(zx::channel block_device, zx::channel dynamic_data_sink, UseBlockDeviceCompleter::Sync _completer) { // Use global devfs if one wasn't injected via set_devfs_root. if (!devfs_root_) { devfs_root_ = fbl::unique_fd(open("/dev", O_RDONLY)); } if (!svc_root_) { svc_root_ = OpenServiceRoot(); } DynamicDataSink::Bind(dispatcher_, devfs_root_.duplicate(), std::move(svc_root_), std::move(block_device), std::move(dynamic_data_sink)); } void Paver::FindBootManager(zx::channel boot_manager, bool initialize, FindBootManagerCompleter::Sync _completer) { // Use global devfs if one wasn't injected via set_devfs_root. if (!devfs_root_) { devfs_root_ = fbl::unique_fd(open("/dev", O_RDONLY)); } if (!svc_root_) { svc_root_ = OpenServiceRoot(); } BootManager::Bind(dispatcher_, devfs_root_.duplicate(), std::move(svc_root_), std::move(boot_manager), initialize); } void DataSink::ReadAsset(::llcpp::fuchsia::paver::Configuration configuration, ::llcpp::fuchsia::paver::Asset asset, ReadAssetCompleter::Sync completer) { ::llcpp::fuchsia::mem::Buffer buf; zx_status_t status = sink_.ReadAsset(configuration, asset, &buf); if (status == ZX_OK) { completer.ReplySuccess(std::move(buf)); } else { completer.ReplyError(status); } } void DataSink::WipeVolume(WipeVolumeCompleter::Sync completer) { zx::channel out; zx_status_t status = sink_.WipeVolume(&out); if (status == ZX_OK) { completer.ReplySuccess(std::move(out)); } else { completer.ReplyError(status); } } zx_status_t DataSinkImpl::ReadAsset(Configuration configuration, Asset asset, ::llcpp::fuchsia::mem::Buffer* buf) { return PartitionRead(*partitioner_, PartitionType(configuration, asset), &buf->vmo, &buf->size); } zx_status_t DataSinkImpl::WriteAsset(Configuration configuration, Asset asset, ::llcpp::fuchsia::mem::Buffer payload) { return PartitionPave(*partitioner_, std::move(payload.vmo), payload.size, PartitionType(configuration, asset)); } zx_status_t DataSinkImpl::WriteVolumes(zx::channel payload_stream) { std::unique_ptr<StreamReader> reader; zx_status_t status = StreamReader::Create(std::move(payload_stream), &reader); if (status != ZX_OK) { ERROR("Unable to create stream.\n"); return status; } return FvmPave(devfs_root_, *partitioner_, std::move(reader)); } zx_status_t DataSinkImpl::WriteBootloader(::llcpp::fuchsia::mem::Buffer payload) { return PartitionPave(*partitioner_, std::move(payload.vmo), payload.size, Partition::kBootloader); } zx_status_t DataSinkImpl::WriteDataFile(fidl::StringView filename, ::llcpp::fuchsia::mem::Buffer payload) { const char* mount_path = "/volume/data"; const uint8_t data_guid[] = GUID_DATA_VALUE; char minfs_path[PATH_MAX] = {0}; char path[PATH_MAX] = {0}; zx_status_t status = ZX_OK; fbl::unique_fd part_fd( open_partition_with_devfs(devfs_root_.get(), nullptr, data_guid, ZX_SEC(1), path)); if (!part_fd) { ERROR("DATA partition not found in FVM\n"); return ZX_ERR_NOT_FOUND; } auto disk_format = detect_disk_format(part_fd.get()); fbl::unique_fd mountpoint_dev_fd; // By the end of this switch statement, mountpoint_dev_fd needs to be an // open handle to the block device that we want to mount at mount_path. switch (disk_format) { case DISK_FORMAT_MINFS: // If the disk we found is actually minfs, we can just use the block // device path we were given by open_partition. strncpy(minfs_path, path, PATH_MAX); mountpoint_dev_fd.reset(open(minfs_path, O_RDWR)); break; case DISK_FORMAT_ZXCRYPT: { std::unique_ptr<zxcrypt::FdioVolume> zxc_volume; uint8_t slot = 0; if ((status = zxcrypt::FdioVolume::UnlockWithDeviceKey( std::move(part_fd), devfs_root_.duplicate(), static_cast<zxcrypt::key_slot_t>(slot), &zxc_volume)) != ZX_OK) { ERROR("Couldn't unlock zxcrypt volume: %s\n", zx_status_get_string(status)); return status; } // Most of the time we'll expect the volume to actually already be // unsealed, because we created it and unsealed it moments ago to // format minfs. if ((status = zxc_volume->Open(zx::sec(0), &mountpoint_dev_fd)) == ZX_OK) { // Already unsealed, great, early exit. break; } // Ensure zxcrypt volume manager is bound. zx::channel zxc_manager_chan; if ((status = zxc_volume->OpenManager(zx::sec(5), zxc_manager_chan.reset_and_get_address())) != ZX_OK) { ERROR("Couldn't open zxcrypt volume manager: %s\n", zx_status_get_string(status)); return status; } // Unseal. zxcrypt::FdioVolumeManager zxc_manager(std::move(zxc_manager_chan)); if ((status = zxc_manager.UnsealWithDeviceKey(slot)) != ZX_OK) { ERROR("Couldn't unseal zxcrypt volume: %s\n", zx_status_get_string(status)); return status; } // Wait for the device to appear, and open it. if ((status = zxc_volume->Open(zx::sec(5), &mountpoint_dev_fd)) != ZX_OK) { ERROR("Couldn't open block device atop unsealed zxcrypt volume: %s\n", zx_status_get_string(status)); return status; } } break; default: ERROR("unsupported disk format at %s\n", path); return ZX_ERR_NOT_SUPPORTED; } mount_options_t opts(default_mount_options); opts.create_mountpoint = true; if ((status = mount(mountpoint_dev_fd.get(), mount_path, DISK_FORMAT_MINFS, &opts, launch_logs_async)) != ZX_OK) { ERROR("mount error: %s\n", zx_status_get_string(status)); return status; } int filename_size = static_cast<int>(filename.size()); // mkdir any intermediate directories between mount_path and basename(filename). snprintf(path, sizeof(path), "%s/%.*s", mount_path, filename_size, filename.data()); size_t cur = strlen(mount_path); size_t max = strlen(path) - strlen(basename(path)); // note: the call to basename above modifies path, so it needs reconstruction. snprintf(path, sizeof(path), "%s/%.*s", mount_path, filename_size, filename.data()); while (cur < max) { ++cur; if (path[cur] == '/') { path[cur] = 0; // errors ignored, let the open() handle that later. mkdir(path, 0700); path[cur] = '/'; } } // We append here, because the primary use case here is to send SSH keys // which can be appended, but we may want to revisit this choice for other // files in the future. { uint8_t buf[8192]; fbl::unique_fd kfd(open(path, O_CREAT | O_WRONLY | O_APPEND, 0600)); if (!kfd) { umount(mount_path); ERROR("open %.*s error: %s\n", filename_size, filename.data(), strerror(errno)); return ZX_ERR_IO; } VmoReader reader(std::move(payload)); size_t actual; while ((status = reader.Read(buf, sizeof(buf), &actual)) == ZX_OK && actual > 0) { if (write(kfd.get(), buf, actual) != static_cast<ssize_t>(actual)) { umount(mount_path); ERROR("write %.*s error: %s\n", filename_size, filename.data(), strerror(errno)); return ZX_ERR_IO; } } fsync(kfd.get()); } if ((status = umount(mount_path)) != ZX_OK) { ERROR("unmount %s failed: %s\n", mount_path, zx_status_get_string(status)); return status; } LOG("Wrote %.*s\n", filename_size, filename.data()); return ZX_OK; } zx_status_t DataSinkImpl::WipeVolume(zx::channel* out) { std::unique_ptr<PartitionClient> partition; zx_status_t status = GetFvmPartition(*partitioner_, &partition); if (status != ZX_OK) { return status; } // Bind the FVM driver to be in a well known state regarding races with block watcher. // The block watcher will attempt to bind the FVM driver automatically based on // the contents of the partition. However, that operation is not synchronized in // any way with this service so the driver can be loaded at any time. // WipeFvm basically writes underneath that driver, which means that we should // eliminate the races at this point: assuming that the driver can load, either // this call or the block watcher will succeed (and the other one will fail), // but the driver will be loaded before moving on. TryBindToFvmDriver(devfs_root_, partition->block_fd(), zx::sec(3)); status = partitioner_->WipeFvm(); if (status != ZX_OK) { ERROR("Failure wiping partition: %s\n", zx_status_get_string(status)); return status; } zx::channel channel; status = FormatFvm(devfs_root_, *partitioner_, &channel); if (status != ZX_OK) { ERROR("Failure formatting partition: %s\n", zx_status_get_string(status)); return status; } *out = std::move(channel); return ZX_OK; } void DataSink::Bind(async_dispatcher_t* dispatcher, fbl::unique_fd devfs_root, zx::channel svc_root, zx::channel server) { auto partitioner = DevicePartitioner::Create(devfs_root.duplicate(), std::move(svc_root), GetCurrentArch()); if (!partitioner) { ERROR("Unable to initialize a partitioner.\n"); fidl_epitaph_write(server.get(), ZX_ERR_BAD_STATE); return; } auto data_sink = std::make_unique<DataSink>(std::move(devfs_root), std::move(partitioner)); fidl::Bind(dispatcher, std::move(server), std::move(data_sink)); } void DynamicDataSink::Bind(async_dispatcher_t* dispatcher, fbl::unique_fd devfs_root, zx::channel svc_root, zx::channel block_device, zx::channel server) { auto partitioner = DevicePartitioner::Create(devfs_root.duplicate(), std::move(svc_root), GetCurrentArch(), std::move(block_device)); if (!partitioner) { ERROR("Unable to initialize a partitioner.\n"); fidl_epitaph_write(server.get(), ZX_ERR_BAD_STATE); return; } auto data_sink = std::make_unique<DynamicDataSink>(std::move(devfs_root), std::move(partitioner)); fidl::Bind(dispatcher, std::move(server), std::move(data_sink)); } void DynamicDataSink::InitializePartitionTables( InitializePartitionTablesCompleter::Sync completer) { completer.Reply(sink_.partitioner()->InitPartitionTables()); } void DynamicDataSink::WipePartitionTables(WipePartitionTablesCompleter::Sync completer) { completer.Reply(sink_.partitioner()->WipePartitionTables()); } void DynamicDataSink::ReadAsset(::llcpp::fuchsia::paver::Configuration configuration, ::llcpp::fuchsia::paver::Asset asset, ReadAssetCompleter::Sync completer) { ::llcpp::fuchsia::mem::Buffer buf; auto status = sink_.ReadAsset(configuration, asset, &buf); if (status == ZX_OK) { completer.ReplySuccess(std::move(buf)); } else { completer.ReplyError(status); } } void DynamicDataSink::WipeVolume(WipeVolumeCompleter::Sync completer) { zx::channel out; zx_status_t status = sink_.WipeVolume(&out); if (status == ZX_OK) { completer.ReplySuccess(std::move(out)); } else { completer.ReplyError(status); } } void BootManager::Bind(async_dispatcher_t* dispatcher, fbl::unique_fd devfs_root, zx::channel svc_root, zx::channel server, bool initialize) { std::unique_ptr<abr::Client> abr_client; if (zx_status_t status = abr::Client::Create(std::move(devfs_root), std::move(svc_root), &abr_client); status != ZX_OK) { ERROR("Failed to get ABR client: %s\n", zx_status_get_string(status)); fidl_epitaph_write(server.get(), status); return; } const bool valid = abr_client->IsValid(); if (!valid && initialize) { abr::Data data = abr_client->Data(); memset(&data, 0, sizeof(data)); memcpy(data.magic, abr::kMagic, sizeof(abr::kMagic)); data.version_major = abr::kMajorVersion; data.version_minor = abr::kMinorVersion; if (zx_status_t status = abr_client->Persist(data); status != ZX_OK) { ERROR("Unabled to persist ABR metadata %s\n", zx_status_get_string(status)); fidl_epitaph_write(server.get(), status); return; } ZX_DEBUG_ASSERT(abr_client->IsValid()); } else if (!valid) { ERROR("ABR metadata is not valid!\n"); fidl_epitaph_write(server.get(), ZX_ERR_NOT_SUPPORTED); return; } auto boot_manager = std::make_unique<BootManager>(std::move(abr_client)); fidl::Bind(dispatcher, std::move(server), std::move(boot_manager)); } void BootManager::QueryActiveConfiguration(QueryActiveConfigurationCompleter::Sync completer) { std::optional<Configuration> config = GetActiveConfiguration(*abr_client_); if (!config) { completer.ReplyError(ZX_ERR_NOT_SUPPORTED); return; } completer.ReplySuccess(config.value()); } void BootManager::QueryConfigurationStatus(Configuration configuration, QueryConfigurationStatusCompleter::Sync completer) { const abr::SlotData* slot; switch (configuration) { case Configuration::A: slot = &abr_client_->Data().slots[0]; break; case Configuration::B: slot = &abr_client_->Data().slots[1]; break; default: ERROR("Unexpected configuration: %d\n", static_cast<uint32_t>(configuration)); completer.ReplyError(ZX_ERR_INVALID_ARGS); return; } if (!IsBootable(*slot)) { completer.ReplySuccess(::llcpp::fuchsia::paver::ConfigurationStatus::UNBOOTABLE); } else if (slot->successful_boot == 0) { completer.ReplySuccess(::llcpp::fuchsia::paver::ConfigurationStatus::PENDING); } else { completer.ReplySuccess(::llcpp::fuchsia::paver::ConfigurationStatus::HEALTHY); } } void BootManager::SetConfigurationActive(Configuration configuration, SetConfigurationActiveCompleter::Sync completer) { LOG("Setting configuration %d as active\n", static_cast<uint32_t>(configuration)); abr::Data data = abr_client_->Data(); abr::SlotData *primary, *secondary; switch (configuration) { case Configuration::A: primary = &data.slots[0]; secondary = &data.slots[1]; break; case Configuration::B: primary = &data.slots[1]; secondary = &data.slots[0]; break; default: ERROR("Unexpected configuration: %d\n", static_cast<uint32_t>(configuration)); completer.Reply(ZX_ERR_INVALID_ARGS); return; } if (secondary->priority >= abr::kMaxPriority) { // 0 means unbootable, so we reset down to 1 to indicate lowest priority. secondary->priority = 1; } primary->successful_boot = 0; primary->tries_remaining = abr::kMaxTriesRemaining; primary->priority = static_cast<uint8_t>(secondary->priority + 1); if (zx_status_t status = abr_client_->Persist(data); status != ZX_OK) { ERROR("Unabled to persist ABR metadata %s\n", zx_status_get_string(status)); completer.Reply(status); return; } LOG("Set active configuration to %d\n", static_cast<uint32_t>(configuration)); completer.Reply(ZX_OK); } void BootManager::SetConfigurationUnbootable(Configuration configuration, SetConfigurationUnbootableCompleter::Sync completer) { LOG("Setting configuration %d as unbootable\n", static_cast<uint32_t>(configuration)); auto data = abr_client_->Data(); abr::SlotData* slot; switch (configuration) { case Configuration::A: slot = &data.slots[0]; break; case Configuration::B: slot = &data.slots[1]; break; default: ERROR("Unexpected configuration: %d\n", static_cast<uint32_t>(configuration)); completer.Reply(ZX_ERR_INVALID_ARGS); return; } slot->successful_boot = 0; slot->tries_remaining = 0; slot->priority = 0; if (zx_status_t status = abr_client_->Persist(data); status != ZX_OK) { ERROR("Unabled to persist ABR metadata %s\n", zx_status_get_string(status)); completer.Reply(status); return; } LOG("Set %d configuration as unbootable\n", static_cast<uint32_t>(configuration)); completer.Reply(ZX_OK); } void BootManager::SetActiveConfigurationHealthy( SetActiveConfigurationHealthyCompleter::Sync completer) { LOG("Setting active configuration as healthy\n"); abr::Data data = abr_client_->Data(); std::optional<Configuration> config = GetActiveConfiguration(*abr_client_); if (!config) { ERROR("No configuration bootable. Cannot mark as successful boot.\n"); completer.Reply(ZX_ERR_BAD_STATE); return; } abr::SlotData* slot; switch (*config) { case Configuration::A: slot = &data.slots[0]; break; case Configuration::B: slot = &data.slots[1]; break; default: // We've previously validated active is A or B. ZX_ASSERT(false); } slot->tries_remaining = 0; slot->successful_boot = 1; if (zx_status_t status = abr_client_->Persist(data); status != ZX_OK) { ERROR("Unabled to persist ABR metadata %s\n", zx_status_get_string(status)); completer.Reply(status); return; } LOG("Set active configuration as healthy\n"); completer.Reply(ZX_OK); } } // namespace paver
35.776709
100
0.672858
sysidos
a8e89b3a2181f913f0b8d6d9fb35d04715d32ed0
1,447
cxx
C++
src/mlio/data_type.cxx
rizwangilani/ml-io
d9572227281168139c4e99d79a6d2ebc83323a61
[ "Apache-2.0" ]
null
null
null
src/mlio/data_type.cxx
rizwangilani/ml-io
d9572227281168139c4e99d79a6d2ebc83323a61
[ "Apache-2.0" ]
2
2020-04-08T01:37:44.000Z
2020-04-14T20:14:07.000Z
src/mlio/data_type.cxx
rizwangilani/ml-io
d9572227281168139c4e99d79a6d2ebc83323a61
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You * may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ #include "mlio/data_type.h" #include "mlio/parser.h" #include "mlio/util/number.h" namespace mlio { inline namespace v1 { data_type infer_data_type(std::string_view s) noexcept { if (s.empty()) { return data_type::string; } std::int64_t sint64_val{}; parse_result r = try_parse_int<std::int64_t>(s, sint64_val); if (r == parse_result::ok) { return data_type::sint64; } if (r == parse_result::overflowed) { std::uint64_t uint64_val{}; r = try_parse_int<std::uint64_t>(s, uint64_val); if (r == parse_result::ok) { return data_type::uint64; } } double double_val{}; r = try_parse_float<double>(s, double_val); if (r == parse_result::ok) { return data_type::float64; } return data_type::string; } } // namespace v1 } // namespace mlio
25.839286
74
0.656531
rizwangilani
a8efb1646c1d2d5bf11a8a4516d5fbe95fc08062
445
cpp
C++
wliotproxy-src-base/libVDIL/src/core/StopBlock.cpp
ooolms/wl_iot_framework
77f5d577105d505fd1c5a21940f29b72eb3391ea
[ "Apache-2.0" ]
null
null
null
wliotproxy-src-base/libVDIL/src/core/StopBlock.cpp
ooolms/wl_iot_framework
77f5d577105d505fd1c5a21940f29b72eb3391ea
[ "Apache-2.0" ]
null
null
null
wliotproxy-src-base/libVDIL/src/core/StopBlock.cpp
ooolms/wl_iot_framework
77f5d577105d505fd1c5a21940f29b72eb3391ea
[ "Apache-2.0" ]
null
null
null
#include "VDIL/core/StopBlock.h" #include "VDIL/core/Program.h" using namespace WLIOTVDIL; const QString StopBlock::mBlockName="stop"; StopBlock::StopBlock(quint32 blockId) :BaseBlock(blockId) { } QString StopBlock::groupName()const { return Program::reservedCoreGroupName; } QString StopBlock::blockName()const { return mBlockName; } void StopBlock::evalInternal() { if(engineCallbacks()) engineCallbacks()->programStopRequest(); }
15.892857
43
0.761798
ooolms
a8f1206a684e311f8692318e04eeeb0f28c73f4a
173
hpp
C++
src/intersim/booksim_config.hpp
beneslami/Multi-GPU
89101177a29a0f238fa85671943f2f584e82a815
[ "Apache-2.0" ]
null
null
null
src/intersim/booksim_config.hpp
beneslami/Multi-GPU
89101177a29a0f238fa85671943f2f584e82a815
[ "Apache-2.0" ]
null
null
null
src/intersim/booksim_config.hpp
beneslami/Multi-GPU
89101177a29a0f238fa85671943f2f584e82a815
[ "Apache-2.0" ]
null
null
null
#ifndef _BOOKSIM_CONFIG_HPP_ #define _BOOKSIM_CONFIG_HPP_ #include "config_utils.hpp" class BookSimConfig : public Configuration { public: BookSimConfig( ); }; #endif
14.416667
44
0.780347
beneslami
a8f1450e8d56be831e3c0b8fa3c744f83dd959c6
24,470
cpp
C++
nGenEx/Window.cpp
RogerioY/starshatter-open
3a507e08b1d4e5970b27401a7e6517570d529400
[ "BSD-3-Clause" ]
null
null
null
nGenEx/Window.cpp
RogerioY/starshatter-open
3a507e08b1d4e5970b27401a7e6517570d529400
[ "BSD-3-Clause" ]
4
2019-09-05T22:22:57.000Z
2021-03-28T02:09:24.000Z
nGenEx/Window.cpp
RogerioY/starshatter-open
3a507e08b1d4e5970b27401a7e6517570d529400
[ "BSD-3-Clause" ]
null
null
null
/* Starshatter OpenSource Distribution Copyright (c) 1997-2004, Destroyer Studios LLC. 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 "Destroyer Studios" nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. SUBSYSTEM: nGenEx.lib FILE: Window.cpp AUTHOR: John DiCamillo OVERVIEW ======== Window class */ #include "MemDebug.h" #include "Window.h" #include "Bitmap.h" #include "Color.h" #include "Fix.h" #include "Font.h" #include "Polygon.h" #include "Screen.h" #include "Video.h" #include "View.h" static VertexSet vset4(4); // +--------------------------------------------------------------------+ Window::Window(Screen* s, int ax, int ay, int aw, int ah) : screen(s), rect(ax, ay, aw, ah), shown(true), font(0) { } // +--------------------------------------------------------------------+ Window::~Window() { view_list.destroy(); } // +--------------------------------------------------------------------+ bool Window::AddView(View* v) { if (!v) return false; if (!view_list.contains(v)) view_list.append(v); return true; } bool Window::DelView(View* v) { if (!v) return false; return view_list.remove(v) == v; } void Window::MoveTo(const Rect& r) { if (rect.x == r.x && rect.y == r.y && rect.w == r.w && rect.h == r.h) return; rect = r; ListIter<View> v = view_list; while (++v) v->OnWindowMove(); } // +--------------------------------------------------------------------+ void Window::Paint() { ListIter<View> v = view_list; while (++v) v->Refresh(); } // +--------------------------------------------------------------------+ static inline void swap(int& a, int& b) { int tmp=a; a=b; b=tmp; } static inline void sort(int& a, int& b) { if (a>b) swap(a,b); } static inline void swap(double& a, double& b) { double tmp=a; a=b; b=tmp; } static inline void sort(double& a, double& b) { if (a>b) swap(a,b); } Rect Window::ClipRect(const Rect& r) { Rect clip_rect = r; clip_rect.x += rect.x; clip_rect.y += rect.y; if (clip_rect.x < rect.x) { clip_rect.w -= rect.x - clip_rect.x; clip_rect.x = rect.x; } if (clip_rect.y < rect.y) { clip_rect.h -= rect.y - clip_rect.y; clip_rect.y = rect.y; } if (clip_rect.x + clip_rect.w > rect.x + rect.w) clip_rect.w = rect.x + rect.w - clip_rect.x; if (clip_rect.y + clip_rect.h > rect.y + rect.h) clip_rect.h = rect.y + rect.h - clip_rect.y; return clip_rect; } // +--------------------------------------------------------------------+ bool Window::ClipLine(int& x1, int& y1, int& x2, int& y2) { // vertical lines: if (x1==x2) { clip_vertical: sort(y1,y2); if (x1 < 0 || x1 >= rect.w) return false; if (y1 < 0) y1 = 0; if (y2 >= rect.h) y2 = rect.h; return true; } // horizontal lines: if (y1==y2) { clip_horizontal: sort(x1,x2); if (y1 < 0 || y1 >= rect.h) return false; if (x1 < 0) x1 = 0; if (x2 > rect.w) x2 = rect.w; return true; } // general lines: // sort left to right: if (x1 > x2) { swap(x1,x2); swap(y1,y2); } double m = (double)(y2-y1) / (double)(x2-x1); double b = (double) y1 - (m * x1); // clip: if (x1 < 0) { x1 = 0; y1 = (int) b; } if (x1 >= rect.w) return false; if (x2 < 0) return false; if (x2 > rect.w-1) { x2 = rect.w-1; y2 = (int) (m * x2 + b); } if (y1 < 0 && y2 < 0) return false; if (y1 >= rect.h && y2 >= rect.h) return false; if (y1 < 0) { y1 = 0; x1 = (int) (-b/m); } if (y1 >= rect.h) { y1 = rect.h-1; x1 = (int) ((y1-b)/m); } if (y2 < 0) { y2 = 0; x2 = (int) (-b/m); } if (y2 >= rect.h) { y2 = rect.h-1; x2 = (int) ((y2-b)/m); } if (x1 == x2) goto clip_vertical; if (y1 == y2) goto clip_horizontal; return true; } // +--------------------------------------------------------------------+ bool Window::ClipLine(double& x1, double& y1, double& x2, double& y2) { // vertical lines: if (x1==x2) { clip_vertical: sort(y1,y2); if (x1 < 0 || x1 >= rect.w) return false; if (y1 < 0) y1 = 0; if (y2 >= rect.h) y2 = rect.h; return true; } // horizontal lines: if (y1==y2) { clip_horizontal: sort(x1,x2); if (y1 < 0 || y1 >= rect.h) return false; if (x1 < 0) x1 = 0; if (x2 > rect.w) x2 = rect.w; return true; } // general lines: // sort left to right: if (x1 > x2) { swap(x1,x2); swap(y1,y2); } double m = (double)(y2-y1) / (double)(x2-x1); double b = (double) y1 - (m * x1); // clip: if (x1 < 0) { x1 = 0; y1 = b; } if (x1 >= rect.w) return false; if (x2 < 0) return false; if (x2 > rect.w-1) { x2 = rect.w-1; y2 = (m * x2 + b); } if (y1 < 0 && y2 < 0) return false; if (y1 >= rect.h && y2 >= rect.h) return false; if (y1 < 0) { y1 = 0; x1 = (-b/m); } if (y1 >= rect.h) { y1 = rect.h-1; x1 = ((y1-b)/m); } if (y2 < 0) { y2 = 0; x2 = (-b/m); } if (y2 >= rect.h) { y2 = rect.h-1; x2 = ((y2-b)/m); } if (x1 == x2) goto clip_vertical; if (y1 == y2) goto clip_horizontal; return true; } // +--------------------------------------------------------------------+ void Window::DrawLine(int x1, int y1, int x2, int y2, Color color, int blend) { if (!screen || !screen->GetVideo()) return; if (ClipLine(x1,y1,x2,y2)) { float points[4]; points[0] = (float) (rect.x + x1); points[1] = (float) (rect.y + y1); points[2] = (float) (rect.x + x2); points[3] = (float) (rect.y + y2); Video* video = screen->GetVideo(); video->DrawScreenLines(1, points, color, blend); } } // +--------------------------------------------------------------------+ void Window::DrawRect(int x1, int y1, int x2, int y2, Color color, int blend) { if (!screen || !screen->GetVideo()) return; sort(x1,x2); sort(y1,y2); if (x1 > rect.w || x2 < 0 || y1 > rect.h || y2 < 0) return; float points[16]; points[ 0] = (float) (rect.x + x1); points[ 1] = (float) (rect.y + y1); points[ 2] = (float) (rect.x + x2); points[ 3] = (float) (rect.y + y1); points[ 4] = (float) (rect.x + x2); points[ 5] = (float) (rect.y + y1); points[ 6] = (float) (rect.x + x2); points[ 7] = (float) (rect.y + y2); points[ 8] = (float) (rect.x + x2); points[ 9] = (float) (rect.y + y2); points[10] = (float) (rect.x + x1); points[11] = (float) (rect.y + y2); points[12] = (float) (rect.x + x1); points[13] = (float) (rect.y + y2); points[14] = (float) (rect.x + x1); points[15] = (float) (rect.y + y1); Video* video = screen->GetVideo(); video->DrawScreenLines(4, points, color, blend); } void Window::DrawRect(const Rect& r, Color color, int blend) { DrawRect(r.x, r.y, r.x+r.w, r.y+r.h, color, blend); } // +--------------------------------------------------------------------+ void Window::FillRect(int x1, int y1, int x2, int y2, Color color, int blend) { if (!screen || !screen->GetVideo()) return; sort(x1,x2); sort(y1,y2); if (x1 > rect.w || x2 < 0 || y1 > rect.h || y2 < 0) return; vset4.space = VertexSet::SCREEN_SPACE; for (int i = 0; i < 4; i++) { vset4.diffuse[i] = color.Value(); } vset4.s_loc[0].x = (float) (rect.x + x1) - 0.5f; vset4.s_loc[0].y = (float) (rect.y + y1) - 0.5f; vset4.s_loc[0].z = 0.0f; vset4.rw[0] = 1.0f; vset4.tu[0] = 0.0f; vset4.tv[0] = 0.0f; vset4.s_loc[1].x = (float) (rect.x + x2) - 0.5f; vset4.s_loc[1].y = (float) (rect.y + y1) - 0.5f; vset4.s_loc[1].z = 0.0f; vset4.rw[1] = 1.0f; vset4.tu[1] = 1.0f; vset4.tv[1] = 0.0f; vset4.s_loc[2].x = (float) (rect.x + x2) - 0.5f; vset4.s_loc[2].y = (float) (rect.y + y2) - 0.5f; vset4.s_loc[2].z = 0.0f; vset4.rw[2] = 1.0f; vset4.tu[2] = 1.0f; vset4.tv[2] = 1.0f; vset4.s_loc[3].x = (float) (rect.x + x1) - 0.5f; vset4.s_loc[3].y = (float) (rect.y + y2) - 0.5f; vset4.s_loc[3].z = 0.0f; vset4.rw[3] = 1.0f; vset4.tu[3] = 0.0f; vset4.tv[3] = 1.0f; Poly poly(0); poly.nverts = 4; poly.vertex_set = &vset4; poly.verts[0] = 0; poly.verts[1] = 1; poly.verts[2] = 2; poly.verts[3] = 3; Video* video = screen->GetVideo(); video->DrawScreenPolys(1, &poly, blend); } void Window::FillRect(const Rect& r, Color color, int blend) { FillRect(r.x, r.y, r.x+r.w, r.y+r.h, color, blend); } // +--------------------------------------------------------------------+ void Window::DrawLines(int nPts, POINT* pts, Color color, int blend) { if (nPts < 2 || nPts > 16) return; if (!screen || !screen->GetVideo()) return; float f[64]; int n = 0; for (int i = 0; i < nPts-1; i++) { f[n++] = (float) rect.x + pts[i].x; f[n++] = (float) rect.y + pts[i].y; f[n++] = (float) rect.x + pts[i+1].x; f[n++] = (float) rect.y + pts[i+1].y; } Video* video = screen->GetVideo(); video->DrawScreenLines(nPts-1, f, color, blend); } void Window::DrawPoly(int nPts, POINT* pts, Color color, int blend) { if (nPts < 3 || nPts > 8) return; if (!screen || !screen->GetVideo()) return; float f[32]; int n = 0; for (int i = 0; i < nPts-1; i++) { f[n++] = (float) rect.x + pts[i].x; f[n++] = (float) rect.y + pts[i].y; f[n++] = (float) rect.x + pts[i+1].x; f[n++] = (float) rect.y + pts[i+1].y; } f[n++] = (float) rect.x + pts[nPts-1].x; f[n++] = (float) rect.y + pts[nPts-1].y; f[n++] = (float) rect.x + pts[0].x; f[n++] = (float) rect.y + pts[0].y; Video* video = screen->GetVideo(); video->DrawScreenLines(nPts, f, color, blend); } void Window::FillPoly(int nPts, POINT* pts, Color color, int blend) { if (nPts < 3 || nPts > 4) return; if (!screen || !screen->GetVideo()) return; vset4.space = VertexSet::SCREEN_SPACE; for (int i = 0; i < nPts; i++) { vset4.diffuse[i] = color.Value(); vset4.s_loc[i].x = (float) (rect.x + pts[i].x) - 0.5f; vset4.s_loc[i].y = (float) (rect.y + pts[i].y) - 0.5f; vset4.s_loc[i].z = 0.0f; vset4.rw[i] = 1.0f; vset4.tu[i] = 0.0f; vset4.tv[i] = 0.0f; } Poly poly(0); poly.nverts = nPts; poly.vertex_set = &vset4; poly.verts[0] = 0; poly.verts[1] = 1; poly.verts[2] = 2; poly.verts[3] = 3; Video* video = screen->GetVideo(); video->DrawScreenPolys(1, &poly, blend); } // +--------------------------------------------------------------------+ void Window::DrawBitmap(int x1, int y1, int x2, int y2, Bitmap* img, int blend) { Rect clip_rect; clip_rect.w = rect.w; clip_rect.h = rect.h; ClipBitmap(x1,y1,x2,y2,img,Color::White,blend,clip_rect); } void Window::FadeBitmap(int x1, int y1, int x2, int y2, Bitmap* img, Color c, int blend) { Rect clip_rect; clip_rect.w = rect.w; clip_rect.h = rect.h; ClipBitmap(x1,y1,x2,y2,img,c,blend,clip_rect); } void Window::ClipBitmap(int x1, int y1, int x2, int y2, Bitmap* img, Color c, int blend, const Rect& clip_rect) { if (!screen || !screen->GetVideo() || !img) return; Rect clip = clip_rect; // clip the clip rect to the window rect: if (clip.x < 0) { clip.w -= clip.x; clip.x = 0; } if (clip.x + clip.w > rect.w) { clip.w -= (clip.x + clip.w - rect.w); } if (clip.y < 0) { clip.h -= clip.y; clip.y = 0; } if (clip.y + clip.h > rect.h) { clip.h -= (clip.y + clip.h - rect.h); } // now clip the bitmap to the validated clip rect: sort(x1,x2); sort(y1,y2); if (x1 > clip.x + clip.w || x2 < clip.x || y1 > clip.y + clip.h || y2 < clip.y) return; vset4.space = VertexSet::SCREEN_SPACE; for (int i = 0; i < 4; i++) { vset4.diffuse[i] = c.Value(); } float u1 = 0.0f; float u2 = 1.0f; float v1 = 0.0f; float v2 = 1.0f; float iw = (float) (x2-x1); float ih = (float) (y2-y1); int x3 = clip.x + clip.w; int y3 = clip.y + clip.h; if (x1 < clip.x) { u1 = (clip.x - x1) / iw; x1 = clip.x; } if (x2 > x3) { u2 = 1.0f - (x2 - x3) / iw; x2 = x3; } if (y1 < clip.y) { v1 = (clip.y - y1) / ih; y1 = clip.y; } if (y2 > y3) { v2 = 1.0f - (y2 - y3) / ih; y2 = y3; } vset4.s_loc[0].x = (float) (rect.x + x1) - 0.5f; vset4.s_loc[0].y = (float) (rect.y + y1) - 0.5f; vset4.s_loc[0].z = 0.0f; vset4.rw[0] = 1.0f; vset4.tu[0] = u1; vset4.tv[0] = v1; vset4.s_loc[1].x = (float) (rect.x + x2) - 0.5f; vset4.s_loc[1].y = (float) (rect.y + y1) - 0.5f; vset4.s_loc[1].z = 0.0f; vset4.rw[1] = 1.0f; vset4.tu[1] = u2; vset4.tv[1] = v1; vset4.s_loc[2].x = (float) (rect.x + x2) - 0.5f; vset4.s_loc[2].y = (float) (rect.y + y2) - 0.5f; vset4.s_loc[2].z = 0.0f; vset4.rw[2] = 1.0f; vset4.tu[2] = u2; vset4.tv[2] = v2; vset4.s_loc[3].x = (float) (rect.x + x1) - 0.5f; vset4.s_loc[3].y = (float) (rect.y + y2) - 0.5f; vset4.s_loc[3].z = 0.0f; vset4.rw[3] = 1.0f; vset4.tu[3] = u1; vset4.tv[3] = v2; Material mtl; mtl.tex_diffuse = img; Poly poly(0); poly.nverts = 4; poly.vertex_set = &vset4; poly.material = &mtl; poly.verts[0] = 0; poly.verts[1] = 1; poly.verts[2] = 2; poly.verts[3] = 3; Video* video = screen->GetVideo(); video->SetRenderState(Video::TEXTURE_WRAP, 0); video->DrawScreenPolys(1, &poly, blend); video->SetRenderState(Video::TEXTURE_WRAP, 1); } // +--------------------------------------------------------------------+ void Window::TileBitmap(int x1, int y1, int x2, int y2, Bitmap* img, int blend) { if (!screen || !screen->GetVideo()) return; if (!img || !img->Width() || !img->Height()) return; vset4.space = VertexSet::SCREEN_SPACE; for (int i = 0; i < 4; i++) { vset4.diffuse[i] = Color::White.Value(); } float xscale = (float) rect.w / (float) img->Width(); float yscale = (float) rect.h / (float) img->Height(); vset4.s_loc[0].x = (float) (rect.x + x1) - 0.5f; vset4.s_loc[0].y = (float) (rect.y + y1) - 0.5f; vset4.s_loc[0].z = 0.0f; vset4.rw[0] = 1.0f; vset4.tu[0] = 0.0f; vset4.tv[0] = 0.0f; vset4.s_loc[1].x = (float) (rect.x + x2) - 0.5f; vset4.s_loc[1].y = (float) (rect.y + y1) - 0.5f; vset4.s_loc[1].z = 0.0f; vset4.rw[1] = 1.0f; vset4.tu[1] = xscale; vset4.tv[1] = 0.0f; vset4.s_loc[2].x = (float) (rect.x + x2) - 0.5f; vset4.s_loc[2].y = (float) (rect.y + y2) - 0.5f; vset4.s_loc[2].z = 0.0f; vset4.rw[2] = 1.0f; vset4.tu[2] = xscale; vset4.tv[2] = yscale; vset4.s_loc[3].x = (float) (rect.x + x1) - 0.5f; vset4.s_loc[3].y = (float) (rect.y + y2) - 0.5f; vset4.s_loc[3].z = 0.0f; vset4.rw[3] = 1.0f; vset4.tu[3] = 0.0f; vset4.tv[3] = yscale; Material mtl; mtl.tex_diffuse = img; Poly poly(0); poly.nverts = 4; poly.vertex_set = &vset4; poly.material = &mtl; poly.verts[0] = 0; poly.verts[1] = 1; poly.verts[2] = 2; poly.verts[3] = 3; Video* video = screen->GetVideo(); video->DrawScreenPolys(1, &poly, blend); } // +--------------------------------------------------------------------+ static float ellipse_pts[256]; void Window::DrawEllipse(int x1, int y1, int x2, int y2, Color color, int blend) { Video* video = screen->GetVideo(); if (!video) return; sort(x1,x2); sort(y1,y2); if (x1 > rect.w || x2 < 0 || y1 > rect.h || y2 < 0) return; double w2 = (x2-x1)/2.0; double h2 = (y2-y1)/2.0; double cx = rect.x + x1 + w2; double cy = rect.y + y1 + h2; double r = w2; int ns = 4; int np = 0; if (h2 > r) r = h2; if (r > 2*ns) ns = (int) (r/2); if (ns > 64) ns = 64; double theta = 0; double dt = (PI/2) / ns; // quadrant 1 (lower right): if (cx < (rect.x+rect.w) && cy < (rect.y + rect.h)) { theta = 0; np = 0; for (int i = 0; i < ns; i++) { double ex1 = x1 + w2 + cos(theta) * w2; double ey1 = y1 + h2 + sin(theta) * h2; theta += dt; double ex2 = x1 + w2 + cos(theta) * w2; double ey2 = y1 + h2 + sin(theta) * h2; if (ClipLine(ex1, ey1, ex2, ey2)) { ellipse_pts[np++] = (float) (rect.x + ex1); ellipse_pts[np++] = (float) (rect.y + ey1); ellipse_pts[np++] = (float) (rect.x + ex2); ellipse_pts[np++] = (float) (rect.y + ey2); } } video->DrawScreenLines(np/4, ellipse_pts, color, blend); } // quadrant 2 (lower left): if (cx > rect.x && cy < (rect.y + rect.h)) { theta = 90*DEGREES; np = 0; for (int i = 0; i < ns; i++) { double ex1 = x1 + w2 + cos(theta) * w2; double ey1 = y1 + h2 + sin(theta) * h2; theta += dt; double ex2 = x1 + w2 + cos(theta) * w2; double ey2 = y1 + h2 + sin(theta) * h2; if (ClipLine(ex1, ey1, ex2, ey2)) { ellipse_pts[np++] = (float) (rect.x + ex1); ellipse_pts[np++] = (float) (rect.y + ey1); ellipse_pts[np++] = (float) (rect.x + ex2); ellipse_pts[np++] = (float) (rect.y + ey2); } } video->DrawScreenLines(np/4, ellipse_pts, color, blend); } // quadrant 3 (upper left): if (cx > rect.x && cy > rect.y) { theta = 180*DEGREES; np = 0; for (int i = 0; i < ns; i++) { double ex1 = x1 + w2 + cos(theta) * w2; double ey1 = y1 + h2 + sin(theta) * h2; theta += dt; double ex2 = x1 + w2 + cos(theta) * w2; double ey2 = y1 + h2 + sin(theta) * h2; if (ClipLine(ex1, ey1, ex2, ey2)) { ellipse_pts[np++] = (float) (rect.x + ex1); ellipse_pts[np++] = (float) (rect.y + ey1); ellipse_pts[np++] = (float) (rect.x + ex2); ellipse_pts[np++] = (float) (rect.y + ey2); } } video->DrawScreenLines(np/4, ellipse_pts, color, blend); } // quadrant 4 (upper right): if (cx < (rect.x+rect.w) && cy > rect.y) { theta = 270*DEGREES; np = 0; for (int i = 0; i < ns; i++) { double ex1 = x1 + w2 + cos(theta) * w2; double ey1 = y1 + h2 + sin(theta) * h2; theta += dt; double ex2 = x1 + w2 + cos(theta) * w2; double ey2 = y1 + h2 + sin(theta) * h2; if (ClipLine(ex1, ey1, ex2, ey2)) { ellipse_pts[np++] = (float) (rect.x + ex1); ellipse_pts[np++] = (float) (rect.y + ey1); ellipse_pts[np++] = (float) (rect.x + ex2); ellipse_pts[np++] = (float) (rect.y + ey2); } } video->DrawScreenLines(np/4, ellipse_pts, color, blend); } } void Window::FillEllipse(int x1, int y1, int x2, int y2, Color color, int blend) { Video* video = screen->GetVideo(); if (!video) return; sort(x1,x2); sort(y1,y2); if (x1 > rect.w || x2 < 0 || y1 > rect.h || y2 < 0) return; double w2 = (x2-x1)/2.0; double h2 = (y2-y1)/2.0; double cx = x1 + w2; double cy = y1 + h2; double r = w2; int ns = 4; int np = 0; if (h2 > r) r = h2; if (r > 2*ns) ns = (int) (r/2); if (ns > 64) ns = 64; double theta = -PI / 2; double dt = PI / ns; for (int i = 0; i < ns; i++) { double ex1 = cos(theta) * w2; double ey1 = sin(theta) * h2; theta += dt; double ex2 = cos(theta) * w2; double ey2 = sin(theta) * h2; POINT pts[4]; pts[0].x = (int) (cx - ex1); pts[0].y = (int) (cy + ey1); pts[1].x = (int) (cx + ex1); pts[1].y = (int) (cy + ey1); pts[2].x = (int) (cx + ex2); pts[2].y = (int) (cy + ey2); pts[3].x = (int) (cx - ex2); pts[3].y = (int) (cy + ey2); if (pts[0].x > rect.w && pts[3].x > rect.w) continue; if (pts[1].x < 0 && pts[2].x < 0) continue; if (pts[0].y > rect.h) return; if (pts[2].y < 0) continue; if (pts[0].x < 0) pts[0].x = 0; if (pts[3].x < 0) pts[3].x = 0; if (pts[1].x > rect.w) pts[1].x = rect.w; if (pts[2].x > rect.w) pts[2].x = rect.w; if (pts[0].y < 0) pts[0].y = 0; if (pts[1].y < 0) pts[1].y = 0; if (pts[2].y > rect.h) pts[2].y = rect.h; if (pts[3].y > rect.h) pts[3].y = rect.h; FillPoly(4, pts, color, blend); } } // +--------------------------------------------------------------------+ void Window::Print(int x1, int y1, const char* fmt, ...) { if (!font || x1<0 || y1<0 || x1>=rect.w || y1>=rect.h || !fmt) return; x1 += rect.x; y1 += rect.y; char msgbuf[512]; vsprintf_s(msgbuf, fmt, (char *)(&fmt+1)); font->DrawString(msgbuf, strlen(msgbuf), x1, y1, rect); } void Window::DrawText(const char* txt, int count, Rect& txt_rect, DWORD flags) { if (!font) return; if (txt && !count) count = strlen(txt); // clip the rect: Rect clip_rect = txt_rect; if (clip_rect.x < 0) { int dx = -clip_rect.x; clip_rect.x += dx; clip_rect.w -= dx; } if (clip_rect.y < 0) { int dy = -clip_rect.y; clip_rect.y += dy; clip_rect.h -= dy; } if (clip_rect.w < 1 || clip_rect.h < 1) return; if (clip_rect.x + clip_rect.w > rect.w) clip_rect.w = rect.w - clip_rect.x; if (clip_rect.y + clip_rect.h > rect.h) clip_rect.h = rect.h - clip_rect.y; clip_rect.x += rect.x; clip_rect.y += rect.y; if (font && txt && count) { font->DrawText(txt, count, clip_rect, flags); font->SetAlpha(1); } // if calc only, update the rectangle: if (flags & DT_CALCRECT) { txt_rect.h = clip_rect.h; txt_rect.w = clip_rect.w; } }
25.463059
106
0.479403
RogerioY
5ef47ed827fd88cd573bd7c95daec49cb7a816ee
1,170
cpp
C++
qtgui/ResultImage.cpp
starturtle/one-bit
32138249e20c42bd164c1d91a209f338087730f9
[ "MIT" ]
null
null
null
qtgui/ResultImage.cpp
starturtle/one-bit
32138249e20c42bd164c1d91a209f338087730f9
[ "MIT" ]
25
2020-03-18T22:50:22.000Z
2020-10-30T10:49:16.000Z
qtgui/ResultImage.cpp
starturtle/one-bit
32138249e20c42bd164c1d91a209f338087730f9
[ "MIT" ]
null
null
null
#include "ResultImage.h" #include "logging.h" #include <algorithm> #include <QMouseEvent> ResultImage::ResultImage(QQuickItem* parent) : QQuickPaintedItem() , image{} { } void ResultImage::setData(const QImage& data) { if (data.isNull()) { logging::logger() << logging::Level::NOTE << "Input Image empty!" << logging::Level::OFF; } else { logging::logger() << logging::Level::DEBUG << "Setting Result Image" << logging::Level::OFF; } image = data; if (image.isNull()) { logging::logger() << logging::Level::WARNING << "Result Image empty!" << logging::Level::OFF; } else { logging::logger() << logging::Level::DEBUG << "Set Result Image" << logging::Level::OFF; } update(); } void ResultImage::paint(QPainter* painter){ QRectF bounds = boundingRect(); if(image.isNull()) { painter->fillRect(bounds, Qt::green); return; } QImage scaled = image.scaledToWidth(bounds.width()); QPointF center = bounds.center() - scaled.rect().center(); if(center.x() < 0) center.setX(0); if(center.y() < 0) center.setY(0); painter->drawImage(center, scaled); } QImage ResultImage::data() const { return image; }
21.666667
97
0.642735
starturtle
5ef76395fe577771422a3fe5adc717b25613601f
5,459
cpp
C++
src/test_array_of_ordered.cpp
mheyman/daw_json_link_vcpkg_tests
efb56c122bec2f1a80d6a1843752510a2a8ca956
[ "BSL-1.0" ]
275
2019-04-28T18:53:01.000Z
2022-03-29T23:10:14.000Z
src/test_array_of_ordered.cpp
mheyman/daw_json_link_vcpkg_tests
efb56c122bec2f1a80d6a1843752510a2a8ca956
[ "BSL-1.0" ]
78
2019-11-15T16:20:11.000Z
2022-02-23T01:24:49.000Z
src/test_array_of_ordered.cpp
mheyman/daw_json_link_vcpkg_tests
efb56c122bec2f1a80d6a1843752510a2a8ca956
[ "BSL-1.0" ]
15
2019-06-20T10:28:47.000Z
2022-03-10T16:45:10.000Z
// Copyright (c) Darrell Wright // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/beached/daw_json_link // #include <daw/json/daw_json_link.h> #include <cstdint> #include <iostream> #include <string> #include <string_view> #include <vector> struct Fixed8JsonConverter { double operator( )( std::string_view sv ) const { return stod( std::string( sv ) ); } template<typename OutputIterator> constexpr OutputIterator operator( )( OutputIterator _it, double _f ) const { return daw::json::utils::copy_to_iterator( _it, std::to_string( _f ) ); } }; template<JSONNAMETYPE name> using json_fixed8 = daw::json::json_custom<name, double, Fixed8JsonConverter, Fixed8JsonConverter>; struct Change { double rate; double amount; }; namespace daw::json { template<> struct json_data_contract<Change> { using type = json_ordered_member_list<json_fixed8<no_name>, json_fixed8<no_name>>; }; } // namespace daw::json class DepthUpdateJson { public: std::int64_t time; // E std::string pairName; // s std::int64_t idTo; // u std::int64_t idFrom; // U std::vector<Change> bid; // b std::vector<Change> ask; // a }; namespace daw::json { template<> struct json_data_contract<DepthUpdateJson> { static constexpr char const E[] = "E"; static constexpr char const s[] = "s"; static constexpr char const u[] = "u"; static constexpr char const U[] = "U"; static constexpr char const b[] = "b"; static constexpr char const a[] = "a"; using type = json_member_list<json_number<E, std::int64_t>, json_string<s>, json_number<u, std::int64_t>, json_number<U, std::int64_t>, json_array<b, Change>, json_array<a, Change>>; }; } // namespace daw::json int main( ) { try { std::string testJson1 = R"({"e":"depthUpdate","E":1609884707320,"s":"BTCBUSD","U":2544556159,"u":2544556219,"a":[["34198.19000000","0.00000000"],["34198.23000000","0.00000000"],["34198.25000000","0.00000000"],["34198.27000000","0.00000000"],["34198.30000000","0.00000000"],["34198.32000000","0.00958500"],["34198.40000000","0.01232200"],["34198.41000000","0.01000000"],["34198.87000000","0.00000000"],["34199.12000000","0.00000000"],["34199.16000000","0.00000000"],["34199.42000000","0.00000000"],["34200.25000000","0.00000000"],["34200.71000000","0.03199900"],["34201.27000000","0.03100000"],["34201.62000000","0.00000000"],["34202.58000000","0.00000000"],["34204.45000000","0.00952700"],["34207.64000000","0.00000000"],["34207.74000000","0.00000000"],["34209.77000000","0.00000000"],["34209.81000000","0.20400000"],["34225.94000000","0.20200000"],["34226.60000000","0.91050000"],["34236.08000000","0.30000000"]],"b":[["34198.31000000","0.00000000"],["34196.54000000","0.00453200"],["34193.34000000","0.00000000"],["34189.89000000","0.00000000"],["34188.82000000","0.00000000"],["34185.32000000","0.00000000"],["34184.84000000","0.06350200"],["34184.83000000","0.20000000"],["34180.61000000","0.08622700"],["34180.60000000","0.00000000"],["34180.59000000","0.19200000"],["34180.02000000","0.00000000"],["34180.01000000","0.00000000"],["34176.88000000","0.00000000"],["34166.48000000","0.00000000"],["34166.47000000","0.00000000"],["34159.85000000","0.03317500"],["34159.24000000","0.09394900"],["34158.29000000","1.00000000"],["34154.86000000","0.00000000"]]})"; std::string testJson2 = R"({"e":"depthUpdate","E":1609884707320,"s":"BTCBUSD","U":2544556159,"u":2544556219,"b":[["34198.31000000","0.00000000"],["34196.54000000","0.00453200"],["34193.34000000","0.00000000"],["34189.89000000","0.00000000"],["34188.82000000","0.00000000"],["34185.32000000","0.00000000"],["34184.84000000","0.06350200"],["34184.83000000","0.20000000"],["34180.61000000","0.08622700"],["34180.60000000","0.00000000"],["34180.59000000","0.19200000"],["34180.02000000","0.00000000"],["34180.01000000","0.00000000"],["34176.88000000","0.00000000"],["34166.48000000","0.00000000"],["34166.47000000","0.00000000"],["34159.85000000","0.03317500"],["34159.24000000","0.09394900"],["34158.29000000","1.00000000"],["34154.86000000","0.00000000"]],"a":[["34198.19000000","0.00000000"],["34198.23000000","0.00000000"],["34198.25000000","0.00000000"],["34198.27000000","0.00000000"],["34198.30000000","0.00000000"],["34198.32000000","0.00958500"],["34198.40000000","0.01232200"],["34198.41000000","0.01000000"],["34198.87000000","0.00000000"],["34199.12000000","0.00000000"],["34199.16000000","0.00000000"],["34199.42000000","0.00000000"],["34200.25000000","0.00000000"],["34200.71000000","0.03199900"],["34201.27000000","0.03100000"],["34201.62000000","0.00000000"],["34202.58000000","0.00000000"],["34204.45000000","0.00952700"],["34207.64000000","0.00000000"],["34207.74000000","0.00000000"],["34209.77000000","0.00000000"],["34209.81000000","0.20400000"],["34225.94000000","0.20200000"],["34226.60000000","0.91050000"],["34236.08000000","0.30000000"]])"; auto parsed = daw::json::from_json<DepthUpdateJson>( testJson1 ); std::cout << ""; } catch( daw::json::json_exception const &e ) { std::cout << "formatted: " << to_formatted_string( e ) << "\n\n"; std::cout << "daw error: " << e.reason( ) << " near: '" << e.parse_location( ) << "'" << std::endl; } }
62.747126
1,543
0.66111
mheyman
5ef78d02c64c47f4d9c91d76878ca14bf8b2679d
8,274
cpp
C++
generator/maxspeeds_builder.cpp
sthirvela/organicmaps
14885ba070ac9d1b7241ebb89eeefa46c9fdc1e4
[ "Apache-2.0" ]
3,062
2021-04-09T16:51:55.000Z
2022-03-31T21:02:51.000Z
generator/maxspeeds_builder.cpp
MAPSWorks/organicmaps
b5fef4b5954cb27153c0dafddd7eed3bfa0b1e7f
[ "Apache-2.0" ]
1,396
2021-04-08T07:26:49.000Z
2022-03-31T20:27:46.000Z
generator/maxspeeds_builder.cpp
MAPSWorks/organicmaps
b5fef4b5954cb27153c0dafddd7eed3bfa0b1e7f
[ "Apache-2.0" ]
242
2021-04-10T17:10:46.000Z
2022-03-31T13:41:07.000Z
#include "generator/maxspeeds_builder.hpp" #include "generator/maxspeeds_parser.hpp" #include "generator/routing_helpers.hpp" #include "routing/index_graph.hpp" #include "routing/maxspeeds_serialization.hpp" #include "routing/routing_helpers.hpp" #include "routing_common/maxspeed_conversion.hpp" #include "indexer/feature.hpp" #include "indexer/feature_data.hpp" #include "indexer/feature_processor.hpp" #include "coding/files_container.hpp" #include "coding/file_writer.hpp" #include "platform/measurement_utils.hpp" #include "base/assert.hpp" #include "base/logging.hpp" #include "base/string_utils.hpp" #include <algorithm> #include <fstream> #include <sstream> #include <utility> #include "defines.hpp" using namespace feature; using namespace generator; using namespace routing; using namespace std; namespace { char const kDelim[] = ", \t\r\n"; bool ParseOneSpeedValue(strings::SimpleTokenizer & iter, MaxspeedType & value) { if (!iter) return false; uint64_t parsedSpeed = 0; if (!strings::to_uint64(*iter, parsedSpeed)) return false; if (parsedSpeed > routing::kInvalidSpeed) return false; value = static_cast<MaxspeedType>(parsedSpeed); ++iter; return true; } FeatureMaxspeed ToFeatureMaxspeed(uint32_t featureId, Maxspeed const & maxspeed) { return FeatureMaxspeed(featureId, maxspeed.GetUnits(), maxspeed.GetForward(), maxspeed.GetBackward()); } /// \brief Collects all maxspeed tag values of specified mwm based on maxspeeds.csv file. class MaxspeedsMwmCollector { vector<FeatureMaxspeed> m_maxspeeds; public: MaxspeedsMwmCollector(IndexGraph * graph, string const & dataPath, map<uint32_t, base::GeoObjectId> const & featureIdToOsmId, string const & maxspeedCsvPath) { OsmIdToMaxspeed osmIdToMaxspeed; CHECK(ParseMaxspeeds(maxspeedCsvPath, osmIdToMaxspeed), (maxspeedCsvPath)); auto const GetOsmID = [&](uint32_t fid) -> base::GeoObjectId { auto const osmIdIt = featureIdToOsmId.find(fid); if (osmIdIt == featureIdToOsmId.cend()) return base::GeoObjectId(); return osmIdIt->second; }; auto const GetSpeed = [&](uint32_t fid) -> Maxspeed * { auto osmid = GetOsmID(fid); if (osmid.GetType() == base::GeoObjectId::Type::Invalid) return nullptr; auto const maxspeedIt = osmIdToMaxspeed.find(osmid); if (maxspeedIt == osmIdToMaxspeed.cend()) return nullptr; return &maxspeedIt->second; }; auto const GetRoad = [&](uint32_t fid) -> routing::RoadGeometry const & { return graph->GetGeometry().GetRoad(fid); }; auto const GetLastIndex = [&](uint32_t fid) { return GetRoad(fid).GetPointsCount() - 2; }; auto const GetOpposite = [&](Segment const & seg) { // Assume that links are connected with main roads in first or last point, always. uint32_t const fid = seg.GetFeatureId(); return Segment(0, fid, seg.GetSegmentIdx() > 0 ? 0 : GetLastIndex(fid), seg.IsForward()); }; ForEachFeature(dataPath, [&](FeatureType & ft, uint32_t fid) { if (!routing::IsCarRoad(TypesHolder(ft))) return; Maxspeed * maxSpeed = GetSpeed(fid); if (!maxSpeed) return; auto const osmid = GetOsmID(fid).GetSerialId(); // Recalculate link speed accordint to the ingoing highway. // See MaxspeedsCollector::CollectFeature. if (maxSpeed->GetForward() == routing::kCommonMaxSpeedValue) { // Check if we are in unit tests. if (graph == nullptr) return; // 0 - not updated, 1 - goto next iteration, 2 - updated int status; // Check ingoing first, then - outgoing. for (bool direction : { false, true }) { Segment seg(0, fid, 0, true); if (direction) seg = GetOpposite(seg); std::unordered_set<uint32_t> reviewed; do { status = 0; reviewed.insert(seg.GetFeatureId()); IndexGraph::SegmentEdgeListT edges; graph->GetEdgeList(seg, direction, true /* useRoutingOptions */, edges); for (auto const & e : edges) { Segment const target = e.GetTarget(); Maxspeed * s = GetSpeed(target.GetFeatureId()); if (s) { if (s->GetForward() != routing::kCommonMaxSpeedValue) { status = 2; maxSpeed->SetForward(s->GetForward()); // In theory, we should iterate on forward and backward segments/speeds separately, // but I don't see any reason for this complication. if (!GetRoad(fid).IsOneWay()) maxSpeed->SetBackward(s->GetForward()); LOG(LINFO, ("Updated link speed for way", osmid, "with", *maxSpeed)); break; } else if (reviewed.find(target.GetFeatureId()) == reviewed.end()) { // Found another input link. Save it for the next iteration. status = 1; seg = GetOpposite(target); } } } } while (status == 1); if (status == 2) break; } if (status == 0) { LOG(LWARNING, ("Didn't find connected edge with speed for way", osmid)); return; } } m_maxspeeds.push_back(ToFeatureMaxspeed(fid, *maxSpeed)); }); } vector<FeatureMaxspeed> const & GetMaxspeeds() { CHECK(is_sorted(m_maxspeeds.cbegin(), m_maxspeeds.cend(), IsFeatureIdLess), ()); return m_maxspeeds; } }; } // namespace namespace routing { bool ParseMaxspeeds(string const & maxspeedsFilename, OsmIdToMaxspeed & osmIdToMaxspeed) { osmIdToMaxspeed.clear(); ifstream stream(maxspeedsFilename); if (!stream) return false; string line; while (getline(stream, line)) { strings::SimpleTokenizer iter(line, kDelim); if (!iter) // the line is empty return false; // @TODO(bykoianko) strings::to_uint64 returns not-zero value if |*iter| is equal to // a too long string of numbers. But ParseMaxspeeds() should return false in this case. uint64_t osmId = 0; if (!strings::to_uint64(*iter, osmId)) return false; ++iter; if (!iter) return false; Maxspeed speed; speed.SetUnits(StringToUnits(*iter)); ++iter; MaxspeedType forward = 0; if (!ParseOneSpeedValue(iter, forward)) return false; speed.SetForward(forward); if (iter) { // There's backward maxspeed limit. MaxspeedType backward = 0; if (!ParseOneSpeedValue(iter, backward)) return false; speed.SetBackward(backward); if (iter) return false; } auto const res = osmIdToMaxspeed.insert(make_pair(base::MakeOsmWay(osmId), speed)); if (!res.second) return false; } return true; } void SerializeMaxspeeds(string const & dataPath, vector<FeatureMaxspeed> const & speeds) { if (speeds.empty()) return; FilesContainerW cont(dataPath, FileWriter::OP_WRITE_EXISTING); auto writer = cont.GetWriter(MAXSPEEDS_FILE_TAG); MaxspeedsSerializer::Serialize(speeds, *writer); LOG(LINFO, ("SerializeMaxspeeds(", dataPath, ", ...) serialized:", speeds.size(), "maxspeed tags.")); } void BuildMaxspeedsSection(IndexGraph * graph, string const & dataPath, map<uint32_t, base::GeoObjectId> const & featureIdToOsmId, string const & maxspeedsFilename) { MaxspeedsMwmCollector collector(graph, dataPath, featureIdToOsmId, maxspeedsFilename); SerializeMaxspeeds(dataPath, collector.GetMaxspeeds()); } void BuildMaxspeedsSection(IndexGraph * graph, string const & dataPath, string const & osmToFeaturePath, string const & maxspeedsFilename) { map<uint32_t, base::GeoObjectId> featureIdToOsmId; CHECK(ParseWaysFeatureIdToOsmIdMapping(osmToFeaturePath, featureIdToOsmId), ()); BuildMaxspeedsSection(graph, dataPath, featureIdToOsmId, maxspeedsFilename); } } // namespace routing
29.236749
103
0.630771
sthirvela
5efbeea1d451979703edf492de43826be70fc94f
2,018
cpp
C++
number theory/segmented_sieve.cpp
ferdouszislam/Algorithms
bfae54231a3a27bcc69aa6585574e9ec8863e8ba
[ "MIT" ]
1
2020-10-15T10:55:45.000Z
2020-10-15T10:55:45.000Z
number theory/segmented_sieve.cpp
ferdouszislam/Algorithms
bfae54231a3a27bcc69aa6585574e9ec8863e8ba
[ "MIT" ]
null
null
null
number theory/segmented_sieve.cpp
ferdouszislam/Algorithms
bfae54231a3a27bcc69aa6585574e9ec8863e8ba
[ "MIT" ]
null
null
null
/** Segmented Sieve Find all prime numbers in the range- [a, b] where (a, b)<=10^14 and b-a<=10^5 Complexity: O(loglogN) **/ #include <bits/stdc++.h> using namespace std; ///------------------- Segmented Sieve start -------------------/// vector<int> primes; // Sieve Of Eratosthenes to find primes upto 10^7 // and populate the vector 'primes' void findPrimesUpto(int n) { primes.clear(); vector<bool> prime(n+1, true); //bool prime[n + 1]; //memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++){ if (prime[p] == true){ for (int i = p * p; i <= n; i += p) prime[i] = false; } } for (int p = 2; p <= n; p++) if (prime[p]) primes.push_back(p); } vector<long long> primesInSegment; void findPrimesInSegment(long long a, long long b){ primesInSegment.clear(); if (a == 1) a++; int sqrtn = sqrt(b); findPrimesUpto(sqrtn); vector<bool> prime(b-a+1, true); //bool prime[b-a+1]; //memset(prime, true, sizeof prime); for (int i = 0; i < primes.size() && primes[i] <= sqrtn; i++) { long long p = primes[i]; long long j = p * p; // If j is smaller than a, then shift it inside of segment [a,b] if (j < a) j = ( ( a + p - 1 ) / p ) * p; for ( ; j <= b; j += p ) { prime[j-a] = false; } } for (long long i = a; i <= b; i++) { int pos = i-a; if (prime[pos]) primesInSegment.push_back(i); } } ///------------------- Segmented Sieve end -------------------/// int getRandomNumberInRange(int lower, int upper){ // generate a random number in the range- ['lower', 'upper'] srand(time(0)); return rand()%(upper-lower+1)+lower; } void exec(){ // execute the algorithm long long a = 10e14-1000; long long b = 10e14-100; findPrimesInSegment(a, b); for(long long x : primesInSegment) cout<<x<<"\n"; } int main() { exec(); return 0; }
19.784314
81
0.512884
ferdouszislam
6f06c982cb4f6df43487f4be1d7153ba54206d82
1,206
cpp
C++
Timus/Devices.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
1
2019-09-29T03:58:35.000Z
2019-09-29T03:58:35.000Z
Timus/Devices.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
null
null
null
Timus/Devices.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> #ifdef ONLINE_JUDGE #define DB(x) #define DBL(x) #define EL #else #define DB(x) cerr << "#" << (#x) << ": " << (x) << " "; #define DBL(x) cerr << "#" << (#x) << ": " << (x) << endl; #define EL cerr << endl; #endif #define EPS 1e-11 #define X first #define Y second #define PB push_back #define SQ(x) ((x)*(x)) #define GB(m, x) ((m) & (1<<(x))) #define SB(m, x) ((m) | (1<<(x))) #define CB(m, x) ((m) & (~(1<<(x)))) #define TB(m, x) ((m) ^ (1<<(x))) using namespace std; typedef string string; typedef long double ld; typedef unsigned long long ull; typedef long long ll; typedef pair<ll, ll> ii; typedef pair<int, ii> iii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<vi> vvi; typedef vector<ll> vll; typedef pair<string, string> ss; const static ll MX = 54322, MN = 780; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); string A, B; int p, i, j; map<string, set<int>> M; while(cin >> A >> B >> p){ M[B].insert(p); } int m, mm; m = 0; mm = INT_MAX; for(auto x : M){ if(x.Y.size() > m || (x.Y.size() == m && *x.Y.begin() < mm)) { m = x.Y.size(); mm = *x.Y.begin(); A = x.X; } } cout << A << endl; }
23.647059
64
0.548093
MartinAparicioPons
6f08483d4f17cb075d9126823f81938f1bbdd3e3
1,226
cpp
C++
src/CefWing/CefRenderApp/CefViewAppBase.cpp
klarso-gmbh/CefView_CefViewCore
18958c0dbcc44e851ce8569909b098a13ea37953
[ "MIT" ]
null
null
null
src/CefWing/CefRenderApp/CefViewAppBase.cpp
klarso-gmbh/CefView_CefViewCore
18958c0dbcc44e851ce8569909b098a13ea37953
[ "MIT" ]
null
null
null
src/CefWing/CefRenderApp/CefViewAppBase.cpp
klarso-gmbh/CefView_CefViewCore
18958c0dbcc44e851ce8569909b098a13ea37953
[ "MIT" ]
null
null
null
// // CefWingAppBase.cpp // CeViewfWing // // Created by Sheen Tian on 2020/6/17. // #pragma region project_heasers #include "CefViewAppBase.h" #pragma endregion project_heasers #pragma region mac_headers #include <Common/CefViewCoreLog.h> #pragma endregion mac_headers #include <CefViewCoreProtocol.h> // These flags must match the Chromium values. const char kProcessType[] = "type"; const char kRendererProcess[] = "renderer"; CefViewAppBase::CefViewAppBase() {} // static CefViewAppBase::ProcessType CefViewAppBase::GetProcessType(CefRefPtr<CefCommandLine> command_line) { // The command-line flag won't be specified for the browser process. if (!command_line->HasSwitch(kProcessType)) return UnkownProcess; const std::string& process_type = command_line->GetSwitchValue(kProcessType); logI("process type parameter is: %s", process_type.c_str()); return (process_type == kRendererProcess) ? RendererProcess : OtherProcess; } std::string CefViewAppBase::GetBridgeObjectName(CefRefPtr<CefCommandLine> command_line) { if (!command_line->HasSwitch(CEFVIEW_BRIDGE_OBJ_NAME_KEY)) return ""; const std::string& name = command_line->GetSwitchValue(CEFVIEW_BRIDGE_OBJ_NAME_KEY); return name; }
26.652174
86
0.769984
klarso-gmbh
6f0d8852d96eb107a385ea7ca3e1c83189e2f07a
11,150
cpp
C++
tests/GrCCPRTest.cpp
lightbell/skia
37aea440fdb0257a4cffb0b41ab9745a9fc4d4fa
[ "BSD-3-Clause" ]
null
null
null
tests/GrCCPRTest.cpp
lightbell/skia
37aea440fdb0257a4cffb0b41ab9745a9fc4d4fa
[ "BSD-3-Clause" ]
null
null
null
tests/GrCCPRTest.cpp
lightbell/skia
37aea440fdb0257a4cffb0b41ab9745a9fc4d4fa
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" #include "Test.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrContextPriv.h" #include "GrClip.h" #include "GrDrawingManager.h" #include "GrPathRenderer.h" #include "GrPaint.h" #include "GrRenderTargetContext.h" #include "GrRenderTargetContextPriv.h" #include "GrShape.h" #include "SkMatrix.h" #include "SkPathPriv.h" #include "SkRect.h" #include "ccpr/GrCoverageCountingPathRenderer.h" #include "mock/GrMockTypes.h" #include <cmath> static constexpr int kCanvasSize = 100; class CCPRClip : public GrClip { public: CCPRClip(GrCoverageCountingPathRenderer* ccpr, const SkPath& path) : fCCPR(ccpr), fPath(path) {} private: bool apply(GrContext* context, GrRenderTargetContext* rtc, bool, bool, GrAppliedClip* out, SkRect* bounds) const override { GrProxyProvider* proxyProvider = context->contextPriv().proxyProvider(); out->addCoverageFP(fCCPR->makeClipProcessor(proxyProvider, rtc->priv().testingOnly_getOpListID(), fPath, SkIRect::MakeWH(rtc->width(), rtc->height()), rtc->width(), rtc->height())); return true; } bool quickContains(const SkRect&) const final { return false; } bool isRRect(const SkRect& rtBounds, SkRRect* rr, GrAA*) const final { return false; } void getConservativeBounds(int width, int height, SkIRect* rect, bool* iior) const final { rect->set(0, 0, width, height); if (iior) { *iior = false; } } GrCoverageCountingPathRenderer* const fCCPR; const SkPath fPath; }; class CCPRPathDrawer { public: CCPRPathDrawer(GrContext* ctx, skiatest::Reporter* reporter) : fCtx(ctx) , fCCPR(fCtx->contextPriv().drawingManager()->getCoverageCountingPathRenderer()) , fRTC(fCtx->contextPriv().makeDeferredRenderTargetContext( SkBackingFit::kExact, kCanvasSize, kCanvasSize, kRGBA_8888_GrPixelConfig, nullptr)) { if (!fCCPR) { ERRORF(reporter, "ccpr not enabled in GrContext for ccpr tests"); } if (!fRTC) { ERRORF(reporter, "failed to create GrRenderTargetContext for ccpr tests"); } } bool valid() const { return fCCPR && fRTC; } void clear() const { fRTC->clear(nullptr, 0, GrRenderTargetContext::CanClearFullscreen::kYes); } void abandonGrContext() { fCtx = nullptr; fCCPR = nullptr; fRTC = nullptr; } void drawPath(SkPath path, GrColor4f color = GrColor4f(0, 1, 0, 1)) const { SkASSERT(this->valid()); GrPaint paint; paint.setColor4f(color); GrNoClip noClip; SkIRect clipBounds = SkIRect::MakeWH(kCanvasSize, kCanvasSize); SkMatrix matrix = SkMatrix::I(); path.setIsVolatile(true); GrShape shape(path); fCCPR->drawPath({fCtx, std::move(paint), &GrUserStencilSettings::kUnused, fRTC.get(), &noClip, &clipBounds, &matrix, &shape, GrAAType::kCoverage, false}); } void clipFullscreenRect(SkPath clipPath, GrColor4f color = GrColor4f(0, 1, 0, 1)) { SkASSERT(this->valid()); GrPaint paint; paint.setColor4f(color); fRTC->drawRect(CCPRClip(fCCPR, clipPath), std::move(paint), GrAA::kYes, SkMatrix::I(), SkRect::MakeIWH(kCanvasSize, kCanvasSize)); } void flush() const { SkASSERT(this->valid()); fCtx->flush(); } private: GrContext* fCtx; GrCoverageCountingPathRenderer* fCCPR; sk_sp<GrRenderTargetContext> fRTC; }; class CCPRTest { public: void run(skiatest::Reporter* reporter) { GrMockOptions mockOptions; mockOptions.fInstanceAttribSupport = true; mockOptions.fMapBufferFlags = GrCaps::kCanMap_MapFlag; mockOptions.fConfigOptions[kAlpha_half_GrPixelConfig].fRenderability = GrMockOptions::ConfigOptions::Renderability::kNonMSAA; mockOptions.fConfigOptions[kAlpha_half_GrPixelConfig].fTexturable = true; mockOptions.fGeometryShaderSupport = true; mockOptions.fIntegerSupport = true; mockOptions.fFlatInterpolationSupport = true; this->customizeMockOptions(&mockOptions); GrContextOptions ctxOptions; ctxOptions.fAllowPathMaskCaching = false; ctxOptions.fGpuPathRenderers = GpuPathRenderers::kCoverageCounting; fMockContext = GrContext::MakeMock(&mockOptions, ctxOptions); if (!fMockContext) { ERRORF(reporter, "could not create mock context"); return; } if (!fMockContext->unique()) { ERRORF(reporter, "mock context is not unique"); return; } CCPRPathDrawer ccpr(fMockContext.get(), reporter); if (!ccpr.valid()) { return; } fPath.moveTo(0, 0); fPath.cubicTo(50, 50, 0, 50, 50, 0); this->onRun(reporter, ccpr); } virtual ~CCPRTest() {} protected: virtual void customizeMockOptions(GrMockOptions*) {} virtual void onRun(skiatest::Reporter* reporter, CCPRPathDrawer& ccpr) = 0; sk_sp<GrContext> fMockContext; SkPath fPath; }; #define DEF_CCPR_TEST(name) \ DEF_GPUTEST(name, reporter, /* options */) { \ name test; \ test.run(reporter); \ } class GrCCPRTest_cleanup : public CCPRTest { void onRun(skiatest::Reporter* reporter, CCPRPathDrawer& ccpr) override { REPORTER_ASSERT(reporter, SkPathPriv::TestingOnly_unique(fPath)); // Ensure paths get unreffed. for (int i = 0; i < 10; ++i) { ccpr.drawPath(fPath); ccpr.clipFullscreenRect(fPath); } REPORTER_ASSERT(reporter, !SkPathPriv::TestingOnly_unique(fPath)); ccpr.flush(); REPORTER_ASSERT(reporter, SkPathPriv::TestingOnly_unique(fPath)); // Ensure paths get unreffed when we delete the context without flushing. for (int i = 0; i < 10; ++i) { ccpr.drawPath(fPath); ccpr.clipFullscreenRect(fPath); } ccpr.abandonGrContext(); REPORTER_ASSERT(reporter, !SkPathPriv::TestingOnly_unique(fPath)); fMockContext.reset(); REPORTER_ASSERT(reporter, SkPathPriv::TestingOnly_unique(fPath)); } }; DEF_CCPR_TEST(GrCCPRTest_cleanup) class GrCCPRTest_cleanupWithTexAllocFail : public GrCCPRTest_cleanup { void customizeMockOptions(GrMockOptions* options) override { options->fFailTextureAllocations = true; } }; DEF_CCPR_TEST(GrCCPRTest_cleanupWithTexAllocFail) class GrCCPRTest_unregisterCulledOps : public CCPRTest { void onRun(skiatest::Reporter* reporter, CCPRPathDrawer& ccpr) override { REPORTER_ASSERT(reporter, SkPathPriv::TestingOnly_unique(fPath)); // Ensure Ops get unregistered from CCPR when culled early. ccpr.drawPath(fPath); REPORTER_ASSERT(reporter, !SkPathPriv::TestingOnly_unique(fPath)); ccpr.clear(); // Clear should delete the CCPR Op. REPORTER_ASSERT(reporter, SkPathPriv::TestingOnly_unique(fPath)); ccpr.flush(); // Should not crash (DrawPathsOp should have unregistered itself). // Ensure Op unregisters work when we delete the context without flushing. ccpr.drawPath(fPath); REPORTER_ASSERT(reporter, !SkPathPriv::TestingOnly_unique(fPath)); ccpr.clear(); // Clear should delete the CCPR DrawPathsOp. REPORTER_ASSERT(reporter, SkPathPriv::TestingOnly_unique(fPath)); ccpr.abandonGrContext(); fMockContext.reset(); // Should not crash (DrawPathsOp should have unregistered itself). } }; DEF_CCPR_TEST(GrCCPRTest_unregisterCulledOps) class GrCCPRTest_parseEmptyPath : public CCPRTest { void onRun(skiatest::Reporter* reporter, CCPRPathDrawer& ccpr) override { REPORTER_ASSERT(reporter, SkPathPriv::TestingOnly_unique(fPath)); // Make a path large enough that ccpr chooses to crop it by the RT bounds, and ends up with // an empty path. SkPath largeOutsidePath; largeOutsidePath.moveTo(-1e30f, -1e30f); largeOutsidePath.lineTo(-1e30f, +1e30f); largeOutsidePath.lineTo(-1e10f, +1e30f); ccpr.drawPath(largeOutsidePath); // Normally an empty path is culled before reaching ccpr, however we use a back door for // testing so this path will make it. SkPath emptyPath; SkASSERT(emptyPath.isEmpty()); ccpr.drawPath(emptyPath); // This is the test. It will exercise various internal asserts and verify we do not crash. ccpr.flush(); // Now try again with clips. ccpr.clipFullscreenRect(largeOutsidePath); ccpr.clipFullscreenRect(emptyPath); ccpr.flush(); // ... and both. ccpr.drawPath(largeOutsidePath); ccpr.clipFullscreenRect(largeOutsidePath); ccpr.drawPath(emptyPath); ccpr.clipFullscreenRect(emptyPath); ccpr.flush(); } }; DEF_CCPR_TEST(GrCCPRTest_parseEmptyPath) class CCPRRenderingTest { public: void run(skiatest::Reporter* reporter, GrContext* ctx) const { if (!ctx->contextPriv().drawingManager()->getCoverageCountingPathRenderer()) { return; // CCPR is not enabled on this GPU. } CCPRPathDrawer ccpr(ctx, reporter); if (!ccpr.valid()) { return; } this->onRun(reporter, ccpr); } virtual ~CCPRRenderingTest() {} protected: virtual void onRun(skiatest::Reporter* reporter, const CCPRPathDrawer& ccpr) const = 0; }; #define DEF_CCPR_RENDERING_TEST(name) \ DEF_GPUTEST_FOR_RENDERING_CONTEXTS(name, reporter, ctxInfo) { \ name test; \ test.run(reporter, ctxInfo.grContext()); \ } class GrCCPRTest_busyPath : public CCPRRenderingTest { void onRun(skiatest::Reporter* reporter, const CCPRPathDrawer& ccpr) const override { static constexpr int kNumBusyVerbs = 1 << 17; ccpr.clear(); SkPath busyPath; busyPath.moveTo(0, 0); // top left busyPath.lineTo(kCanvasSize, kCanvasSize); // bottom right for (int i = 2; i < kNumBusyVerbs; ++i) { float offset = i * ((float)kCanvasSize / kNumBusyVerbs); busyPath.lineTo(kCanvasSize - offset, kCanvasSize + offset); // offscreen } ccpr.drawPath(busyPath); ccpr.flush(); // If this doesn't crash, the test passed. // If it does, maybe fiddle with fMaxInstancesPerDrawArraysWithoutCrashing in // your platform's GrGLCaps. } }; DEF_CCPR_RENDERING_TEST(GrCCPRTest_busyPath) #endif
36.201299
100
0.634978
lightbell
6f10c3ca253ea68208faa87e31d11465acb79831
9,178
hpp
C++
proton-c/bindings/cpp/include/proton/container.hpp
aikchar/qpid-proton
10df4133e8877ee535e24b494738356369dcd24c
[ "Apache-2.0" ]
null
null
null
proton-c/bindings/cpp/include/proton/container.hpp
aikchar/qpid-proton
10df4133e8877ee535e24b494738356369dcd24c
[ "Apache-2.0" ]
null
null
null
proton-c/bindings/cpp/include/proton/container.hpp
aikchar/qpid-proton
10df4133e8877ee535e24b494738356369dcd24c
[ "Apache-2.0" ]
1
2020-12-17T15:47:50.000Z
2020-12-17T15:47:50.000Z
#ifndef PROTON_CONTAINER_HPP #define PROTON_CONTAINER_HPP /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ #include "./fwd.hpp" #include "./types_fwd.hpp" #include "./internal/config.hpp" #include "./internal/export.hpp" #include "./internal/pn_unique_ptr.hpp" #ifdef PN_CPP_HAS_STD_FUNCTION #include <functional> #endif #include <string> namespace proton { /// A top-level container of connections, sessions, senders, and /// receivers. /// /// A container gives a unique identity to each communicating peer. It /// is often a process-level object. /// /// It serves as an entry point to the API, allowing connections, /// senders, and receivers to be established. It can be supplied with /// an event handler in order to intercept important messaging events, /// such as newly received messages or newly issued credit for sending /// messages. class PN_CPP_CLASS_EXTERN container { public: /// Create a container. PN_CPP_EXTERN container(messaging_handler& h, const std::string& id=""); /// Create a container. PN_CPP_EXTERN container(const std::string& id=""); PN_CPP_EXTERN ~container(); /// Connect to `url` and send an open request to the remote peer. /// /// Options are applied to the connection as follows, values in later /// options override earlier ones: /// /// 1. client_connection_options() /// 2. options passed to connect() /// /// The handler in the composed options is used to call /// proton::messaging_handler::on_connection_open() when the remote peer's /// open response is received. PN_CPP_EXTERN returned<connection> connect(const std::string& url, const connection_options &); /// Connect to `url` and send an open request to the remote peer. PN_CPP_EXTERN returned<connection> connect(const std::string& url); /// @cond INTERNAL /// Stop listening on url, must match the url string given to listen(). /// You can also use the proton::listener object returned by listen() PN_CPP_EXTERN void stop_listening(const std::string& url); /// @endcond /// Start listening on url. /// /// Calls to the @ref listen_handler are serialized for this listener, /// but handlers attached to separate listeners may be called concurrently. /// /// @param url identifies a listening url. /// @param lh handles listening events /// @return listener lets you stop listening PN_CPP_EXTERN listener listen(const std::string& url, listen_handler& lh); /// Listen with a fixed set of options for all accepted connections. /// See listen(const std::string&, listen_handler&) PN_CPP_EXTERN listener listen(const std::string& url, const connection_options&); /// Start listening on URL. /// New connections will use the handler from server_connection_options() PN_CPP_EXTERN listener listen(const std::string& url); /// Run the container in this thread. /// Returns when the container stops. /// @see auto_stop() and stop(). /// /// With a multithreaded container, call run() in multiple threads to create a thread pool. PN_CPP_EXTERN void run(); /// If true, stop the container when all active connections and listeners are closed. /// If false the container will keep running till stop() is called. /// /// auto_stop is set by default when a new container is created. PN_CPP_EXTERN void auto_stop(bool); /// **Experimental** - Stop the container with an error_condition /// err. /// /// - Abort all open connections and listeners. /// - Process final handler events and injected functions /// - If `!err.empty()`, handlers will receive on_transport_error /// - run() will return in all threads. PN_CPP_EXTERN void stop(const error_condition& err); /// **Experimental** - Stop the container with an empty error /// condition. /// /// @see stop(const error_condition&) PN_CPP_EXTERN void stop(); /// Open a connection and sender for `url`. PN_CPP_EXTERN returned<sender> open_sender(const std::string &url); /// Open a connection and sender for `url`. /// /// Supplied sender options will override the container's /// template options. PN_CPP_EXTERN returned<sender> open_sender(const std::string &url, const proton::sender_options &o); /// Open a connection and sender for `url`. /// /// Supplied connection options will override the /// container's template options. PN_CPP_EXTERN returned<sender> open_sender(const std::string &url, const connection_options &c); /// Open a connection and sender for `url`. /// /// Supplied sender or connection options will override the /// container's template options. PN_CPP_EXTERN returned<sender> open_sender(const std::string &url, const proton::sender_options &o, const connection_options &c); /// Open a connection and receiver for `url`. PN_CPP_EXTERN returned<receiver> open_receiver(const std::string&url); /// Open a connection and receiver for `url`. /// /// Supplied receiver options will override the container's /// template options. PN_CPP_EXTERN returned<receiver> open_receiver(const std::string&url, const proton::receiver_options &o); /// Open a connection and receiver for `url`. /// /// Supplied receiver or connection options will override the /// container's template options. PN_CPP_EXTERN returned<receiver> open_receiver(const std::string&url, const connection_options &c); /// Open a connection and receiver for `url`. /// /// Supplied receiver or connection options will override the /// container's template options. PN_CPP_EXTERN returned<receiver> open_receiver(const std::string&url, const proton::receiver_options &o, const connection_options &c); /// A unique identifier for the container. PN_CPP_EXTERN std::string id() const; /// Connection options that will be to outgoing connections. These /// are applied first and overriden by options provided in /// connect() and messaging_handler::on_connection_open(). PN_CPP_EXTERN void client_connection_options(const connection_options &); /// @copydoc client_connection_options PN_CPP_EXTERN connection_options client_connection_options() const; /// Connection options that will be applied to incoming /// connections. These are applied first and overridden by options /// provided in listen(), listen_handler::on_accept() and /// messaging_handler::on_connection_open(). PN_CPP_EXTERN void server_connection_options(const connection_options &); /// @copydoc server_connection_options PN_CPP_EXTERN connection_options server_connection_options() const; /// Sender options applied to senders created by this /// container. They are applied before messaging_handler::on_sender_open() /// and can be overridden. PN_CPP_EXTERN void sender_options(const class sender_options &); /// @copydoc sender_options PN_CPP_EXTERN class sender_options sender_options() const; /// Receiver options applied to receivers created by this /// container. They are applied before messaging_handler::on_receiver_open() /// and can be overridden. PN_CPP_EXTERN void receiver_options(const class receiver_options &); /// @copydoc receiver_options PN_CPP_EXTERN class receiver_options receiver_options() const; /// Schedule a function to be called after the duration. C++03 /// compatible, for C++11 use schedule(duration, /// std::function<void()>) PN_CPP_EXTERN void schedule(duration, void_function0&); #if PN_CPP_HAS_STD_FUNCTION /// Schedule a function to be called after the duration PN_CPP_EXTERN void schedule(duration, std::function<void()>); #endif private: class impl; internal::pn_unique_ptr<impl> impl_; friend class connection_options; friend class session_options; friend class receiver_options; friend class sender_options; }; } // proton #endif // PROTON_CONTAINER_HPP
38.563025
99
0.686097
aikchar
6f1759908d4bb42a1f3f7b6639aca363236a09ab
4,484
cpp
C++
Source/Scripting/bsfScript/Generated/BsScriptParticleDepthCollisionSettings.generated.cpp
bsf2dev/bsf
b318cd4eb1b0299773d625e6c870b8d503cf539e
[ "MIT" ]
1,745
2018-03-16T02:10:28.000Z
2022-03-26T17:34:21.000Z
Source/Scripting/bsfScript/Generated/BsScriptParticleDepthCollisionSettings.generated.cpp
bsf2dev/bsf
b318cd4eb1b0299773d625e6c870b8d503cf539e
[ "MIT" ]
395
2018-03-16T10:18:20.000Z
2021-08-04T16:52:08.000Z
Source/Scripting/bsfScript/Generated/BsScriptParticleDepthCollisionSettings.generated.cpp
bsf2dev/bsf
b318cd4eb1b0299773d625e6c870b8d503cf539e
[ "MIT" ]
267
2018-03-17T19:32:54.000Z
2022-02-17T16:55:50.000Z
//********************************* bs::framework - Copyright 2018-2019 Marko Pintera ************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// #include "BsScriptParticleDepthCollisionSettings.generated.h" #include "BsMonoMethod.h" #include "BsMonoClass.h" #include "BsMonoUtil.h" namespace bs { ScriptParticleDepthCollisionSettings::ScriptParticleDepthCollisionSettings(MonoObject* managedInstance, const SPtr<ParticleDepthCollisionSettings>& value) :TScriptReflectable(managedInstance, value) { } void ScriptParticleDepthCollisionSettings::initRuntimeData() { metaData.scriptClass->addInternalCall("Internal_ParticleDepthCollisionSettings", (void*)&ScriptParticleDepthCollisionSettings::Internal_ParticleDepthCollisionSettings); metaData.scriptClass->addInternalCall("Internal_getenabled", (void*)&ScriptParticleDepthCollisionSettings::Internal_getenabled); metaData.scriptClass->addInternalCall("Internal_setenabled", (void*)&ScriptParticleDepthCollisionSettings::Internal_setenabled); metaData.scriptClass->addInternalCall("Internal_getrestitution", (void*)&ScriptParticleDepthCollisionSettings::Internal_getrestitution); metaData.scriptClass->addInternalCall("Internal_setrestitution", (void*)&ScriptParticleDepthCollisionSettings::Internal_setrestitution); metaData.scriptClass->addInternalCall("Internal_getdampening", (void*)&ScriptParticleDepthCollisionSettings::Internal_getdampening); metaData.scriptClass->addInternalCall("Internal_setdampening", (void*)&ScriptParticleDepthCollisionSettings::Internal_setdampening); metaData.scriptClass->addInternalCall("Internal_getradiusScale", (void*)&ScriptParticleDepthCollisionSettings::Internal_getradiusScale); metaData.scriptClass->addInternalCall("Internal_setradiusScale", (void*)&ScriptParticleDepthCollisionSettings::Internal_setradiusScale); } MonoObject* ScriptParticleDepthCollisionSettings::create(const SPtr<ParticleDepthCollisionSettings>& value) { if(value == nullptr) return nullptr; bool dummy = false; void* ctorParams[1] = { &dummy }; MonoObject* managedInstance = metaData.scriptClass->createInstance("bool", ctorParams); new (bs_alloc<ScriptParticleDepthCollisionSettings>()) ScriptParticleDepthCollisionSettings(managedInstance, value); return managedInstance; } void ScriptParticleDepthCollisionSettings::Internal_ParticleDepthCollisionSettings(MonoObject* managedInstance) { SPtr<ParticleDepthCollisionSettings> instance = bs_shared_ptr_new<ParticleDepthCollisionSettings>(); new (bs_alloc<ScriptParticleDepthCollisionSettings>())ScriptParticleDepthCollisionSettings(managedInstance, instance); } bool ScriptParticleDepthCollisionSettings::Internal_getenabled(ScriptParticleDepthCollisionSettings* thisPtr) { bool tmp__output; tmp__output = thisPtr->getInternal()->enabled; bool __output; __output = tmp__output; return __output; } void ScriptParticleDepthCollisionSettings::Internal_setenabled(ScriptParticleDepthCollisionSettings* thisPtr, bool value) { thisPtr->getInternal()->enabled = value; } float ScriptParticleDepthCollisionSettings::Internal_getrestitution(ScriptParticleDepthCollisionSettings* thisPtr) { float tmp__output; tmp__output = thisPtr->getInternal()->restitution; float __output; __output = tmp__output; return __output; } void ScriptParticleDepthCollisionSettings::Internal_setrestitution(ScriptParticleDepthCollisionSettings* thisPtr, float value) { thisPtr->getInternal()->restitution = value; } float ScriptParticleDepthCollisionSettings::Internal_getdampening(ScriptParticleDepthCollisionSettings* thisPtr) { float tmp__output; tmp__output = thisPtr->getInternal()->dampening; float __output; __output = tmp__output; return __output; } void ScriptParticleDepthCollisionSettings::Internal_setdampening(ScriptParticleDepthCollisionSettings* thisPtr, float value) { thisPtr->getInternal()->dampening = value; } float ScriptParticleDepthCollisionSettings::Internal_getradiusScale(ScriptParticleDepthCollisionSettings* thisPtr) { float tmp__output; tmp__output = thisPtr->getInternal()->radiusScale; float __output; __output = tmp__output; return __output; } void ScriptParticleDepthCollisionSettings::Internal_setradiusScale(ScriptParticleDepthCollisionSettings* thisPtr, float value) { thisPtr->getInternal()->radiusScale = value; } }
40.763636
170
0.807538
bsf2dev
6f1bcda59f47ce894a61e4f743de58b2941f4687
20,321
cpp
C++
lv_cpp/core/LvObj.cpp
lvgl/lv_binding_cpp
5ce27254ac8526dd1ca61e883785ed2606076a68
[ "MIT" ]
7
2021-07-26T12:26:48.000Z
2022-03-19T16:30:56.000Z
lv_cpp/core/LvObj.cpp
lvgl/lv_binding_cpp
5ce27254ac8526dd1ca61e883785ed2606076a68
[ "MIT" ]
4
2021-07-15T21:31:48.000Z
2022-02-03T11:48:16.000Z
lv_cpp/core/LvObj.cpp
kisvegabor/lv_binding_cpp
5ce27254ac8526dd1ca61e883785ed2606076a68
[ "MIT" ]
2
2021-10-06T00:59:52.000Z
2022-02-18T15:03:51.000Z
/* * LvObj.cpp * * Created on: Jun 24, 2021 * Author: fstuffdev */ #include "LvObj.h" namespace lvglpp { LvObj::LvObj() : LvObj(NULL){ } LvObj::LvObj(LvObj* Parent) { if(Parent) cObj.reset(lv_obj_create(Parent->raw())); else cObj.reset(lv_obj_create(lv_scr_act())); } lv_obj_t* LvObj::raw() { return cObj.get(); } LvObj::~LvObj() { } LvObj& LvObj::setCObj(lv_obj_t* _cObj) { if(_cObj) cObj.reset(_cObj); return *this; } LvObj& LvObj::setUserData(void *user_data){ lv_obj_set_user_data(cObj.get(),user_data); return *this; } void *LvObj::getUserData() const noexcept { return lv_obj_get_user_data(cObj.get()); } lv_coord_t LvObj::dpx(lv_coord_t n){ return lv_obj_dpx(cObj.get(),n); } LvObj& LvObj::del(){ lv_obj_del(cObj.get()); return *this; } LvObj& LvObj::clean(){ lv_obj_clean(cObj.get()); return *this; } LvObj& LvObj::delDelayed(uint32_t delay_ms){ lv_obj_del_delayed(cObj.get(),delay_ms); return *this; } LvObj& LvObj::delAsync(){ lv_obj_del_async(cObj.get()); return *this; } LvObj& LvObj::setParent(LvObj *parent){ lv_obj_set_parent(cObj.get(),parent->raw()); return *this; } LvObj& LvObj::moveToIndex(int32_t index){ lv_obj_move_to_index(cObj.get(),index); return *this; } lv_obj_t *LvObj::getScreen() const noexcept { return lv_obj_get_screen(cObj.get()); } lv_disp_t *LvObj::getDisp() const noexcept { return lv_obj_get_disp(cObj.get()); } lv_obj_t *LvObj::getParent() const noexcept { return lv_obj_get_parent(cObj.get()); } lv_obj_t *LvObj::getChild(int32_t id) const noexcept { return lv_obj_get_child(cObj.get(),id); } uint32_t LvObj::getChildCnt() const noexcept { return lv_obj_get_child_cnt(cObj.get()); } uint32_t LvObj::getIndex() const noexcept { return lv_obj_get_index(cObj.get()); } LvObj& LvObj::moveForeground(){ lv_obj_move_foreground(cObj.get()); return *this; } LvObj& LvObj::moveBackground(){ lv_obj_move_background(cObj.get()); return *this; } lv_flex_flow_t LvObj::getStyleFlexFlow(uint32_t part) const noexcept { return lv_obj_get_style_flex_flow(cObj.get(),part); } lv_flex_align_t LvObj::getStyleFlexMainPlace(uint32_t part) const noexcept { return lv_obj_get_style_flex_main_place(cObj.get(),part); } lv_flex_align_t LvObj::getStyleFlexCrossPlace(uint32_t part) const noexcept { return lv_obj_get_style_flex_cross_place(cObj.get(),part); } lv_flex_align_t LvObj::getStyleFlexTrackPlace(uint32_t part) const noexcept { return lv_obj_get_style_flex_track_place(cObj.get(),part); } uint8_t LvObj::getStyleFlexGrow(uint32_t part) const noexcept { return lv_obj_get_style_flex_grow(cObj.get(),part); } const lv_coord_t *LvObj::getStyleGridRowDscArray(uint32_t part) const noexcept { return lv_obj_get_style_grid_row_dsc_array(cObj.get(),part); } const lv_coord_t *LvObj::getStyleGridColumnDscArray(uint32_t part) const noexcept { return lv_obj_get_style_grid_column_dsc_array(cObj.get(),part); } lv_grid_align_t LvObj::getStyleGridRowAlign(uint32_t part) const noexcept { return lv_obj_get_style_grid_row_align(cObj.get(),part); } lv_grid_align_t LvObj::getStyleGridColumnAlign(uint32_t part) const noexcept { return lv_obj_get_style_grid_column_align(cObj.get(),part); } lv_coord_t LvObj::getStyleGridCellColumnPos(uint32_t part) const noexcept { return lv_obj_get_style_grid_cell_column_pos(cObj.get(),part); } lv_coord_t LvObj::getStyleGridCellColumnSpan(uint32_t part) const noexcept { return lv_obj_get_style_grid_cell_column_span(cObj.get(),part); } lv_coord_t LvObj::getStyleGridCellRowPos(uint32_t part) const noexcept { return lv_obj_get_style_grid_cell_row_pos(cObj.get(),part); } lv_coord_t LvObj::getStyleGridCellRowSpan(uint32_t part) const noexcept { return lv_obj_get_style_grid_cell_row_span(cObj.get(),part); } lv_coord_t LvObj::getStyleGridCellXAlign(uint32_t part) const noexcept { return lv_obj_get_style_grid_cell_x_align(cObj.get(),part); } lv_coord_t LvObj::getStyleGridCellYAlign(uint32_t part) const noexcept { return lv_obj_get_style_grid_cell_y_align(cObj.get(),part); } lv_theme_t *LvObj::getTheme() const noexcept { return lv_theme_get_from_obj(cObj.get()); } struct _lv_event_dsc_t *LvObj::addEventCb(lv_event_cb_t event_cb, lv_event_code_t filter, void *user_data){ return lv_obj_add_event_cb(cObj.get(),event_cb,filter,user_data); } bool LvObj::removeEventCb(lv_event_cb_t event_cb){ return lv_obj_remove_event_cb(cObj.get(),event_cb); } bool LvObj::removeEventCbWithUserData(lv_event_cb_t event_cb, const void *user_data){ return lv_obj_remove_event_cb_with_user_data(cObj.get(),event_cb,user_data); } bool LvObj::removeEventDsc(struct _lv_event_dsc_t *event_dsc){ return lv_obj_remove_event_dsc(cObj.get(),event_dsc); } LvObj& LvObj::classInitObj(){ lv_obj_class_init_obj(cObj.get()); return *this; } LvObj& LvObj::destruct(){ _lv_obj_destruct(cObj.get()); return *this; } bool LvObj::isEditable(){ return lv_obj_is_editable(cObj.get()); } bool LvObj::isGroupDef(){ return lv_obj_is_group_def(cObj.get()); } LvObj& LvObj::addFlag(lv_obj_flag_t f){ lv_obj_add_flag(cObj.get(),f); return *this; } LvObj& LvObj::clearFlag(lv_obj_flag_t f){ lv_obj_clear_flag(cObj.get(),f); return *this; } LvObj& LvObj::addState(lv_state_t state){ lv_obj_add_state(cObj.get(),state); return *this; } LvObj& LvObj::clearState(lv_state_t state){ lv_obj_clear_state(cObj.get(),state); return *this; } bool LvObj::hasFlag(lv_obj_flag_t f){ return lv_obj_has_flag(cObj.get(),f); } bool LvObj::hasFlagAny(lv_obj_flag_t f){ return lv_obj_has_flag_any(cObj.get(),f); } lv_state_t LvObj::getState() const noexcept { return lv_obj_get_state(cObj.get()); } bool LvObj::hasState(lv_state_t state){ return lv_obj_has_state(cObj.get(),state); } void *LvObj::getGroup() const noexcept { return lv_obj_get_group(cObj.get()); } LvObj& LvObj::allocateSpecAttr(){ lv_obj_allocate_spec_attr(cObj.get()); return *this; } bool LvObj::checkType(const lv_obj_class_t *class_p){ return lv_obj_check_type(cObj.get(),class_p); } bool LvObj::hasClass(const lv_obj_class_t *class_p){ return lv_obj_has_class(cObj.get(),class_p); } const lv_obj_class_t *LvObj::getClass() const noexcept { return lv_obj_get_class(cObj.get()); } bool LvObj::isValid(){ return lv_obj_is_valid(cObj.get()); } LvObj& LvObj::setScrollbarMode(lv_scrollbar_mode_t mode){ lv_obj_set_scrollbar_mode(cObj.get(),mode); return *this; } LvObj& LvObj::setScrollDir(lv_dir_t dir){ lv_obj_set_scroll_dir(cObj.get(),dir); return *this; } LvObj& LvObj::setScrollSnapX(lv_scroll_snap_t align){ lv_obj_set_scroll_snap_x(cObj.get(),align); return *this; } LvObj& LvObj::setScrollSnapY(lv_scroll_snap_t align){ lv_obj_set_scroll_snap_y(cObj.get(),align); return *this; } lv_scrollbar_mode_t LvObj::getScrollbarMode() const noexcept { return lv_obj_get_scrollbar_mode(cObj.get()); } lv_dir_t LvObj::getScrollDir() const noexcept { return lv_obj_get_scroll_dir(cObj.get()); } lv_scroll_snap_t LvObj::getScrollSnapX() const noexcept { return lv_obj_get_scroll_snap_x(cObj.get()); } lv_scroll_snap_t LvObj::getScrollSnapY() const noexcept { return lv_obj_get_scroll_snap_y(cObj.get()); } lv_coord_t LvObj::getScrollX() const noexcept { return lv_obj_get_scroll_x(cObj.get()); } lv_coord_t LvObj::getScrollY() const noexcept { return lv_obj_get_scroll_y(cObj.get()); } lv_coord_t LvObj::getScrollTop() const noexcept { return lv_obj_get_scroll_top(cObj.get()); } lv_coord_t LvObj::getScrollBottom() const noexcept { return lv_obj_get_scroll_bottom(cObj.get()); } lv_coord_t LvObj::getScrollLeft() const noexcept { return lv_obj_get_scroll_left(cObj.get()); } lv_coord_t LvObj::getScrollRight() const noexcept { return lv_obj_get_scroll_right(cObj.get()); } LvObj& LvObj::scrollBy(lv_coord_t x, lv_coord_t y, lv_anim_enable_t anim_en){ lv_obj_scroll_by(cObj.get(),x,y,anim_en); return *this; } LvObj& LvObj::scrollTo(lv_coord_t x, lv_coord_t y, lv_anim_enable_t anim_en){ lv_obj_scroll_to(cObj.get(),x,y,anim_en); return *this; } LvObj& LvObj::scrollToX(lv_coord_t x, lv_anim_enable_t anim_en){ lv_obj_scroll_to_x(cObj.get(),x,anim_en); return *this; } LvObj& LvObj::scrollToY(lv_coord_t y, lv_anim_enable_t anim_en){ lv_obj_scroll_to_y(cObj.get(),y,anim_en); return *this; } LvObj& LvObj::scrollToView(lv_anim_enable_t anim_en){ lv_obj_scroll_to_view(cObj.get(),anim_en); return *this; } LvObj& LvObj::scrollToViewRecursive(lv_anim_enable_t anim_en){ lv_obj_scroll_to_view_recursive(cObj.get(),anim_en); return *this; } bool LvObj::isScrolling(){ return lv_obj_is_scrolling(cObj.get()); } LvObj& LvObj::updateSnap(lv_anim_enable_t anim_en){ lv_obj_update_snap(cObj.get(),anim_en); return *this; } LvObj& LvObj::getScrollbarArea(lv_area_t *hor_area, lv_area_t *ver_area){ lv_obj_get_scrollbar_area(cObj.get(),hor_area,ver_area); return *this; } LvObj& LvObj::scrollbarInvalidate(){ lv_obj_scrollbar_invalidate(cObj.get()); return *this; } LvObj& LvObj::readjustScroll(lv_anim_enable_t anim_en){ lv_obj_readjust_scroll(cObj.get(),anim_en); return *this; } lv_obj_t *LvObj::lvIndevSearchObj(lv_point_t *point){ return lv_indev_search_obj(cObj.get(),point); } LvObj& LvObj::lvGroupRemoveObj(){ lv_group_remove_obj(cObj.get()); return *this; } LvObj& LvObj::lvGroupFocusObj(){ lv_group_focus_obj(cObj.get()); return *this; } LvObj& LvObj::setPos(lv_coord_t x, lv_coord_t y){ lv_obj_set_pos(cObj.get(),x,y); return *this; } LvObj& LvObj::setX(lv_coord_t x){ lv_obj_set_x(cObj.get(),x); return *this; } LvObj& LvObj::setY(lv_coord_t y){ lv_obj_set_y(cObj.get(),y); return *this; } bool LvObj::refrSize(){ return lv_obj_refr_size(cObj.get()); } LvObj& LvObj::setSize(lv_coord_t w, lv_coord_t h){ lv_obj_set_size(cObj.get(),w,h); return *this; } LvObj& LvObj::setWidth(lv_coord_t w){ lv_obj_set_width(cObj.get(),w); return *this; } LvObj& LvObj::setHeight(lv_coord_t h){ lv_obj_set_height(cObj.get(),h); return *this; } LvObj& LvObj::setContentWidth(lv_coord_t w){ lv_obj_set_content_width(cObj.get(),w); return *this; } LvObj& LvObj::setContentHeight(lv_coord_t h){ lv_obj_set_content_height(cObj.get(),h); return *this; } LvObj& LvObj::setLayout(uint32_t layout){ lv_obj_set_layout(cObj.get(),layout); return *this; } bool LvObj::isLayoutPositioned(){ return lv_obj_is_layout_positioned(cObj.get()); } LvObj& LvObj::markLayoutAsDirty(){ lv_obj_mark_layout_as_dirty(cObj.get()); return *this; } LvObj& LvObj::updateLayout(){ lv_obj_update_layout(cObj.get()); return *this; } LvObj& LvObj::setAlign(lv_align_t align){ lv_obj_set_align(cObj.get(),align); return *this; } LvObj& LvObj::align(lv_align_t align, lv_coord_t x_ofs, lv_coord_t y_ofs){ lv_obj_align(cObj.get(),align,x_ofs,y_ofs); return *this; } LvObj& LvObj::alignTo(const lv_obj_t *base, lv_align_t align, lv_coord_t x_ofs, lv_coord_t y_ofs){ lv_obj_align_to(cObj.get(),base,align,x_ofs,y_ofs); return *this; } LvObj& LvObj::getCoords(lv_area_t *coords){ lv_obj_get_coords(cObj.get(),coords); return *this; } lv_coord_t LvObj::getX() const noexcept { return lv_obj_get_x(cObj.get()); } lv_coord_t LvObj::getX2() const noexcept { return lv_obj_get_x2(cObj.get()); } lv_coord_t LvObj::getY() const noexcept { return lv_obj_get_y(cObj.get()); } lv_coord_t LvObj::getY2() const noexcept { return lv_obj_get_y2(cObj.get()); } lv_coord_t LvObj::getWidth() const noexcept { return lv_obj_get_width(cObj.get()); } lv_coord_t LvObj::getHeight() const noexcept { return lv_obj_get_height(cObj.get()); } lv_coord_t LvObj::getContentWidth() const noexcept { return lv_obj_get_content_width(cObj.get()); } lv_coord_t LvObj::getContentHeight() const noexcept { return lv_obj_get_content_height(cObj.get()); } LvObj& LvObj::getContentCoords(lv_area_t *area){ lv_obj_get_content_coords(cObj.get(),area); return *this; } lv_coord_t LvObj::getSelfWidth() const noexcept { return lv_obj_get_self_width(cObj.get()); } lv_coord_t LvObj::getSelfHeight() const noexcept { return lv_obj_get_self_height(cObj.get()); } bool LvObj::refreshSelfSize(){ return lv_obj_refresh_self_size(cObj.get()); } LvObj& LvObj::refrPos(){ lv_obj_refr_pos(cObj.get()); return *this; } LvObj& LvObj::moveTo(lv_coord_t x, lv_coord_t y){ lv_obj_move_to(cObj.get(),x,y); return *this; } LvObj& LvObj::moveChildrenBy(lv_coord_t x_diff, lv_coord_t y_diff, bool ignore_floating){ lv_obj_move_children_by(cObj.get(),x_diff,y_diff,ignore_floating); return *this; } LvObj& LvObj::invalidateArea(const lv_area_t *area){ lv_obj_invalidate_area(cObj.get(),area); return *this; } LvObj& LvObj::invalidate(){ lv_obj_invalidate(cObj.get()); return *this; } bool LvObj::areaIsVisible(lv_area_t *area){ return lv_obj_area_is_visible(cObj.get(),area); } bool LvObj::isVisible(){ return lv_obj_is_visible(cObj.get()); } LvObj& LvObj::setExtClickArea(lv_coord_t size){ lv_obj_set_ext_click_area(cObj.get(),size); return *this; } LvObj& LvObj::getClickArea(lv_area_t *area){ lv_obj_get_click_area(cObj.get(),area); return *this; } bool LvObj::hitTest(const lv_point_t *point){ return lv_obj_hit_test(cObj.get(),point); } LvObj& LvObj::addStyle(LvStyle *style, lv_style_selector_t selector){ lv_obj_add_style(cObj.get(),style->raw(),selector); return *this; } LvObj& LvObj::removeStyle(LvStyle *style, lv_style_selector_t selector){ lv_obj_remove_style(cObj.get(),style->raw(),selector); return *this; } LvObj& LvObj::refreshStyle(lv_style_selector_t selector, lv_style_prop_t prop){ lv_obj_refresh_style(cObj.get(),selector,prop); return *this; } lv_style_value_t LvObj::getStyleProp(lv_part_t part, lv_style_prop_t prop) const noexcept { return lv_obj_get_style_prop(cObj.get(),part,prop); } LvObj& LvObj::setLocalStyleProp(lv_style_prop_t prop, lv_style_value_t value, lv_style_selector_t selector){ lv_obj_set_local_style_prop(cObj.get(),prop,value,selector); return *this; } lv_res_t LvObj::getLocalStyleProp(lv_style_prop_t prop, lv_style_value_t *value, lv_style_selector_t selector) const noexcept { return lv_obj_get_local_style_prop(cObj.get(),prop,value,selector); } bool LvObj::removeLocalStyleProp(lv_style_prop_t prop, lv_style_selector_t selector){ return lv_obj_remove_local_style_prop(cObj.get(),prop,selector); } LvObj& LvObj::styleCreateTransition(lv_part_t part, lv_state_t prev_state, lv_state_t new_state, const _lv_obj_style_transition_dsc_t *tr_dsc){ _lv_obj_style_create_transition(cObj.get(),part,prev_state,new_state,tr_dsc); return *this; } _lv_style_state_cmp_t LvObj::styleStateCompare(lv_state_t state1, lv_state_t state2){ return _lv_obj_style_state_compare(cObj.get(),state1,state2); } LvObj& LvObj::fadeIn(uint32_t time, uint32_t delay){ lv_obj_fade_in(cObj.get(),time,delay); return *this; } LvObj& LvObj::fadeOut(uint32_t time, uint32_t delay){ lv_obj_fade_out(cObj.get(),time,delay); return *this; } LvObj& LvObj::initDrawRectDsc(uint32_t part, lv_draw_rect_dsc_t *draw_dsc){ lv_obj_init_draw_rect_dsc(cObj.get(),part,draw_dsc); return *this; } LvObj& LvObj::initDrawLabelDsc(uint32_t part, lv_draw_label_dsc_t *draw_dsc){ lv_obj_init_draw_label_dsc(cObj.get(),part,draw_dsc); return *this; } LvObj& LvObj::initDrawImgDsc(uint32_t part, lv_draw_img_dsc_t *draw_dsc){ lv_obj_init_draw_img_dsc(cObj.get(),part,draw_dsc); return *this; } LvObj& LvObj::initDrawLineDsc(uint32_t part, lv_draw_line_dsc_t *draw_dsc){ lv_obj_init_draw_line_dsc(cObj.get(),part,draw_dsc); return *this; } LvObj& LvObj::initDrawArcDsc(uint32_t part, lv_draw_arc_dsc_t *draw_dsc){ lv_obj_init_draw_arc_dsc(cObj.get(),part,draw_dsc); return *this; } lv_coord_t LvObj::calculateExtDrawSize(uint32_t part){ return lv_obj_calculate_ext_draw_size(cObj.get(),part); } LvObj& LvObj::refreshExtDrawSize(){ lv_obj_refresh_ext_draw_size(cObj.get()); return *this; } lv_coord_t LvObj::getExtDrawSize() const noexcept { return _lv_obj_get_ext_draw_size(cObj.get()); } LvObj& LvObj::setFlexFlow(lv_flex_flow_t flow){ lv_obj_set_flex_flow(cObj.get(),flow); return *this; } LvObj& LvObj::setFlexAlign(lv_flex_align_t main_place, lv_flex_align_t cross_place, lv_flex_align_t track_place){ lv_obj_set_flex_align(cObj.get(),main_place,cross_place,track_place); return *this; } LvObj& LvObj::setFlexGrow(uint8_t grow){ lv_obj_set_flex_grow(cObj.get(),grow); return *this; } LvObj& LvObj::setStyleFlexFlow(lv_flex_flow_t value, lv_style_selector_t selector){ lv_obj_set_style_flex_flow(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleFlexMainPlace(lv_flex_align_t value, lv_style_selector_t selector){ lv_obj_set_style_flex_main_place(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleFlexCrossPlace(lv_flex_align_t value, lv_style_selector_t selector){ lv_obj_set_style_flex_cross_place(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleFlexTrackPlace(lv_flex_align_t value, lv_style_selector_t selector){ lv_obj_set_style_flex_track_place(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleFlexGrow(uint8_t value, lv_style_selector_t selector){ lv_obj_set_style_flex_grow(cObj.get(),value,selector); return *this; } LvObj& LvObj::setGridDscArray(const lv_coord_t col_dsc[], const lv_coord_t row_dsc[]){ lv_obj_set_grid_dsc_array(cObj.get(),col_dsc,row_dsc); return *this; } LvObj& LvObj::setGridAlign(lv_grid_align_t column_align, lv_grid_align_t row_align){ lv_obj_set_grid_align(cObj.get(),column_align,row_align); return *this; } LvObj& LvObj::setGridCell(lv_grid_align_t x_align, uint8_t col_pos, uint8_t col_span, lv_grid_align_t y_align, uint8_t row_pos, uint8_t row_span){ lv_obj_set_grid_cell(cObj.get(),x_align,col_pos,col_span,y_align,row_pos,row_span); return *this; } LvObj& LvObj::setStyleGridRowDscArray(const lv_coord_t value[], lv_style_selector_t selector){ lv_obj_set_style_grid_row_dsc_array(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridColumnDscArray(const lv_coord_t value[], lv_style_selector_t selector){ lv_obj_set_style_grid_column_dsc_array(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridRowAlign(lv_grid_align_t value, lv_style_selector_t selector){ lv_obj_set_style_grid_row_align(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridColumnAlign(lv_grid_align_t value, lv_style_selector_t selector){ lv_obj_set_style_grid_column_align(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridCellColumnPos(lv_coord_t value, lv_style_selector_t selector){ lv_obj_set_style_grid_cell_column_pos(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridCellColumnSpan(lv_coord_t value, lv_style_selector_t selector){ lv_obj_set_style_grid_cell_column_span(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridCellRowPos(lv_coord_t value, lv_style_selector_t selector){ lv_obj_set_style_grid_cell_row_pos(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridCellRowSpan(lv_coord_t value, lv_style_selector_t selector){ lv_obj_set_style_grid_cell_row_span(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridCellXAlign(lv_coord_t value, lv_style_selector_t selector){ lv_obj_set_style_grid_cell_x_align(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridCellYAlign(lv_coord_t value, lv_style_selector_t selector){ lv_obj_set_style_grid_cell_y_align(cObj.get(),value,selector); return *this; } /* The Cpp event dispatcher */ void LvObj::EventDispatcher(lv_event_t *e) { LvObj *_Obj = static_cast<LvObj*>(e->user_data); std::list<eventBind_t>::iterator eventIter; if (_Obj) { /* Search in registered events */ for (eventIter = _Obj->eventRegister.begin(); eventIter != _Obj->eventRegister.end(); eventIter++) { if (eventIter->evCode == e->code) { /* Call the event */ if (eventIter->evCallback) (*(eventIter->evCallback))(e); } } } } /* Enable the related code Callback */ LvObj& LvObj::setCallback(lv_event_code_t code, LvEvent *Cb) { eventBind_t eventToRegister; eventToRegister.evCallback = Cb; eventToRegister.evCode = code; /* Setting Callback to EventDispatcher sacrificing user_data of callback */ this->addEventCb(LvObj::EventDispatcher, code, (void*) this); eventRegister.push_back(eventToRegister); return *this; } } /* namespace lvglpp */
28.341702
146
0.771763
lvgl
6f1ce37f18f27a5a0216f1df4ca5e79255e52500
3,475
hh
C++
include/util/Singleton.hh
janpipek/g4application
6b063636474a7a8f212023ada7fbb60bd4439606
[ "MIT" ]
1
2018-04-14T08:53:04.000Z
2018-04-14T08:53:04.000Z
include/util/Singleton.hh
janpipek/g4application
6b063636474a7a8f212023ada7fbb60bd4439606
[ "MIT" ]
23
2015-01-13T10:57:36.000Z
2015-11-25T17:49:27.000Z
include/util/Singleton.hh
janpipek/g4application
6b063636474a7a8f212023ada7fbb60bd4439606
[ "MIT" ]
null
null
null
#ifndef SINGLETON_HH #define SINGLETON_HH #include <stdexcept> #include <cstdlib> #include <mutex> namespace g4 { namespace util { template<typename T> bool instanceExists(); /** * @short A simple, non-thread-safe singleton template. * * You have to inherit it with the class being declared as parameter. * * The creation is protected at runtime level (just one instance), * compile-time protection can be achieved by having a private * constructor in the class and making the template friend. * * The instance is automatically destroyed when the program ends. * * Inspiration: http://www.codeproject.com/Articles/4750/Singleton-Pattern-A-review-and-analysis-of-existin * * According to Alexandrescu's terminology (see Modern C++ Design), this is a create-new, * phoenix, non-thread-safe singleton. * * TODO: Check this thread-safety after the change. * * @code * class AClass : public Singleton<AClass> { }; * AClass::Instance().DoSomething(); * * class AnotherClass : public Singleton<AnotherClass> { * private: * AnotherClass() { } * friend class Singleton<AnotherClass>; * } * @endcode */ template<typename T> class Singleton { public: /** * @short Get reference to the valid instance. */ static T& Instance() { if (!_instance) { #ifdef G4MULTITHREADED _mutex.lock(); #endif if (!_instance) { _instance = new T(); } #ifdef G4MULTITHREADED _mutex.unlock(); #endif } return *_instance; } friend bool instanceExists<T>(); protected: Singleton() { if (_instance) { throw std::runtime_error("Attempt to create multiple instances of the singleton class."); } _instance = static_cast<T*>(this); // atexit(Singleton<T>::Destroy); } virtual ~Singleton() { _instance = 0; // enables further re-creation } private: Singleton(const Singleton&); Singleton& operator= (const Singleton&); static T* _instance; static void Destroy() // TODO: Reconsider using it { delete _instance; } #ifdef G4MULTITHREADED static std::mutex _mutex; #endif }; template<typename T> T* Singleton<T>::_instance = 0; #ifdef G4MULTITHREADED template<typename T> std::mutex Singleton<T>::_mutex; #endif /** * @short Is an instance of singleton class T already created? * * Defined outside the class not to spoil the class namespace. */ template<typename T> bool instanceExists() { return T::_instance != 0; } } } #endif // SINGLETON_HH
28.958333
116
0.488345
janpipek
6f1e713f595884b4d652c9ae231061b70f145424
805
hpp
C++
inc/GraphicsLib/ImGui/ImGuiImage.hpp
Sushiwave/graphics-lib
c303e9fb9f11276230a09b45581cdbefa8d2a356
[ "MIT" ]
1
2020-07-13T18:10:33.000Z
2020-07-13T18:10:33.000Z
inc/GraphicsLib/ImGui/ImGuiImage.hpp
Sushiwave/graphics-lib
c303e9fb9f11276230a09b45581cdbefa8d2a356
[ "MIT" ]
null
null
null
inc/GraphicsLib/ImGui/ImGuiImage.hpp
Sushiwave/graphics-lib
c303e9fb9f11276230a09b45581cdbefa8d2a356
[ "MIT" ]
null
null
null
#pragma once #include <GraphicsLib/Graphics/GPUResource/ShaderResource/Texture/Texture2D/Base/ITexture2D.hpp> #include <GraphicsLib/Graphics/GPUResource/RenderTarget/IRenderTarget.hpp> #include <GraphicsLib/Graphics/GPUResource/MultipleRenderTargets/IMultipleRenderTargets.hpp> #include <ThirdParty/ExtendedImGui/ImGui/imgui.h> namespace ImGui { void Image(std::shared_ptr<cg::ITexture2D> texture, const ImVec2& size); void Image(std::shared_ptr<cg::IRenderTarget> renderTarget, const ImVec2& size); void Image(std::shared_ptr<cg::IMultipleRenderTargets> mrt, int index, const ImVec2& size); void ImageDepth(std::shared_ptr<cg::IDepthStencilBuffer> depthStencilBuffer, const ImVec2& size); void ImageStencil(std::shared_ptr<cg::IDepthStencilBuffer> depthStencilBuffer, const ImVec2& size); }
40.25
100
0.81118
Sushiwave
6f2812c72819a586601a26520e68c02418434c2d
51,157
cxx
C++
libbuild2/variable.cxx
build2/build2
af662849b756ef2ff0f3d5148a6771acab78fd80
[ "MIT" ]
422
2018-05-30T12:00:00.000Z
2022-03-29T07:29:56.000Z
libbuild2/variable.cxx
build2/build2
af662849b756ef2ff0f3d5148a6771acab78fd80
[ "MIT" ]
183
2018-07-02T20:38:30.000Z
2022-03-31T09:54:35.000Z
libbuild2/variable.cxx
build2/build2
af662849b756ef2ff0f3d5148a6771acab78fd80
[ "MIT" ]
14
2019-01-09T12:34:02.000Z
2021-03-16T09:10:53.000Z
// file : libbuild2/variable.cxx -*- C++ -*- // license : MIT; see accompanying LICENSE file #include <libbuild2/variable.hxx> #include <cstring> // memcmp() #include <libbutl/path-pattern.hxx> #include <libbuild2/target.hxx> #include <libbuild2/diagnostics.hxx> using namespace std; namespace build2 { // variable_visibility // string to_string (variable_visibility v) { string r; switch (v) { case variable_visibility::global: r = "global"; break; case variable_visibility::project: r = "project"; break; case variable_visibility::scope: r = "scope"; break; case variable_visibility::target: r = "target"; break; case variable_visibility::prereq: r = "prerequisite"; break; } return r; } // value // void value:: reset () { if (type == nullptr) as<names> ().~names (); else if (type->dtor != nullptr) type->dtor (*this); null = true; } value:: value (value&& v) : type (v.type), null (v.null), extra (v.extra) { if (!null) { if (type == nullptr) new (&data_) names (move (v).as<names> ()); else if (type->copy_ctor != nullptr) type->copy_ctor (*this, v, true); else data_ = v.data_; // Copy as POD. } } value:: value (const value& v) : type (v.type), null (v.null), extra (v.extra) { if (!null) { if (type == nullptr) new (&data_) names (v.as<names> ()); else if (type->copy_ctor != nullptr) type->copy_ctor (*this, v, false); else data_ = v.data_; // Copy as POD. } } value& value:: operator= (value&& v) { if (this != &v) { // Prepare the receiving value. // if (type != v.type) { *this = nullptr; type = v.type; } // Now our types are the same. If the receiving value is NULL, then call // copy_ctor() instead of copy_assign(). // if (v) { if (type == nullptr) { if (null) new (&data_) names (move (v).as<names> ()); else as<names> () = move (v).as<names> (); } else if (auto f = null ? type->copy_ctor : type->copy_assign) f (*this, v, true); else data_ = v.data_; // Assign as POD. null = v.null; } else *this = nullptr; } return *this; } value& value:: operator= (const value& v) { if (this != &v) { // Prepare the receiving value. // if (type != v.type) { *this = nullptr; type = v.type; } // Now our types are the same. If the receiving value is NULL, then call // copy_ctor() instead of copy_assign(). // if (v) { if (type == nullptr) { if (null) new (&data_) names (v.as<names> ()); else as<names> () = v.as<names> (); } else if (auto f = null ? type->copy_ctor : type->copy_assign) f (*this, v, false); else data_ = v.data_; // Assign as POD. null = v.null; } else *this = nullptr; } return *this; } void value:: assign (names&& ns, const variable* var) { assert (type == nullptr || type->assign != nullptr); if (type == nullptr) { if (null) new (&data_) names (move (ns)); else as<names> () = move (ns); } else type->assign (*this, move (ns), var); null = false; } void value:: append (names&& ns, const variable* var) { if (type == nullptr) { if (null) new (&data_) names (move (ns)); else { names& p (as<names> ()); if (p.empty ()) p = move (ns); else if (!ns.empty ()) { p.insert (p.end (), make_move_iterator (ns.begin ()), make_move_iterator (ns.end ())); } } } else { if (type->append == nullptr) { diag_record dr (fail); dr << "cannot append to " << type->name << " value"; if (var != nullptr) dr << " in variable " << var->name; } type->append (*this, move (ns), var); } null = false; } void value:: prepend (names&& ns, const variable* var) { if (type == nullptr) { if (null) new (&data_) names (move (ns)); else { names& p (as<names> ()); if (p.empty ()) p = move (ns); else if (!ns.empty ()) { ns.insert (ns.end (), make_move_iterator (p.begin ()), make_move_iterator (p.end ())); p = move (ns); } } } else { if (type->prepend == nullptr) { diag_record dr (fail); dr << "cannot prepend to " << type->name << " value"; if (var != nullptr) dr << " in variable " << var->name; } type->prepend (*this, move (ns), var); } null = false; } bool operator== (const value& x, const value& y) { bool xn (x.null); bool yn (y.null); assert (x.type == y.type || (xn && x.type == nullptr) || (yn && y.type == nullptr)); if (xn || yn) return xn == yn; if (x.type == nullptr) return x.as<names> () == y.as<names> (); if (x.type->compare == nullptr) return memcmp (&x.data_, &y.data_, x.type->size) == 0; return x.type->compare (x, y) == 0; } bool operator< (const value& x, const value& y) { bool xn (x.null); bool yn (y.null); assert (x.type == y.type || (xn && x.type == nullptr) || (yn && y.type == nullptr)); // NULL value is always less than non-NULL. // if (xn || yn) return xn > yn; // !xn < !yn if (x.type == nullptr) return x.as<names> () < y.as<names> (); if (x.type->compare == nullptr) return memcmp (&x.data_, &y.data_, x.type->size) < 0; return x.type->compare (x, y) < 0; } bool operator> (const value& x, const value& y) { bool xn (x.null); bool yn (y.null); assert (x.type == y.type || (xn && x.type == nullptr) || (yn && y.type == nullptr)); // NULL value is always less than non-NULL. // if (xn || yn) return xn < yn; // !xn > !yn if (x.type == nullptr) return x.as<names> () > y.as<names> (); if (x.type->compare == nullptr) return memcmp (&x.data_, &y.data_, x.type->size) > 0; return x.type->compare (x, y) > 0; } void typify (value& v, const value_type& t, const variable* var, memory_order mo) { if (v.type == nullptr) { if (v) { // Note: the order in which we do things here is important. // names ns (move (v).as<names> ()); v = nullptr; // Use value_type::assign directly to delay v.type change. // t.assign (v, move (ns), var); v.null = false; } else v.type = &t; v.type.store (&t, mo); } else if (v.type != &t) { diag_record dr (fail); dr << "type mismatch"; if (var != nullptr) dr << " in variable " << var->name; dr << info << "value type is " << v.type->name; dr << info << (var != nullptr && &t == var->type ? "variable" : "new") << " type is " << t.name; } } void typify_atomic (context& ctx, value& v, const value_type& t, const variable* var) { // Typification is kind of like caching so we reuse that mutex shard. // shared_mutex& m ( ctx.mutexes.variable_cache[ hash<value*> () (&v) % ctx.mutexes.variable_cache_size]); // Note: v.type is rechecked by typify() under lock. // ulock l (m); typify (v, t, var, memory_order_release); } void untypify (value& v) { if (v.type == nullptr) return; if (v.null) { v.type = nullptr; return; } names ns; names_view nv (v.type->reverse (v, ns)); if (nv.empty () || nv.data () == ns.data ()) { // If the data is in storage, then we are all set. // ns.resize (nv.size ()); // Just to be sure. } else { // If the data is somewhere in the value itself, then steal it. // auto b (const_cast<name*> (nv.data ())); ns.assign (make_move_iterator (b), make_move_iterator (b + nv.size ())); } v = nullptr; // Free old data. v.type = nullptr; // Change type. v.assign (move (ns), nullptr); // Assign new data. } [[noreturn]] void convert_throw (const value_type* from, const value_type& to) { string m ("invalid "); m += to.name; m += " value: "; if (from != nullptr) { m += "conversion from "; m += from->name; } else m += "null"; throw invalid_argument (move (m)); } // Throw invalid_argument for an invalid simple value. // [[noreturn]] static void throw_invalid_argument (const name& n, const name* r, const char* type, bool pair_ok = false) { string m; string t (type); // Note that the message should be suitable for appending "in variable X". // if (!pair_ok && r != nullptr) m = "pair in " + t + " value"; else if (n.pattern || (r != nullptr && r->pattern)) m = "pattern in " + t + " value"; else { m = "invalid " + t + " value "; if (n.simple ()) m += "'" + n.value + "'"; else if (n.directory ()) m += "'" + n.dir.representation () + "'"; else m += "name '" + to_string (n) + "'"; } throw invalid_argument (m); } // names // const names& value_traits<names>::empty_instance = empty_names; // bool value // bool value_traits<bool>:: convert (const name& n, const name* r) { if (r == nullptr && !n.pattern && n.simple () ) { const string& s (n.value); if (s == "true") return true; if (s == "false") return false; // Fall through. } throw_invalid_argument (n, r, "bool"); } const char* const value_traits<bool>::type_name = "bool"; const value_type value_traits<bool>::value_type { type_name, sizeof (bool), nullptr, // No base. nullptr, // No element. nullptr, // No dtor (POD). nullptr, // No copy_ctor (POD). nullptr, // No copy_assign (POD). &simple_assign<bool>, &simple_append<bool>, &simple_append<bool>, // Prepend same as append. &simple_reverse<bool>, nullptr, // No cast (cast data_ directly). nullptr, // No compare (compare as POD). nullptr // Never empty. }; // int64_t value // int64_t value_traits<int64_t>:: convert (const name& n, const name* r) { if (r == nullptr && !n.pattern && n.simple ()) { try { // May throw invalid_argument or out_of_range. // size_t i; int64_t r (stoll (n.value, &i)); if (i == n.value.size ()) return r; // Fall through. } catch (const std::exception&) { // Fall through. } } throw_invalid_argument (n, r, "int64"); } const char* const value_traits<int64_t>::type_name = "int64"; const value_type value_traits<int64_t>::value_type { type_name, sizeof (int64_t), nullptr, // No base. nullptr, // No element. nullptr, // No dtor (POD). nullptr, // No copy_ctor (POD). nullptr, // No copy_assign (POD). &simple_assign<int64_t>, &simple_append<int64_t>, &simple_append<int64_t>, // Prepend same as append. &simple_reverse<int64_t>, nullptr, // No cast (cast data_ directly). nullptr, // No compare (compare as POD). nullptr // Never empty. }; // uint64_t value // uint64_t value_traits<uint64_t>:: convert (const name& n, const name* r) { if (r == nullptr && !n.pattern && n.simple ()) { try { // May throw invalid_argument or out_of_range. // size_t i; uint64_t r (stoull (n.value, &i)); if (i == n.value.size ()) return r; // Fall through. } catch (const std::exception&) { // Fall through. } } throw_invalid_argument (n, r, "uint64"); } const char* const value_traits<uint64_t>::type_name = "uint64"; const value_type value_traits<uint64_t>::value_type { type_name, sizeof (uint64_t), nullptr, // No base. nullptr, // No element. nullptr, // No dtor (POD). nullptr, // No copy_ctor (POD). nullptr, // No copy_assign (POD). &simple_assign<uint64_t>, &simple_append<uint64_t>, &simple_append<uint64_t>, // Prepend same as append. &simple_reverse<uint64_t>, nullptr, // No cast (cast data_ directly). nullptr, // No compare (compare as POD). nullptr // Never empty. }; // string value // string value_traits<string>:: convert (name&& n, name* r) { // The goal is to reverse the name into its original representation. The // code is a bit convoluted because we try to avoid extra allocations for // the common cases (unqualified, unpaired simple name or directory). // // We can only convert project-qualified simple and directory names. // if (n.pattern || !(n.simple (true) || n.directory (true))) throw_invalid_argument (n, nullptr, "string"); if (r != nullptr) { if (r->pattern || !(r->simple (true) || r->directory (true))) throw_invalid_argument (*r, nullptr, "string"); } string s; if (n.directory (true)) // Note that here we cannot assume what's in dir is really a // path (think s/foo/bar/) so we have to reverse it exactly. // s = move (n.dir).representation (); // Move out of path. else s.swap (n.value); // Convert project qualification to its string representation. // if (n.qualified ()) { string p (move (*n.proj).string ()); p += '%'; p += s; p.swap (s); } // The same for the RHS of a pair, if we have one. // if (r != nullptr) { s += '@'; if (r->qualified ()) { s += r->proj->string (); s += '%'; } if (r->directory (true)) s += move (r->dir).representation (); else s += r->value; } return s; } const string& value_traits<string>::empty_instance = empty_string; const char* const value_traits<string>::type_name = "string"; const value_type value_traits<string>::value_type { type_name, sizeof (string), nullptr, // No base. nullptr, // No element. &default_dtor<string>, &default_copy_ctor<string>, &default_copy_assign<string>, &simple_assign<string>, &simple_append<string>, &simple_prepend<string>, &simple_reverse<string>, nullptr, // No cast (cast data_ directly). &simple_compare<string>, &default_empty<string> }; // path value // path value_traits<path>:: convert (name&& n, name* r) { if (r == nullptr && !n.pattern) { // A directory path is a path. // if (n.directory ()) return move (n.dir); if (n.simple ()) { try { return path (move (n.value)); } catch (invalid_path& e) { n.value = move (e.path); // Restore the name object for diagnostics. // Fall through. } } // Reassemble split dir/value. // if (n.untyped () && n.unqualified ()) { try { return n.dir / n.value; } catch (const invalid_path&) { // Fall through. } } // Fall through. } throw_invalid_argument (n, r, "path"); } const path& value_traits<path>::empty_instance = empty_path; const char* const value_traits<path>::type_name = "path"; const value_type value_traits<path>::value_type { type_name, sizeof (path), nullptr, // No base. nullptr, // No element. &default_dtor<path>, &default_copy_ctor<path>, &default_copy_assign<path>, &simple_assign<path>, &simple_append<path>, &simple_prepend<path>, &simple_reverse<path>, nullptr, // No cast (cast data_ directly). &simple_compare<path>, &default_empty<path> }; // dir_path value // dir_path value_traits<dir_path>:: convert (name&& n, name* r) { if (r == nullptr && !n.pattern) { if (n.directory ()) return move (n.dir); if (n.simple ()) { try { return dir_path (move (n.value)); } catch (invalid_path& e) { n.value = move (e.path); // Restore the name object for diagnostics. // Fall through. } } // Reassemble split dir/value. // if (n.untyped () && n.unqualified ()) { try { n.dir /= n.value; return move (n.dir); } catch (const invalid_path&) { // Fall through. } } // Fall through. } throw_invalid_argument (n, r, "dir_path"); } const dir_path& value_traits<dir_path>::empty_instance = empty_dir_path; const char* const value_traits<dir_path>::type_name = "dir_path"; const value_type value_traits<dir_path>::value_type { type_name, sizeof (dir_path), &value_traits<path>::value_type, // Base (assuming direct cast works for // both). nullptr, // No element. &default_dtor<dir_path>, &default_copy_ctor<dir_path>, &default_copy_assign<dir_path>, &simple_assign<dir_path>, &simple_append<dir_path>, &simple_prepend<dir_path>, &simple_reverse<dir_path>, nullptr, // No cast (cast data_ directly). &simple_compare<dir_path>, &default_empty<dir_path> }; // abs_dir_path value // abs_dir_path value_traits<abs_dir_path>:: convert (name&& n, name* r) { if (r == nullptr && !n.pattern && (n.simple () || n.directory ())) { try { dir_path d (n.simple () ? dir_path (move (n.value)) : move (n.dir)); if (!d.empty ()) { if (d.relative ()) d.complete (); d.normalize (true); // Actualize. } return abs_dir_path (move (d)); } catch (const invalid_path&) {} // Fall through. } throw_invalid_argument (n, r, "abs_dir_path"); } const char* const value_traits<abs_dir_path>::type_name = "abs_dir_path"; const value_type value_traits<abs_dir_path>::value_type { type_name, sizeof (abs_dir_path), &value_traits<dir_path>::value_type, // Base (assuming direct cast works // for both). nullptr, // No element. &default_dtor<abs_dir_path>, &default_copy_ctor<abs_dir_path>, &default_copy_assign<abs_dir_path>, &simple_assign<abs_dir_path>, &simple_append<abs_dir_path>, nullptr, // No prepend. &simple_reverse<abs_dir_path>, nullptr, // No cast (cast data_ directly). &simple_compare<abs_dir_path>, &default_empty<abs_dir_path> }; // name value // name value_traits<name>:: convert (name&& n, name* r) { if (r == nullptr && !n.pattern) return move (n); throw_invalid_argument (n, r, "name"); } static names_view name_reverse (const value& v, names&) { const name& n (v.as<name> ()); return n.empty () ? names_view (nullptr, 0) : names_view (&n, 1); } const char* const value_traits<name>::type_name = "name"; const value_type value_traits<name>::value_type { type_name, sizeof (name), nullptr, // No base. nullptr, // No element. &default_dtor<name>, &default_copy_ctor<name>, &default_copy_assign<name>, &simple_assign<name>, nullptr, // Append not supported. nullptr, // Prepend not supported. &name_reverse, nullptr, // No cast (cast data_ directly). &simple_compare<name>, &default_empty<name> }; // name_pair // name_pair value_traits<name_pair>:: convert (name&& n, name* r) { if (n.pattern || (r != nullptr && r->pattern)) throw_invalid_argument (n, r, "name_pair", true /* pair_ok */); n.pair = '\0'; // Keep "unpaired" in case r is empty. return name_pair (move (n), r != nullptr ? move (*r) : name ()); } static void name_pair_assign (value& v, names&& ns, const variable* var) { using traits = value_traits<name_pair>; size_t n (ns.size ()); if (n <= 2) { try { traits::assign ( v, (n == 0 ? name_pair () : traits::convert (move (ns[0]), n == 2 ? &ns[1] : nullptr))); return; } catch (const invalid_argument&) {} // Fall through. } diag_record dr (fail); dr << "invalid name_pair value '" << ns << "'"; if (var != nullptr) dr << " in variable " << var->name; } static names_view name_pair_reverse (const value& v, names& ns) { const name_pair& p (v.as<name_pair> ()); const name& f (p.first); const name& s (p.second); if (f.empty () && s.empty ()) return names_view (nullptr, 0); if (f.empty ()) return names_view (&s, 1); if (s.empty ()) return names_view (&f, 1); ns.push_back (f); ns.back ().pair = '@'; ns.push_back (s); return ns; } const char* const value_traits<name_pair>::type_name = "name_pair"; const value_type value_traits<name_pair>::value_type { type_name, sizeof (name_pair), nullptr, // No base. nullptr, // No element. &default_dtor<name_pair>, &default_copy_ctor<name_pair>, &default_copy_assign<name_pair>, &name_pair_assign, nullptr, // Append not supported. nullptr, // Prepend not supported. &name_pair_reverse, nullptr, // No cast (cast data_ directly). &simple_compare<name_pair>, &default_empty<name_pair> }; // process_path value // template <typename T> static T process_path_convert (name&& n, name* r, const char* what) { if ( !n.pattern && n.untyped () && n.unqualified () && !n.empty () && (r == nullptr || (!r->pattern && r->untyped () && r->unqualified () && !r->empty ()))) { path rp (move (n.dir)); if (rp.empty ()) rp = path (move (n.value)); else rp /= n.value; path ep; if (r != nullptr) { ep = move (r->dir); if (ep.empty ()) ep = path (move (r->value)); else ep /= r->value; } T pp (nullptr, move (rp), move (ep)); pp.initial = pp.recall.string ().c_str (); return pp; } throw_invalid_argument (n, r, what, true /* pair_ok */); } process_path value_traits<process_path>:: convert (name&& n, name* r) { return process_path_convert<process_path> (move (n), r, "process_path"); } static void process_path_assign (value& v, names&& ns, const variable* var) { using traits = value_traits<process_path>; size_t n (ns.size ()); if (n <= 2) { try { traits::assign ( v, (n == 0 ? process_path () : traits::convert (move (ns[0]), n == 2 ? &ns[1] : nullptr))); return; } catch (const invalid_argument&) {} // Fall through. } diag_record dr (fail); dr << "invalid process_path value '" << ns << "'"; if (var != nullptr) dr << " in variable " << var->name; } template <typename T> static void process_path_copy_ctor (value& l, const value& r, bool m) { const auto& rhs (r.as<T> ()); if (m) new (&l.data_) T (move (const_cast<T&> (rhs))); else { auto& lhs ( *new (&l.data_) T ( nullptr, path (rhs.recall), path (rhs.effect))); lhs.initial = lhs.recall.string ().c_str (); } } static void process_path_copy_assign (value& l, const value& r, bool m) { auto& lhs (l.as<process_path> ()); const auto& rhs (r.as<process_path> ()); if (m) lhs = move (const_cast<process_path&> (rhs)); else { lhs.recall = rhs.recall; lhs.effect = rhs.effect; lhs.initial = lhs.recall.string ().c_str (); } } static void process_path_reverse_impl (const process_path& x, names& s) { s.push_back (name (x.recall.directory (), string (), x.recall.leaf ().string ())); if (!x.effect.empty ()) { s.back ().pair = '@'; s.push_back (name (x.effect.directory (), string (), x.effect.leaf ().string ())); } } static names_view process_path_reverse (const value& v, names& s) { const auto& x (v.as<process_path> ()); if (!x.empty ()) { s.reserve (x.effect.empty () ? 1 : 2); process_path_reverse_impl (x, s); } return s; } const char* const value_traits<process_path>::type_name = "process_path"; const value_type value_traits<process_path>::value_type { type_name, sizeof (process_path), nullptr, // No base. nullptr, // No element. &default_dtor<process_path>, &process_path_copy_ctor<process_path>, &process_path_copy_assign, &process_path_assign, nullptr, // Append not supported. nullptr, // Prepend not supported. &process_path_reverse, nullptr, // No cast (cast data_ directly). &simple_compare<process_path>, &default_empty<process_path> }; // process_path_ex value // process_path_ex value_traits<process_path_ex>:: convert (names&& ns) { if (ns.empty ()) return process_path_ex (); bool p (ns[0].pair); process_path_ex pp ( process_path_convert<process_path_ex> ( move (ns[0]), p ? &ns[1] : nullptr, "process_path_ex")); for (auto i (ns.begin () + (p ? 2 : 1)); i != ns.end (); ++i) { if (!i->pair) throw invalid_argument ("non-pair in process_path_ex value"); if (i->pattern || !i->simple ()) throw_invalid_argument (*i, nullptr, "process_path_ex"); const string& k ((i++)->value); // NOTE: see also find_end() below. // if (k == "name") { if (i->pattern || !i->simple ()) throw_invalid_argument (*i, nullptr, "process_path_ex name"); pp.name = move (i->value); } else if (k == "checksum") { if (i->pattern || !i->simple ()) throw_invalid_argument ( *i, nullptr, "process_path_ex executable checksum"); pp.checksum = move (i->value); } else if (k == "env-checksum") { if (i->pattern || !i->simple ()) throw_invalid_argument ( *i, nullptr, "process_path_ex environment checksum"); pp.env_checksum = move (i->value); } else throw invalid_argument ( "unknown key '" + k + "' in process_path_ex value"); } return pp; } names::iterator value_traits<process_path_ex>:: find_end (names& ns) { auto b (ns.begin ()), i (b), e (ns.end ()); for (i += i->pair ? 2 : 1; i != e && i->pair; i += 2) { if (!i->simple () || (i->value != "name" && i->value != "checksum" && i->value != "env-checksum")) break; } return i; } static void process_path_ex_assign (value& v, names&& ns, const variable* var) { using traits = value_traits<process_path_ex>; try { traits::assign (v, traits::convert (move (ns))); } catch (const invalid_argument& e) { // Note: ns is not guaranteed to be valid. // diag_record dr (fail); dr << "invalid process_path_ex value"; if (var != nullptr) dr << " in variable " << var->name; dr << ": " << e; } } static void process_path_ex_copy_ex (value& l, const value& r, bool m) { auto& lhs (l.as<process_path_ex> ()); if (m) { const auto& rhs (const_cast<value&> (r).as<process_path_ex> ()); lhs.name = move (rhs.name); lhs.checksum = move (rhs.checksum); lhs.env_checksum = move (rhs.env_checksum); } else { const auto& rhs (r.as<process_path_ex> ()); lhs.name = rhs.name; lhs.checksum = rhs.checksum; lhs.env_checksum = rhs.env_checksum; } } static void process_path_ex_copy_ctor (value& l, const value& r, bool m) { process_path_copy_ctor<process_path_ex> (l, r, m); if (!m) process_path_ex_copy_ex (l, r, false); } static void process_path_ex_copy_assign (value& l, const value& r, bool m) { process_path_copy_assign (l, r, m); process_path_ex_copy_ex (l, r, m); } static names_view process_path_ex_reverse (const value& v, names& s) { const auto& x (v.as<process_path_ex> ()); if (!x.empty ()) { s.reserve ((x.effect.empty () ? 1 : 2) + (x.name ? 2 : 0) + (x.checksum ? 2 : 0) + (x.env_checksum ? 2 : 0)); process_path_reverse_impl (x, s); if (x.name) { s.push_back (name ("name")); s.back ().pair = '@'; s.push_back (name (*x.name)); } if (x.checksum) { s.push_back (name ("checksum")); s.back ().pair = '@'; s.push_back (name (*x.checksum)); } if (x.env_checksum) { s.push_back (name ("env-checksum")); s.back ().pair = '@'; s.push_back (name (*x.env_checksum)); } } return s; } const char* const value_traits<process_path_ex>::type_name = "process_path_ex"; const value_type value_traits<process_path_ex>::value_type { type_name, sizeof (process_path_ex), &value_traits< // Base (assuming direct cast works process_path>::value_type, // for both). nullptr, // No element. &default_dtor<process_path_ex>, &process_path_ex_copy_ctor, &process_path_ex_copy_assign, &process_path_ex_assign, nullptr, // Append not supported. nullptr, // Prepend not supported. &process_path_ex_reverse, nullptr, // No cast (cast data_ directly). &simple_compare<process_path>, // For now compare as process_path. &default_empty<process_path_ex> }; // target_triplet value // target_triplet value_traits<target_triplet>:: convert (name&& n, name* r) { if (r == nullptr && !n.pattern && n.simple ()) { try { return n.empty () ? target_triplet () : target_triplet (n.value); } catch (const invalid_argument& e) { throw invalid_argument ( string ("invalid target_triplet value: ") + e.what ()); } } throw_invalid_argument (n, r, "target_triplet"); } const char* const value_traits<target_triplet>::type_name = "target_triplet"; const value_type value_traits<target_triplet>::value_type { type_name, sizeof (target_triplet), nullptr, // No base. nullptr, // No element. &default_dtor<target_triplet>, &default_copy_ctor<target_triplet>, &default_copy_assign<target_triplet>, &simple_assign<target_triplet>, nullptr, // Append not supported. nullptr, // Prepend not supported. &simple_reverse<target_triplet>, nullptr, // No cast (cast data_ directly). &simple_compare<target_triplet>, &default_empty<target_triplet> }; // project_name value // project_name value_traits<project_name>:: convert (name&& n, name* r) { if (r == nullptr && !n.pattern && n.simple ()) { try { return n.empty () ? project_name () : project_name (move (n.value)); } catch (const invalid_argument& e) { throw invalid_argument ( string ("invalid project_name value: ") + e.what ()); } } throw_invalid_argument (n, r, "project_name"); } const project_name& value_traits<project_name>::empty_instance = empty_project_name; const char* const value_traits<project_name>::type_name = "project_name"; const value_type value_traits<project_name>::value_type { type_name, sizeof (project_name), nullptr, // No base. nullptr, // No element. &default_dtor<project_name>, &default_copy_ctor<project_name>, &default_copy_assign<project_name>, &simple_assign<project_name>, nullptr, // Append not supported. nullptr, // Prepend not supported. &simple_reverse<project_name>, nullptr, // No cast (cast data_ directly). &simple_compare<project_name>, &default_empty<project_name> }; // variable_pool // void variable_pool:: update (variable& var, const build2::value_type* t, const variable_visibility* v, const bool* o) const { // Check overridability (all overrides, if any, should already have // been entered; see context ctor for details). // if (o != nullptr && var.overrides != nullptr && !*o) fail << "variable " << var.name << " cannot be overridden"; bool ut (t != nullptr && var.type != t); bool uv (v != nullptr && var.visibility != *v); // Variable should not be updated post-aliasing. // assert (var.aliases == &var || (!ut && !uv)); // Update type? // if (ut) { assert (var.type == nullptr); var.type = t; } // Change visibility? While this might at first seem like a bad idea, it // can happen that the variable lookup happens before any values were set // in which case the variable will be entered with the default (project) // visibility. // // For example, a buildfile, for some reason, could reference a target- // specific variable (say, test) before loading a module (say, test) that // sets this visibility. While strictly speaking we could have potentially // already made a lookup using the wrong visibility, presumably this // should be harmless. // // @@ But consider a situation where this test is set on scope prior to // loading the module: now this value will effectively be unreachable // without any diagnostics. So maybe we should try to clean this up. // But we will need proper diagnostics instead of assert (which means // we would probably need to track the location where the variable // was first entered). // // Note also that this won't work well for global visibility since we only // allow restrictions. The thinking is that global visibility is special // and requiring special arrangements (like variable patterns, similar to // how we've done it for config.*) is reasonable. In fact, it feels like // only the build system core should be allowed to use global visibility // (see the context ctor for details). // if (uv) { assert (*v > var.visibility); var.visibility = *v; } } static bool match_pattern (const string& n, const string& p, const string& s, bool multi) { size_t nn (n.size ()), pn (p.size ()), sn (s.size ()); if (nn < pn + sn + 1) return false; if (pn != 0) { if (n.compare (0, pn, p) != 0) return false; } if (sn != 0) { if (n.compare (nn - sn, sn, s) != 0) return false; } // Make sure the stem is a single name unless instructed otherwise. // return multi || string::traits_type::find (n.c_str () + pn, nn - pn - sn, '.') == nullptr; } static inline void merge_pattern (const variable_pool::pattern& p, const build2::value_type*& t, const variable_visibility*& v, const bool*& o) { if (p.type) { if (t == nullptr) t = *p.type; else if (p.match) assert (t == *p.type); } if (p.visibility) { if (v == nullptr) v = &*p.visibility; else if (p.match) { // Allow the pattern to restrict but not relax. // if (*p.visibility > *v) v = &*p.visibility; else assert (*v == *p.visibility); } } if (p.overridable) { if (o == nullptr) o = &*p.overridable; else if (p.match) { // Allow the pattern to restrict but not relax. // if (*o) o = &*p.overridable; else assert (*o == *p.overridable); } } } pair<variable&, bool> variable_pool:: insert (string n, const build2::value_type* t, const variable_visibility* v, const bool* o, bool pat) { assert (!global_ || global_->phase == run_phase::load); // Apply pattern. // const pattern* pa (nullptr); auto pt (t); auto pv (v); auto po (o); if (pat) { if (n.find ('.') != string::npos) { // Reverse means from the "largest" (most specific). // for (const pattern& p: reverse_iterate (patterns_)) { if (match_pattern (n, p.prefix, p.suffix, p.multi)) { merge_pattern (p, pt, pv, po); pa = &p; break; } } } } auto r ( insert ( variable { move (n), nullptr, pt, nullptr, pv != nullptr ? *pv : variable_visibility::project})); variable& var (r.first->second); if (r.second) var.aliases = &var; else // Note: overridden variable will always exist. { // This is tricky: if the pattern does not require a match, then we // should re-merge it with values that came from the variable. // bool vo; if (pa != nullptr && !pa->match) { pt = t != nullptr ? t : var.type; pv = v != nullptr ? v : &var.visibility; po = o != nullptr ? o : &(vo = true); merge_pattern (*pa, pt, pv, po); } if (po == nullptr) // NULL overridable falls back to false. po = &(vo = false); update (var, pt, pv, po); // Not changing the key. } return pair<variable&, bool> (var, r.second); } const variable& variable_pool:: insert_alias (const variable& var, string n) { assert (var.aliases != nullptr && var.overrides == nullptr); variable& a (insert (move (n), var.type, &var.visibility, nullptr /* override */, false /* pattern */).first); assert (a.overrides == nullptr); if (a.aliases == &a) // Not aliased yet. { a.aliases = var.aliases; const_cast<variable&> (var).aliases = &a; } else assert (a.alias (var)); // Make sure it is already an alias of var. return a; } void variable_pool:: insert_pattern (const string& p, optional<const value_type*> t, optional<bool> o, optional<variable_visibility> v, bool retro, bool match) { assert (!global_ || global_->phase == run_phase::load); size_t pn (p.size ()); size_t w (p.find ('*')); assert (w != string::npos); bool multi (w + 1 != pn && p[w + 1] == '*'); // Extract prefix and suffix. // string pfx, sfx; if (w != 0) { assert (p[w - 1] == '.' && w != 1); pfx.assign (p, 0, w); } w += multi ? 2 : 1; // First suffix character. size_t sn (pn - w); // Suffix length. if (sn != 0) { assert (p[w] == '.' && sn != 1); sfx.assign (p, w, sn); } auto i ( patterns_.insert ( pattern {move (pfx), move (sfx), multi, match, t, v, o})); // Apply retrospectively to existing variables. // if (retro) { for (auto& p: map_) { variable& var (p.second); if (match_pattern (var.name, i->prefix, i->suffix, i->multi)) { // Make sure that none of the existing more specific patterns // match. // auto j (i), e (patterns_.end ()); for (++j; j != e; ++j) { if (match_pattern (var.name, j->prefix, j->suffix, j->multi)) break; } if (j == e) update (var, t ? *t : nullptr, v ? &*v : nullptr, o ? &*o : nullptr); // Not changing the key. } } } } // variable_map // const variable_map empty_variable_map (nullptr /* context */); auto variable_map:: lookup (const variable& var, bool typed, bool aliased) const -> pair<const value_data*, const variable&> { const variable* v (&var); const value_data* r (nullptr); do { // @@ Should we verify that there are no distinct values for aliases? // This can happen if the values were entered before the variables // were aliased. Possible but probably highly unlikely. // auto i (m_.find (*v)); if (i != m_.end ()) { r = &i->second; break; } if (aliased) v = v->aliases; } while (v != &var && v != nullptr); // Check if this is the first access after being assigned a type. // if (r != nullptr && typed && v->type != nullptr) typify (*r, *v); return pair<const value_data*, const variable&> ( r, r != nullptr ? *v : var); } auto variable_map:: lookup_to_modify (const variable& var, bool typed) -> pair<value_data*, const variable&> { auto p (lookup (var, typed)); auto* r (const_cast<value_data*> (p.first)); if (r != nullptr) r->version++; return pair<value_data*, const variable&> (r, p.second); } pair<value&, bool> variable_map:: insert (const variable& var, bool typed) { assert (!global_ || ctx->phase == run_phase::load); auto p (m_.emplace (var, value_data (typed ? var.type : nullptr))); value_data& r (p.first->second); if (!p.second) { // Check if this is the first access after being assigned a type. // // Note: we still need atomic in case this is not a global state. // if (typed && var.type != nullptr) typify (r, var); } r.version++; return pair<value&, bool> (r, p.second); } bool variable_map:: erase (const variable& var) { assert (!global_ || ctx->phase == run_phase::load); return m_.erase (var) != 0; } // variable_pattern_map // variable_map& variable_pattern_map:: insert (pattern_type type, string&& text) { auto r (map_.emplace (pattern {type, false, move (text), {}}, variable_map (ctx, global_))); // Compile the regex. // if (r.second && type == pattern_type::regex_pattern) { // On exception restore the text argument (so that it's available for // diagnostics) and remove the element from the map. // auto eg (make_exception_guard ( [&text, &r, this] () { text = r.first->first.text; map_.erase (r.first); })); const string& t (r.first->first.text); size_t n (t.size ()), p (t.rfind (t[0])); // Convert flags. // regex::flag_type f (regex::ECMAScript); for (size_t i (p + 1); i != n; ++i) { switch (t[i]) { case 'i': f |= regex::icase; break; case 'e': r.first->first.match_ext = true; break; } } // Skip leading delimiter as well as trailing delimiter and flags. // r.first->first.regex = regex (t.c_str () + 1, p - 1, f); } return r.first->second; } // variable_type_map // lookup variable_type_map:: find (const target_key& tk, const variable& var, optional<string>& oname) const { // Compute and cache "effective" name that we will be matching. // // See also the additional match_ext logic below. // auto name = [&tk, &oname] () -> const string& { if (!oname) { const target_type& tt (*tk.type); // Note that if the name is not empty, then we always use that, even // if the type is dir/fsdir. // if (tk.name->empty () && (tt.is_a<dir> () || tt.is_a<fsdir> ())) { oname = tk.dir->leaf ().string (); } // If we have the extension and the type expects the extension to be // always specified explicitly by the user, then add it to the name. // // Overall, we have the following cases: // // 1. Extension is fixed: man1{}. // // 2. Extension is always specified by the user: file{}. // // 3. Default extension that may be overridden by the user: hxx{}. // // 4. Extension assigned by the rule but may be overridden by the // user: obje{}. // // By default we only match the extension for (2). // else if (tk.ext && !tk.ext->empty () && (tt.fixed_extension == &target_extension_none || tt.fixed_extension == &target_extension_must)) { oname = *tk.name + '.' + *tk.ext; } else oname = string (); // Use tk.name as is. } return oname->empty () ? *tk.name : *oname; }; // Search across target type hierarchy. // for (auto tt (tk.type); tt != nullptr; tt = tt->base) { auto i (map_.find (*tt)); if (i == end ()) continue; // Try to match the pattern, starting from the longest values. // const variable_pattern_map& m (i->second); for (auto j (m.rbegin ()); j != m.rend (); ++j) { using pattern = variable_pattern_map::pattern; using pattern_type = variable_pattern_map::pattern_type; const pattern& pat (j->first); bool r, e (false); if (pat.type == pattern_type::path) { r = pat.text == "*" || butl::path_match (name (), pat.text); } else { const string& n (name ()); // Deal with match_ext: first see if the extension would be added by // default. If not, then temporarily add it in oname and then clean // it up if there is no match (to prevent another pattern from using // it). While we may keep adding it if there are multiple patterns // with such a flag, we will at least reuse the buffer in oname. // e = pat.match_ext && tk.ext && !tk.ext->empty () && oname->empty (); if (e) { *oname = *tk.name; *oname += '.'; *oname += *tk.ext; } r = regex_match (e ? *oname : n, *pat.regex); } // Ok, this pattern matches. But is there a variable? // // Since we store append/prepend values untyped, instruct find() not // to automatically type it. And if it is assignment, then typify it // ourselves. // if (r) { const variable_map& vm (j->second); auto p (vm.lookup (var, false)); if (const variable_map::value_data* v = p.first) { // Check if this is the first access after being assigned a type. // if (v->extra == 0 && var.type != nullptr) vm.typify (*v, var); // Make sure the effective name is computed if this is // append/prepend (it is used as a cache key). // if (v->extra != 0 && !oname) name (); return lookup (*v, p.second, vm); } } if (e) oname->clear (); } } return lookup (); } template struct LIBBUILD2_DEFEXPORT value_traits<strings>; template struct LIBBUILD2_DEFEXPORT value_traits<vector<name>>; template struct LIBBUILD2_DEFEXPORT value_traits<paths>; template struct LIBBUILD2_DEFEXPORT value_traits<dir_paths>; template struct LIBBUILD2_DEFEXPORT value_traits<int64s>; template struct LIBBUILD2_DEFEXPORT value_traits<uint64s>; template struct LIBBUILD2_DEFEXPORT value_traits<vector<pair<string, string>>>; template struct LIBBUILD2_DEFEXPORT value_traits<vector<pair<string, optional<string>>>>; template struct LIBBUILD2_DEFEXPORT value_traits<vector<pair<optional<string>, string>>>; template struct LIBBUILD2_DEFEXPORT value_traits<vector<pair<string, optional<bool>>>>; template struct LIBBUILD2_DEFEXPORT value_traits<map<string, string>>; template struct LIBBUILD2_DEFEXPORT value_traits<map<string, optional<string>>>; template struct LIBBUILD2_DEFEXPORT value_traits<map<optional<string>, string>>; template struct LIBBUILD2_DEFEXPORT value_traits<map<string, optional<bool>>>; template struct LIBBUILD2_DEFEXPORT value_traits<map<project_name, dir_path>>; }
25.425944
94
0.523487
build2
6f285d643ccafd41d15127989f6c9aa7e022512d
243
cpp
C++
Day 15/Q.2]/RAO.cpp
gopalshendge18/Practice-Question
c0dfefb4b6d7c3c5344d09b23d311f07a4444149
[ "MIT" ]
1
2022-01-03T14:04:26.000Z
2022-01-03T14:04:26.000Z
Day 15/Q.2]/RAO.cpp
gopalshendge18/Practice-Question
c0dfefb4b6d7c3c5344d09b23d311f07a4444149
[ "MIT" ]
null
null
null
Day 15/Q.2]/RAO.cpp
gopalshendge18/Practice-Question
c0dfefb4b6d7c3c5344d09b23d311f07a4444149
[ "MIT" ]
8
2021-11-03T04:12:17.000Z
2021-12-11T09:28:54.000Z
class Solution { public: void moveZeroes(vector<int>& A) { int num = 0; for(int i=0; i<A.size(); i++){ if(A[i]!=0) A[num++] = A[i]; } while(num<A.size()) A[num++] = 0; } };
18.692308
41
0.386831
gopalshendge18
6f2a0a323650e354c611b51725880cc698fbda16
901
cpp
C++
topic_wise/backtracking/subsets.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
1
2021-01-27T16:37:36.000Z
2021-01-27T16:37:36.000Z
topic_wise/backtracking/subsets.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
topic_wise/backtracking/subsets.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
/** * @author : archit * @GitHub : archit-1997 * @email : [email protected] * @file : subsets.cpp * @created : Wednesday Jul 28, 2021 12:47:45 IST */ #include <bits/stdc++.h> using namespace std; class Solution { public: void findSubsets(vector<vector<int>> &ans,vector<int> tmp,int index,vector<int> &nums){ //if we have reached the last index if(index==nums.size()){ ans.push_back(tmp); return; } //exclude this element findSubsets(ans,tmp,index+1,nums); //include the element at index tmp.push_back(nums[index]); findSubsets(ans,tmp,index+1,nums); } vector<vector<int>> subsets(vector<int>& nums) { int n=nums.size(); vector<vector<int>> ans; vector<int> tmp; findSubsets(ans,tmp,0,nums); return ans; } };
23.102564
91
0.564928
archit-1997
6f2fdd220abe67337e0a805327cedbdda42266f8
1,830
cpp
C++
src/GameState/PhysicalObject/Enemies/Enemy.cpp
Heaven31415/SpaceShooter
385e43aa2deb8720c1b0a23834ad31de97fd25eb
[ "Zlib" ]
null
null
null
src/GameState/PhysicalObject/Enemies/Enemy.cpp
Heaven31415/SpaceShooter
385e43aa2deb8720c1b0a23834ad31de97fd25eb
[ "Zlib" ]
null
null
null
src/GameState/PhysicalObject/Enemies/Enemy.cpp
Heaven31415/SpaceShooter
385e43aa2deb8720c1b0a23834ad31de97fd25eb
[ "Zlib" ]
null
null
null
#include "Enemy.hpp" #include "../../../Game.hpp" #include "../../../Common/Randomizer.hpp" Enemy::Enemy(Context& context, World& world, LaserFactory& laserFactory) : PhysicalObject(context, world, Type::Enemy, context.textures.get("EnemyShip")) , m_laserFactory(laserFactory) , m_manager(nullptr) { setVelocity({0.f, 0.f}); setMaxVelocity(Game::Config.enemySpeed); /* for now, they doesn't use configuration for their health setMaxHealth(Game::Config.enemyHealth); setHealth(getMaxHealth()); */ centerOrigin(); // this shouldn't be here sf::Vector2f mapSize = static_cast<sf::Vector2f>(Game::Config.windowSize); sf::Vector2f position = { Random::Real(1.f / 10.f * mapSize.x, 9.f / 10.f * mapSize.x), Random::Real(-mapSize.y / 10, 0.f) }; setPosition(position); } void Enemy::collision(PhysicalObject* object) { if (object->getType() == Type::Player) { object->takeDamage(1); takeDamage(1); } getContext().soundSystem.playSound("Explosion"); } void Enemy::update(sf::Time dt) { Object::update(dt); if (!isDestroyed() && m_manager) m_manager->update(this, dt); } void Enemy::changeState(unsigned state) { if(m_manager) m_manager->changeState(state); } void Enemy::addLaser() { auto laser = m_laserFactory.build("enemyLaser"); laser->setOwner(getGUID()); laser->setPosition(getPosition()); addChild(laser->getGUID()); getWorld().add(std::move(laser)); } std::size_t Enemy::countLasers() { std::size_t count = 0; for (auto& child : m_children) { auto* object = getWorld().getObject(child); if (object && object->getType() == Type::EnemyWeapon) count++; } return count; } void Enemy::setAI(EnemyStateManager::Ptr manager) { m_manager.swap(manager); }
24.72973
129
0.644809
Heaven31415
6f3253248ac38b5e8fdff4ca2f25591258362cbb
5,685
cc
C++
tc/core/polyhedral/reduction_matcher.cc
abdullah1908/TensorComprehensions
90360b9290244ff96f8a89d5311dc75981f70bb7
[ "Apache-2.0" ]
1
2021-08-28T17:59:20.000Z
2021-08-28T17:59:20.000Z
tc/core/polyhedral/reduction_matcher.cc
abdullah1908/TensorComprehensions
90360b9290244ff96f8a89d5311dc75981f70bb7
[ "Apache-2.0" ]
null
null
null
tc/core/polyhedral/reduction_matcher.cc
abdullah1908/TensorComprehensions
90360b9290244ff96f8a89d5311dc75981f70bb7
[ "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2017-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "tc/core/polyhedral/schedule_tree_matcher.h" #include <unordered_set> #include "tc/core/polyhedral/cuda/mapped_scop.h" #include "tc/core/polyhedral/schedule_tree.h" #include "tc/core/polyhedral/scop.h" #include "tc/external/isl.h" namespace tc { namespace polyhedral { using detail::ScheduleTree; using detail::ScheduleTreeElemBand; using detail::ScheduleTreeElemFilter; namespace { /* * Does the given statement perform a supported type of reduction? * Only addition is supported for now since it is not clear * if other types are supported by the CUB reduction wrapper. */ bool isSupportedReduction(Halide::Internal::Stmt stmt) { auto provide = stmt.as<Halide::Internal::Provide>(); auto call = provide->values[0].as<Halide::Internal::Call>(); if (call && call->args[0].as<Halide::Internal::Add>()) { return true; } return false; } // TODO: the function currently available in Scop only works _after_ inserting // the reduction. that is a kind of internal state dependence we want to avoid // If id is the statement identifier of an update statement // of a supported type of reduction, // then return the corresponding init statement in init and // the corresponding reduction dimensions in reductionDims. bool isReductionUpdateId( isl::id id, const Scop& scop, Halide::Internal::Stmt& init, std::vector<size_t>& reductionDims) { CHECK_EQ(scop.halide.statements.count(id), 1u) << "id is not a statement in scop" << id; auto provideNode = scop.halide.statements.at(id); if (!isSupportedReduction(provideNode)) { return false; } for (auto const& iup : scop.halide.reductions) { if (iup.update.same_as(provideNode)) { init = iup.init; reductionDims = iup.dims; return true; } } return false; } /* * Does "aff" only involve the specified input dimension (and not * any other input dimensions). */ bool pwAffInvolvesOnlyInputDim(isl::pw_aff pa, int redDimIdx) { auto space = pa.get_space(); if (!pa.involves_dims(isl::dim_type::in, redDimIdx, 1)) { return false; } if (pa.involves_dims(isl::dim_type::in, 0, redDimIdx) || pa.involves_dims( isl::dim_type::in, redDimIdx + 1, space.dim(isl::dim_type::in) - redDimIdx - 1)) { return false; } return true; } // Does pa have the form S(...) -> [(K*r)] where S is either a reduction init // or update statement and r is a known reduction loop in Scop? // // FIXME: now, K can be any value, including nested integer divisions, to // support detection after tiling; tighten this. bool isAlmostIdentityReduction(isl::pw_aff pa, const Scop& scop) { auto space = pa.get_space(); if (!space.has_tuple_id(isl::dim_type::in)) { return false; } auto stmtId = space.get_tuple_id(isl::dim_type::in); Halide::Internal::Stmt init; std::vector<size_t> reductionDims; if (!isReductionUpdateId(stmtId, scop, init, reductionDims)) { return false; } for (auto redDimIdx : reductionDims) { if (pwAffInvolvesOnlyInputDim(pa, redDimIdx)) { return true; } } return false; } /* * Return the identifier that maps to "stmt". */ isl::id statementId(const Scop& scop, const Halide::Internal::Stmt& stmt) { for (auto kvp : scop.halide.statements) { if (kvp.second.same_as(stmt)) { return kvp.first; } } CHECK(false) << "no id recorded for statement" << stmt; return isl::id(); } } // namespace std::pair<isl::union_set, isl::union_set> reductionInitsUpdates( isl::union_set domain, const Scop& scop) { auto initUnion = isl::union_set::empty(domain.get_space()); auto update = initUnion; std::unordered_set<isl::id, isl::IslIdIslHash> init; std::vector<isl::set> nonUpdate; // First collect all the update statements, // the corresponding init statement and all non-update statements. domain.foreach_set([&init, &update, &nonUpdate, &scop](isl::set set) { auto setId = set.get_tuple_id(); Halide::Internal::Stmt initStmt; std::vector<size_t> reductionDims; if (isReductionUpdateId(setId, scop, initStmt, reductionDims)) { update = update.unite(set); init.emplace(statementId(scop, initStmt)); } else { nonUpdate.emplace_back(set); } }); // Then check if all the non-update statements are init statements // that correspond to the update statements found. // If not, return an empty list of update statements. for (auto set : nonUpdate) { if (init.count(set.get_tuple_id()) != 1) { return std::pair<isl::union_set, isl::union_set>( initUnion, isl::union_set::empty(domain.get_space())); } initUnion = initUnion.unite(set); } return std::pair<isl::union_set, isl::union_set>(initUnion, update); } bool isReductionMember( isl::union_pw_aff member, isl::union_set domain, const Scop& scop) { return domain.every_set([member, &scop](isl::set set) { auto pa = member.extract_on_domain(set.get_space()); return isAlmostIdentityReduction(pa, scop); }); } } // namespace polyhedral } // namespace tc
31.236264
79
0.692876
abdullah1908
6f36ba3779fc499e30c0d77e201cc4ead021382f
1,621
cpp
C++
command.cpp
KonradCzerw/portal2util
07bd8fbafe887bed35b076434a899db6444f901d
[ "MIT" ]
null
null
null
command.cpp
KonradCzerw/portal2util
07bd8fbafe887bed35b076434a899db6444f901d
[ "MIT" ]
null
null
null
command.cpp
KonradCzerw/portal2util
07bd8fbafe887bed35b076434a899db6444f901d
[ "MIT" ]
null
null
null
#include <command.hpp> #include <utils.hpp> #include <tier1.hpp> std::vector<Command*>& Command::GetList() { static std::vector<Command*> list; return list; } Command::Command() : ptr(nullptr), version(0), isRegistered(false), isReference(false) {} Command::~Command() { if(!this->isReference) SAFE_DELETE(this->ptr); } ConCommand* Command::ThisPtr() { return this->ptr; } Command::Command(const char *name) { this->ptr = reinterpret_cast<ConCommand *>(tier1->FindCommandBase(tier1->g_pCVar->ThisPtr(), name)); this->isReference = true; } Command::Command(const char* pName, _CommandCallback callback, const char* pHelpString, int flags, _CommandCompletionCallback completionFunc) : version(0), isRegistered(false), isReference(false) { this->ptr = new ConCommand(pName, callback, pHelpString, flags, completionFunc); Command::GetList().push_back(this); } void Command::Register() { if(!this->isRegistered) { this->ptr->ConCommandBase_VTable = tier1->ConCommand_VTable; tier1->RegisterConCommand(tier1->g_pCVar->ThisPtr(), this->ptr); tier1->m_pConCommandList = this->ptr; } this->isRegistered = true; } void Command::Unregister() { if(this->isRegistered) { tier1->UnregisterConCommand(tier1->g_pCVar->ThisPtr(), this->ptr); } this->isRegistered = false; } bool Command::operator!() { return this->ptr == nullptr; } int Command::RegisterAll() { auto result = 0; for(const auto& command : Command::GetList()) { command->Register(); ++result; } return result; } void Command::UnregisterAll() { for(const auto& command : Command::GetList()) { command->Unregister(); } }
21.905405
143
0.705737
KonradCzerw
6f3dd367e6ef4ffc34e6c37a711ee907ac0db512
20,019
cc
C++
ncrack/timing.cc
Adam-K-P/dwm
7a95bb7e68abe713c4fd45809897ab19b33e65f7
[ "MIT" ]
null
null
null
ncrack/timing.cc
Adam-K-P/dwm
7a95bb7e68abe713c4fd45809897ab19b33e65f7
[ "MIT" ]
null
null
null
ncrack/timing.cc
Adam-K-P/dwm
7a95bb7e68abe713c4fd45809897ab19b33e65f7
[ "MIT" ]
null
null
null
/*************************************************************************** * timing.cc -- Functions related to computing crack timing and keeping * * track of rates. * * * ***********************IMPORTANT NMAP LICENSE TERMS************************ * * * The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is * * also a registered trademark of Insecure.Com LLC. This program is free * * software; you may redistribute and/or modify it under the terms of the * * GNU General Public License as published by the Free Software * * Foundation; Version 2 with the clarifications and exceptions described * * below. This guarantees your right to use, modify, and redistribute * * this software under certain conditions. If you wish to embed Nmap * * technology into proprietary software, we sell alternative licenses * * (contact [email protected]). Dozens of software vendors already * * license Nmap technology such as host discovery, port scanning, OS * * detection, and version detection. * * * * Note that the GPL places important restrictions on "derived works", yet * * it does not provide a detailed definition of that term. To avoid * * misunderstandings, we consider an application to constitute a * * "derivative work" for the purpose of this license if it does any of the * * following: * * o Integrates source code from Nmap * * o Reads or includes Nmap copyrighted data files, such as * * nmap-os-db or nmap-service-probes. * * o Executes Nmap and parses the results (as opposed to typical shell or * * execution-menu apps, which simply display raw Nmap output and so are * * not derivative works.) * * o Integrates/includes/aggregates Nmap into a proprietary executable * * installer, such as those produced by InstallShield. * * o Links to a library or executes a program that does any of the above * * * * The term "Nmap" should be taken to also include any portions or derived * * works of Nmap. This list is not exclusive, but is meant to clarify our * * interpretation of derived works with some common examples. Our * * interpretation applies only to Nmap--we don't speak for other people's * * GPL works. * * * * If you have any questions about the GPL licensing restrictions on using * * Nmap in non-GPL works, we would be happy to help. As mentioned above, * * we also offer alternative license to integrate Nmap into proprietary * * applications and appliances. These contracts have been sold to dozens * * of software vendors, and generally include a perpetual license as well * * as providing for priority support and updates as well as helping to * * fund the continued development of Nmap technology. Please email * * [email protected] for further information. * * * * As a special exception to the GPL terms, Insecure.Com LLC grants * * permission to link the code of this program with any version of the * * OpenSSL library which is distributed under a license identical to that * * listed in the included docs/licenses/OpenSSL.txt file, and distribute * * linked combinations including the two. You must obey the GNU GPL in all * * respects for all of the code used other than OpenSSL. If you modify * * this file, you may extend this exception to your version of the file, * * but you are not obligated to do so. * * * * If you received these files with a written license agreement or * * contract stating terms other than the terms above, then that * * alternative license agreement takes precedence over these comments. * * * * Source is provided to this software because we believe users have a * * right to know exactly what a program is going to do before they run it. * * This also allows you to audit the software for security holes (none * * have been found so far). * * * * Source code also allows you to port Nmap to new platforms, fix bugs, * * and add new features. You are highly encouraged to send your changes * * to [email protected] for possible incorporation into the main * * distribution. By sending these changes to Fyodor or one of the * * Insecure.Org development mailing lists, it is assumed that you are * * offering the Nmap Project (Insecure.Com LLC) the unlimited, * * non-exclusive right to reuse, modify, and relicense the code. Nmap * * will always be available Open Source, but this is important because the * * inability to relicense code has caused devastating problems for other * * Free Software projects (such as KDE and NASM). We also occasionally * * relicense the code to third parties as discussed above. If you wish to * * specify special license conditions of your contributions, just say so * * when you send them. * * * * This program is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * General Public License v2.0 for more details at * * http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file * * included with Nmap. * * * ***************************************************************************/ /* $Id: timing.cc 12955 2009-04-15 00:37:03Z fyodor $ */ #include "timing.h" #include "NcrackOps.h" #include "utils.h" #include "time.h" extern NcrackOps o; /* current_rate_history defines how far back (in seconds) we look when calculating the current rate. */ RateMeter::RateMeter(double current_rate_history) { this->current_rate_history = current_rate_history; start_tv.tv_sec = 0; start_tv.tv_usec = 0; stop_tv.tv_sec = 0; stop_tv.tv_usec = 0; last_update_tv.tv_sec = 0; last_update_tv.tv_usec = 0; total = 0.0; current_rate = 0.0; assert(!isSet(&start_tv)); assert(!isSet(&stop_tv)); } void RateMeter::start(const struct timeval *now) { assert(!isSet(&start_tv)); assert(!isSet(&stop_tv)); if (now == NULL) gettimeofday(&start_tv, NULL); else start_tv = *now; } void RateMeter::stop(const struct timeval *now) { assert(isSet(&start_tv)); assert(!isSet(&stop_tv)); if (now == NULL) gettimeofday(&stop_tv, NULL); else stop_tv = *now; } /* Update the rates to reflect the given amount added to the total at the time now. If now is NULL, get the current time with gettimeofday. */ void RateMeter::update(double amount, const struct timeval *now) { struct timeval tv; double diff; double interval; double count; assert(isSet(&start_tv)); assert(!isSet(&stop_tv)); /* Update the total. */ total += amount; if (now == NULL) { gettimeofday(&tv, NULL); now = &tv; } if (!isSet(&last_update_tv)) last_update_tv = start_tv; /* Calculate the approximate moving average of how much was recorded in the last current_rate_history seconds. This average is what is returned as the "current" rate. */ /* How long since the last update? */ diff = TIMEVAL_SUBTRACT(*now, last_update_tv) / 1000000.0; if (diff < -current_rate_history) /* This happened farther in the past than we care about. */ return; if (diff < 0.0) { /* If the event happened in the past, just add it into the total and don't change last_update_tv, as if it had happened at the same time as the most recent event. */ now = &last_update_tv; diff = 0.0; } /* Find out how far back in time to look. We want to look back current_rate_history seconds, or to when the last update occurred, whichever is longer. However, we never look past the start. */ struct timeval tmp; /* Find the time current_rate_history seconds after the start. That's our threshold for deciding how far back to look. */ TIMEVAL_ADD(tmp, start_tv, (time_t) (current_rate_history * 1000000.0)); if (TIMEVAL_AFTER(*now, tmp)) interval = MAX(current_rate_history, diff); else interval = TIMEVAL_SUBTRACT(*now, start_tv) / 1000000.0; assert(diff <= interval); /* If we record an amount in the very same instant that the timer is started, there's no way to calculate meaningful rates. Ignore it. */ if (interval == 0.0) return; /* To calculate the approximate average of the rate over the last interval seconds, we assume that the rate was constant over that interval. We calculate how much would have been received in that interval, ignoring the first diff seconds' worth: (interval - diff) * current_rate. Then we add how much was received in the most recent diff seconds. Divide by the width of the interval to get the average. */ count = (interval - diff) * current_rate + amount; current_rate = count / interval; last_update_tv = *now; } double RateMeter::getOverallRate(const struct timeval *now) const { double elapsed; elapsed = elapsedTime(now); if (elapsed <= 0.0) return 0.0; else return total / elapsed; } /* Get the "current" rate (actually a moving average of the last current_rate_history seconds). If update is true (its default value), lower the rate to account for the time since the last record. */ double RateMeter::getCurrentRate(const struct timeval *now, bool update) { if (update) this->update(0.0, now); return current_rate; } double RateMeter::getTotal(void) const { return total; } /* Get the number of seconds the meter has been running: if it has been stopped, the amount of time between start and stop, or if it is still running, the amount of time between start and now. */ double RateMeter::elapsedTime(const struct timeval *now) const { struct timeval tv; const struct timeval *end_tv; assert(isSet(&start_tv)); if (isSet(&stop_tv)) { end_tv = &stop_tv; } else if (now == NULL) { gettimeofday(&tv, NULL); end_tv = &tv; } else { end_tv = now; } return TIMEVAL_SUBTRACT(*end_tv, start_tv) / 1000000.0; } /* Returns true if tv has been initialized; i.e., its members are not all zero. */ bool RateMeter::isSet(const struct timeval *tv) { return tv->tv_sec != 0 || tv->tv_usec != 0; } PacketRateMeter::PacketRateMeter(double current_rate_history) { packet_rate_meter = RateMeter(current_rate_history); byte_rate_meter = RateMeter(current_rate_history); } void PacketRateMeter::start(const struct timeval *now) { packet_rate_meter.start(now); byte_rate_meter.start(now); } void PacketRateMeter::stop(const struct timeval *now) { packet_rate_meter.stop(now); byte_rate_meter.stop(now); } /* Record one packet of length len. */ void PacketRateMeter::update(u32 len, const struct timeval *now) { packet_rate_meter.update(1, now); byte_rate_meter.update(len, now); } double PacketRateMeter::getOverallPacketRate(const struct timeval *now) const { return packet_rate_meter.getOverallRate(now); } double PacketRateMeter::getCurrentPacketRate(const struct timeval *now, bool update) { return packet_rate_meter.getCurrentRate(now, update); } double PacketRateMeter::getOverallByteRate(const struct timeval *now) const { return byte_rate_meter.getOverallRate(now); } double PacketRateMeter::getCurrentByteRate(const struct timeval *now, bool update) { return byte_rate_meter.getCurrentRate(now, update); } unsigned long long PacketRateMeter::getNumPackets(void) const { return (unsigned long long) packet_rate_meter.getTotal(); } unsigned long long PacketRateMeter::getNumBytes(void) const { return (unsigned long long) byte_rate_meter.getTotal(); } ScanProgressMeter::ScanProgressMeter() { gettimeofday(&begin, NULL); last_print_test = begin; memset(&last_print, 0, sizeof(last_print)); memset(&last_est, 0, sizeof(last_est)); beginOrEndTask(&begin, NULL, true); } ScanProgressMeter::~ScanProgressMeter() { ; } /* Decides whether a timing report is likely to even be printed. There are stringent limitations on how often they are printed, as well as the verbosity level that must exist. So you might as well check this before spending much time computing progress info. now can be NULL if caller doesn't have the current time handy. Just because this function returns true does not mean that the next printStatsIfNecessary will always print something. It depends on whether time estimates have changed, which this func doesn't even know about. */ bool ScanProgressMeter::mayBePrinted(const struct timeval *now) { struct timeval tv; if (!o.verbose) return false; if (!now) { gettimeofday(&tv, NULL); now = (const struct timeval *) &tv; } if (last_print.tv_sec == 0) { /* We've never printed before -- the rules are less stringent */ if (difftime(now->tv_sec, begin.tv_sec) > 30) return true; else return false; } if (difftime(now->tv_sec, last_print_test.tv_sec) < 3) return false; /* No point even checking too often */ /* We'd never want to print more than once per 30 seconds */ if (difftime(now->tv_sec, last_print.tv_sec) < 30) return false; return true; } /* Return an estimate of the time remaining if a process was started at begin and is perc_done of the way finished. Returns inf if perc_done == 0.0. */ static double estimate_time_left(double perc_done, const struct timeval *begin, const struct timeval *now) { double time_used_s; double time_needed_s; time_used_s = difftime(now->tv_sec, begin->tv_sec); time_needed_s = time_used_s / perc_done; return time_needed_s - time_used_s; } /* Prints an estimate of when this scan will complete. It only does so if mayBePrinted() is true, and it seems reasonable to do so because the estimate has changed significantly. Returns whether or not a line was printed.*/ bool ScanProgressMeter::printStatsIfNecessary(double perc_done, const struct timeval *now) { struct timeval tvtmp; double time_left_s; bool printit = false; if (!now) { gettimeofday(&tvtmp, NULL); now = (const struct timeval *) &tvtmp; } if (!mayBePrinted(now)) return false; last_print_test = *now; if (perc_done <= 0.003) return false; /* Need more info first */ assert(perc_done <= 1.0); time_left_s = estimate_time_left(perc_done, &begin, now); if (time_left_s < 30) return false; /* No point in updating when it is virtually finished. */ if (last_est.tv_sec == 0) { /* We don't have an estimate yet (probably means a low completion). */ printit = true; } else if (TIMEVAL_AFTER(*now, last_est)) { /* The last estimate we printed has passed. Print a new one. */ printit = true; } else { /* If the estimate changed by more than 3 minutes, and if that change represents at least 5% of the total time, print it. */ double prev_est_total_time_s = difftime(last_est.tv_sec, begin.tv_sec); double prev_est_time_left_s = difftime(last_est.tv_sec, last_print.tv_sec); double change_abs_s = ABS(prev_est_time_left_s - time_left_s); if (o.debugging || (change_abs_s > 15 && change_abs_s > .05 * prev_est_total_time_s)) printit = true; } if (printit) { return printStats(perc_done, now); } return false; } /* Prints an estimate of when this scan will complete. */ bool ScanProgressMeter::printStats(double perc_done, const struct timeval *now) { struct timeval tvtmp; double time_left_s; time_t timet; struct tm *ltime; if (!now) { gettimeofday(&tvtmp, NULL); now = (const struct timeval *) &tvtmp; } last_print = *now; // If we're less than 1% done we probably don't have enough // data for decent timing estimates. Also with perc_done == 0 // these elements will be nonsensical. if (perc_done < 0.01) { log_write(LOG_STDOUT, "About %.2f%% done\n", perc_done * 100); log_flush(LOG_STDOUT); return true; } /* Add 0.5 to get the effect of rounding in integer calculations. */ time_left_s = estimate_time_left(perc_done, &begin, now) + 0.5; last_est = *now; last_est.tv_sec += (time_t)time_left_s; /* Get the estimated time of day at completion */ timet = last_est.tv_sec; ltime = localtime(&timet); assert(ltime); log_write(LOG_STDOUT, "About %.2f%% done; ETC: %02d:%02d " "(%.f:%02.f:%02.f remaining)\n", perc_done * 100, ltime->tm_hour, ltime->tm_min, floor(time_left_s / 60.0 / 60.0), floor(fmod(time_left_s / 60.0, 60.0)), floor(fmod(time_left_s, 60.0))); /*log_write(LOG_XML, "<taskprogress task=\"%s\" time=\"%lu\" percent=\"%.2f\" remaining=\"%.f\" etc=\"%lu\" />\n", scantypestr, (unsigned long) now->tv_sec, perc_done * 100, time_left_s, (unsigned long) last_est.tv_sec); */ log_flush(LOG_STDOUT|LOG_XML); return true; } /* Indicates that the task is beginning or ending, and that a message should be generated if appropriate. Returns whether a message was printed. now may be NULL, if the caller doesn't have the current time handy. additional_info may be NULL if no additional information is necessary. */ bool ScanProgressMeter::beginOrEndTask(const struct timeval *now, const char *additional_info, bool beginning) { struct timeval tvtmp; //struct tm *tm; //time_t tv_sec; if (!o.verbose) { return false; } if (!now) { gettimeofday(&tvtmp, NULL); now = (const struct timeval *) &tvtmp; } //tv_sec = now->tv_sec; //tm = localtime(&tv_sec); if (beginning) { // log_write(LOG_STDOUT, "Initiating %s at %02d:%02d", scantypestr, tm->tm_hour, tm->tm_min); // log_write(LOG_XML, "<taskbegin task=\"%s\" time=\"%lu\"", scantypestr, (unsigned long) now->tv_sec); if (additional_info) { log_write(LOG_STDOUT, " (%s)", additional_info); log_write(LOG_XML, " extrainfo=\"%s\"", additional_info); } log_write(LOG_STDOUT, "\n"); log_write(LOG_XML, " />\n"); } else { //log_write(LOG_STDOUT, "Completed %s at %02d:%02d, %.2fs elapsed", scantypestr, tm->tm_hour, tm->tm_min, TIMEVAL_MSEC_SUBTRACT(*now, begin) / 1000.0); // log_write(LOG_XML, "<taskend task=\"%s\" time=\"%lu\"", scantypestr, (unsigned long) now->tv_sec); if (additional_info) { log_write(LOG_STDOUT, " (%s)", additional_info); log_write(LOG_XML, " extrainfo=\"%s\"", additional_info); } log_write(LOG_STDOUT, "\n"); log_write(LOG_XML, " />\n"); } log_flush(LOG_STDOUT|LOG_XML); return true; }
38.572254
155
0.636445
Adam-K-P
6f3ddcedff81425b1bbbbd4bc05feec1b03a490b
1,618
cpp
C++
Engine/lib/sdl/src/video/winrt/SDL_winrtopengles.cpp
John3/crabmusket_Torque3D
d84bd0fce2837ffac69d9fc9aadcdf5ee2c98b5c
[ "Unlicense" ]
77
2015-09-09T00:00:15.000Z
2021-08-28T04:37:35.000Z
Engine/lib/sdl/src/video/winrt/SDL_winrtopengles.cpp
John3/crabmusket_Torque3D
d84bd0fce2837ffac69d9fc9aadcdf5ee2c98b5c
[ "Unlicense" ]
10
2015-01-20T23:14:46.000Z
2019-04-05T22:04:15.000Z
Engine/lib/sdl/src/video/winrt/SDL_winrtopengles.cpp
John3/crabmusket_Torque3D
d84bd0fce2837ffac69d9fc9aadcdf5ee2c98b5c
[ "Unlicense" ]
53
2015-12-14T08:33:27.000Z
2021-12-28T04:51:43.000Z
/* Simple DirectMedia Layer Copyright (C) 1997-2014 Sam Lantinga <[email protected]> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" // TODO: WinRT, make this file compile via C code #if SDL_VIDEO_DRIVER_WINRT && SDL_VIDEO_OPENGL_EGL /* EGL implementation of SDL OpenGL support */ #include "SDL_winrtvideo_cpp.h" extern "C" { #include "SDL_winrtopengles.h" } #define EGL_D3D11_ONLY_DISPLAY_ANGLE ((NativeDisplayType) -3) extern "C" int WINRT_GLES_LoadLibrary(_THIS, const char *path) { return SDL_EGL_LoadLibrary(_this, path, EGL_D3D11_ONLY_DISPLAY_ANGLE); } extern "C" { SDL_EGL_CreateContext_impl(WINRT) SDL_EGL_SwapWindow_impl(WINRT) SDL_EGL_MakeCurrent_impl(WINRT) } #endif /* SDL_VIDEO_DRIVER_WINRT && SDL_VIDEO_OPENGL_EGL */ /* vi: set ts=4 sw=4 expandtab: */
31.72549
76
0.765142
John3
6f4079e4415ef8af8f2de5d02fccf8e96c58c68a
10,359
cpp
C++
Experimental/Samples/VR/src/Sample_VR.cpp
azhirnov/DE-Experimental
be0872e603ff0ea1a2aa2b4e579807f6931e65ff
[ "MIT" ]
1
2020-12-19T02:16:12.000Z
2020-12-19T02:16:12.000Z
Experimental/Samples/VR/src/Sample_VR.cpp
azhirnov/DE-Experimental
be0872e603ff0ea1a2aa2b4e579807f6931e65ff
[ "MIT" ]
null
null
null
Experimental/Samples/VR/src/Sample_VR.cpp
azhirnov/DE-Experimental
be0872e603ff0ea1a2aa2b4e579807f6931e65ff
[ "MIT" ]
null
null
null
#include <random> #include <thread> #include "Timer.hpp" #include "MapHelper.hpp" #include "Sample_VR.hpp" #include "TextureUtilities.h" #include "TexturedCube.hpp" #include "EngineFactoryVk.h" #include "OpenVRDevice.h" #include "VREmulator.h" namespace DEVR { using EHmdStatus = IVRDevice::EHmdStatus; void Sample_VR::CreateUniformBuffer() { BufferDesc CBDesc; CBDesc.Name = "VS constants CB"; CBDesc.uiSizeInBytes = sizeof(float4x4) * 2; CBDesc.Usage = USAGE_DYNAMIC; CBDesc.BindFlags = BIND_UNIFORM_BUFFER; CBDesc.CPUAccessFlags = CPU_ACCESS_WRITE; m_pDevice->CreateBuffer(CBDesc, nullptr, &m_VSConstants); } void Sample_VR::CreatePipelineState() { LayoutElement LayoutElems[] = { LayoutElement{0, 0, 3, VT_FLOAT32, False}, LayoutElement{1, 0, 2, VT_FLOAT32, False}, LayoutElement{2, 1, 4, VT_FLOAT32, False, INPUT_ELEMENT_FREQUENCY_PER_INSTANCE}, LayoutElement{3, 1, 4, VT_FLOAT32, False, INPUT_ELEMENT_FREQUENCY_PER_INSTANCE}, LayoutElement{4, 1, 4, VT_FLOAT32, False, INPUT_ELEMENT_FREQUENCY_PER_INSTANCE}, LayoutElement{5, 1, 4, VT_FLOAT32, False, INPUT_ELEMENT_FREQUENCY_PER_INSTANCE}}; RefCntAutoPtr<IShaderSourceInputStreamFactory> pShaderSourceFactory; m_pEngineFactory->CreateDefaultShaderSourceStreamFactory(nullptr, &pShaderSourceFactory); m_pPSO = TexturedCube::CreatePipelineState(m_pDevice, m_VRDevice->GetImageFormat(), m_DepthFormat, pShaderSourceFactory, "cube_inst.vsh", "cube_inst.psh", LayoutElems, _countof(LayoutElems)); m_pPSO->GetStaticVariableByName(SHADER_TYPE_VERTEX, "Constants")->Set(m_VSConstants); m_pPSO->CreateShaderResourceBinding(&m_SRB, true); } void Sample_VR::CreateInstanceBuffer() { BufferDesc InstBuffDesc; InstBuffDesc.Name = "Instance data buffer"; InstBuffDesc.Usage = USAGE_DEFAULT; InstBuffDesc.BindFlags = BIND_VERTEX_BUFFER; InstBuffDesc.uiSizeInBytes = sizeof(float4x4) * MaxInstances; m_pDevice->CreateBuffer(InstBuffDesc, nullptr, &m_InstanceBuffer); PopulateInstanceBuffer(); } void Sample_VR::PopulateInstanceBuffer() { std::vector<float4x4> InstanceData(m_GridSize * m_GridSize * m_GridSize); float fGridSize = static_cast<float>(m_GridSize); std::mt19937 gen; std::uniform_real_distribution<float> scale_distr(0.3f, 1.0f); std::uniform_real_distribution<float> offset_distr(-0.15f, +0.15f); std::uniform_real_distribution<float> rot_distr(-PI_F, +PI_F); float BaseScale = 0.6f / fGridSize; int instId = 0; for (int x = 0; x < m_GridSize; ++x) { for (int y = 0; y < m_GridSize; ++y) { for (int z = 0; z < m_GridSize; ++z) { float xOffset = 2.f * (x + 0.5f + offset_distr(gen)) / fGridSize - 1.f; float yOffset = 2.f * (y + 0.5f + offset_distr(gen)) / fGridSize - 1.f; float zOffset = 2.f * (z + 0.5f + offset_distr(gen)) / fGridSize - 1.f; float scale = BaseScale * scale_distr(gen); float4x4 rotation = float4x4::RotationX(rot_distr(gen)) * float4x4::RotationY(rot_distr(gen)) * float4x4::RotationZ(rot_distr(gen)); float4x4 matrix = rotation * float4x4::Scale(scale, scale, scale) * float4x4::Translation(xOffset, yOffset, zOffset); InstanceData[instId++] = matrix; } } } Uint32 DataSize = static_cast<Uint32>(sizeof(InstanceData[0]) * InstanceData.size()); m_pContext->UpdateBuffer(m_InstanceBuffer, 0, DataSize, InstanceData.data(), RESOURCE_STATE_TRANSITION_MODE_TRANSITION); } void Sample_VR::CreateRenderTargets() { TextureDesc desc; desc.Name = "Depth texture"; desc.Type = RESOURCE_DIM_TEX_2D; desc.Width = m_VRDevice->GetRenderTargetDimension().x; desc.Height = m_VRDevice->GetRenderTargetDimension().y; desc.MipLevels = 1; desc.BindFlags = BIND_DEPTH_STENCIL; desc.Format = m_DepthFormat; m_pDevice->CreateTexture(desc, nullptr, &m_DepthTexture); } void Sample_VR::Render() { ITexture* RenderTargets[2] = {}; ITextureView* RTViews[2] = {}; ITextureView* DSView = m_DepthTexture->GetDefaultView(TEXTURE_VIEW_DEPTH_STENCIL); if (!m_VRDevice->GetRenderTargets(&RenderTargets[0], &RenderTargets[1])) return; for (uint i = 0; i < 2; ++i) { RTViews[i] = RenderTargets[i]->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); m_pContext->SetRenderTargets(1, &RTViews[i], DSView, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); const float ClearColor[] = {0.350f, 0.350f, 0.350f, 1.0f}; m_pContext->ClearRenderTarget(RTViews[i], ClearColor, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); m_pContext->ClearDepthStencil(DSView, CLEAR_DEPTH_FLAG, 1.f, 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); { MapHelper<float4x4> CBConstants(m_pContext, m_VSConstants, MAP_WRITE, MAP_FLAG_DISCARD); CBConstants[0] = m_ViewProjMatrix[i].Transpose(); CBConstants[1] = m_RotationMatrix.Transpose(); } Uint32 offsets[] = {0, 0}; IBuffer* pBuffs[] = {m_CubeVertexBuffer, m_InstanceBuffer}; m_pContext->SetVertexBuffers(0, _countof(pBuffs), pBuffs, offsets, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, SET_VERTEX_BUFFERS_FLAG_RESET); m_pContext->SetIndexBuffer(m_CubeIndexBuffer, 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); m_pContext->SetPipelineState(m_pPSO); m_pContext->CommitShaderResources(m_SRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); DrawIndexedAttribs DrawAttrs; DrawAttrs.IndexType = VT_UINT32; DrawAttrs.NumIndices = 36; DrawAttrs.NumInstances = m_GridSize * m_GridSize * m_GridSize; DrawAttrs.Flags = DRAW_FLAG_VERIFY_ALL; m_pContext->DrawIndexed(DrawAttrs); } } float4x4 Sample_VR::GetAdjustedProjectionMatrix(float FOV, float NearPlane, float FarPlane) const { uint2 Dim = m_VRDevice->GetRenderTargetDimension(); float AspectRatio = float(Dim.x) / Dim.y; float YScale = 1.f / std::tan(FOV / 2.f); float XScale = YScale / AspectRatio; float4x4 Proj; Proj._11 = XScale; Proj._22 = YScale; Proj.SetNearFarClipPlanes(NearPlane, FarPlane, m_pDevice->GetDeviceCaps().IsGLDevice()); return Proj; } void Sample_VR::Update(double CurrTime, double ElapsedTime) { auto& vrCamera = m_VRDevice->GetCamera(); float4x4 View = float4x4::Translation(vrCamera.position) * vrCamera.pose; //float4x4::RotationX(-0.6f) * float4x4::Translation(0.f, 0.f, 4.0f); float4x4 Proj = GetAdjustedProjectionMatrix(PI_F / 4.0f, 0.1f, 100.f); m_ViewProjMatrix[0] = View * vrCamera.left.view * vrCamera.left.proj; m_ViewProjMatrix[1] = View * vrCamera.right.view * vrCamera.right.proj; m_RotationMatrix = float4x4::RotationY(float(CurrTime) * 0.01f) * float4x4::RotationX(-float(CurrTime) * 0.025f); } bool Sample_VR::Initialize() { // engine initialization { m_VRDevice.reset(new VREmulatorVk{}); //m_VRDevice.reset(new OpenVRDeviceVk{}); //m_VRDevice.reset(new OpenXRDeviceVk{}); if (!m_VRDevice->Create()) return false; IVRDevice::Requirements Req; m_VRDevice->GetRequirements(Req); EngineVkCreateInfo CreateInfo; CreateInfo.EnableValidation = true; CreateInfo.NumDeferredContexts = 0; CreateInfo.AdapterId = Req.AdapterId; CreateInfo.InstanceExtensionCount = Uint32(Req.InstanceExtensions.size()); CreateInfo.ppInstanceExtensionNames = CreateInfo.InstanceExtensionCount ? Req.InstanceExtensions.data() : nullptr; CreateInfo.DeviceExtensionCount = Uint32(Req.DeviceExtensions.size()); CreateInfo.ppDeviceExtensionNames = CreateInfo.DeviceExtensionCount ? Req.DeviceExtensions.data() : nullptr; auto* Factory = GetEngineFactoryVk(); m_pEngineFactory = Factory; IRenderDevice* Device = nullptr; IDeviceContext* Context = nullptr; Factory->CreateDeviceAndContextsVk(CreateInfo, &Device, &Context); if (!Device) return false; m_pDevice = Device; m_pContext = Context; m_VRDevice->Initialize(Device, Context); m_VRDevice->SetupCamera(float2{0.1f, 100.f}); } CreateRenderTargets(); CreateUniformBuffer(); CreatePipelineState(); m_CubeVertexBuffer = TexturedCube::CreateVertexBuffer(m_pDevice); m_CubeIndexBuffer = TexturedCube::CreateIndexBuffer(m_pDevice); m_TextureSRV = TexturedCube::LoadTexture(m_pDevice, "DGLogo.png")->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_SRB->GetVariableByName(SHADER_TYPE_PIXEL, "g_Texture")->Set(m_TextureSRV); CreateInstanceBuffer(); return true; } void Sample_VR::Run() { if (!Initialize()) return; Diligent::Timer Timer; auto PrevTime = Timer.GetElapsedTime(); for (;;) { if (!m_VRDevice->BeginFrame()) break; EHmdStatus status = m_VRDevice->GetStatus(); auto CurrTime = Timer.GetElapsedTime(); auto ElapsedTime = CurrTime - PrevTime; PrevTime = CurrTime; switch (status) { case EHmdStatus::Active: case EHmdStatus::Mounted: Update(CurrTime, ElapsedTime); Render(); break; case EHmdStatus::Standby: std::this_thread::sleep_for(std::chrono::milliseconds{1}); break; case EHmdStatus::PowerOff: return; } m_VRDevice->EndFrame(); m_pDevice->ReleaseStaleResources(); } } } // namespace DEVR int main() { DEVR::Sample_VR sample; sample.Run(); return 0; }
36.094077
153
0.643209
azhirnov
6f4832a47b91566139d2569ab9e05e6c03acc272
2,083
cpp
C++
Top Interview Questions/130. Surrounded Regions/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
1
2021-11-19T19:58:33.000Z
2021-11-19T19:58:33.000Z
Top Interview Questions/130. Surrounded Regions/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
null
null
null
Top Interview Questions/130. Surrounded Regions/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
2
2021-11-26T12:47:27.000Z
2022-01-13T16:14:46.000Z
// // main.cpp // 130. Surrounded Regions // // Created by 边俊林 on 2019/10/20. // Copyright © 2019 Minecode.Link. All rights reserved. // #include <map> #include <set> #include <queue> #include <string> #include <stack> #include <vector> #include <cstdio> #include <numeric> #include <cstdlib> #include <utility> #include <iostream> #include <algorithm> #include <unordered_map> #include <unordered_set> using namespace std; /// Solution: // class Solution { public: void solve(vector<vector<char>>& board) { int rows = board.size(), cols = rows ? board[0].size() : 0; vector<vector<bool>> vis (rows, vector<bool> (cols, false)); queue<pair<int, int>> q; for (int i = 0; i < cols; ++i) q.emplace(0, i); for (int i = 1; i < rows; ++i) q.emplace(i, cols-1); for (int i = cols-2; i >= 0; --i) q.emplace(rows-1, i); for (int i = rows-2; i > 0; --i) q.emplace(i, 0); int dir[5] = {0, 1, 0, -1, 0}; while (q.size()) { auto pir = q.front(); q.pop(); int row = pir.first, col = pir.second; if (vis[row][col] || board[row][col] == 'X') continue; vis[row][col] = true; for (int i = 0; i < 4; ++i) { int tor = row + dir[i]; int toc = col + dir[i+1]; if (tor>=0 && tor<rows && toc>=0 && toc<cols && !vis[tor][toc] && board[tor][toc] == 'O') q.emplace(tor, toc); } } for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if (board[i][j] == 'O' && !vis[i][j]) board[i][j] = 'X'; } } } }; int main() { Solution sol = Solution(); vector<string> strs = { // "XXXX", "XOOX", "XXOX", "XOXX" // "O" "OXO", "XOX", "OXO" }; vector<vector<char>> mat; for (auto& str: strs) mat.push_back(vector<char>(str.begin(), str.end())); sol.solve(mat); cout << mat.size() << endl; return 0; }
26.367089
68
0.473836
Minecodecraft
6f4860860d3892964a0adf854adff6219f3b37ca
1,733
hpp
C++
bsengine/src/bstorm/mesh.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
bsengine/src/bstorm/mesh.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
bsengine/src/bstorm/mesh.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
#pragma once #include <bstorm/cache_store.hpp> #include <vector> #include <memory> #include <unordered_map> #include <d3dx9.h> namespace bstorm { struct MeshVertex { MeshVertex() : x(0), y(0), z(0), nx(0), ny(0), nz(0), u(0), v(0) {} MeshVertex(float x, float y, float z, float nx, float ny, float nz, float u, float v) : x(x), y(y), z(z), nx(nx), ny(ny), nz(nz), u(u), v(v) {} float x, y, z; float nx, ny, nz; float u, v; static constexpr DWORD Format = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1; }; class Texture; struct MeshMaterial { MeshMaterial(float r, float g, float b, float a, float dif, float amb, float emi, const std::shared_ptr<Texture>& texture) : col({ r, g, b, a }), dif(dif), amb(amb), emi(emi), texture(texture) { } struct { float r; float g; float b; float a; } col; float dif; float amb; float emi; std::vector<MeshVertex> vertices; std::shared_ptr<Texture> texture; }; class TextureStore; class FileLoader; class Mesh { public: Mesh(const std::wstring& path, const std::shared_ptr<TextureStore>& textureStore, const std::shared_ptr<FileLoader>& fileLoader); ~Mesh(); std::vector<MeshMaterial> materials; const std::wstring& GetPath() const { return path_; } private: std::wstring path_; }; class MeshStore { public: MeshStore(const std::shared_ptr<TextureStore>& textureStore, const std::shared_ptr<FileLoader>& fileLoader); const std::shared_ptr<Mesh>& Load(const std::wstring& path); void RemoveUnusedMesh(); private: std::shared_ptr<TextureStore> textureStore_; std::shared_ptr<FileLoader> fileLoader_; CacheStore<std::wstring, Mesh> cacheStore_; }; }
25.865672
147
0.651471
At-sushi
6f4b2016ad7ae6eb186aaa70fa1f31b8e9db2bb9
582
cpp
C++
src/resources/pattern_store.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
src/resources/pattern_store.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
src/resources/pattern_store.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
/* * TS Elements * Copyright 2015-2018 M. Newhouse * Released under the MIT license. */ #include "pattern_store.hpp" #include "pattern.hpp" namespace ts { namespace resources { Pattern& PatternStore::load_from_file(const std::string& file_name) { auto it = loaded_patterns_.find(file_name); if (it != loaded_patterns_.end()) { return it->second; } auto pattern = load_pattern(file_name); auto result = loaded_patterns_.insert(std::make_pair(file_name, std::move(pattern))); return result.first->second; } } }
20.068966
91
0.654639
mnewhouse
6f4c3ad56bda5cc867130af27b5df9949f2f502e
25,884
cpp
C++
amara/amara_uiBox.cpp
BigBossErndog/Amara-RPG
0a95a35fcddd69775a7ca7b34f3f23be9eb77178
[ "MIT" ]
null
null
null
amara/amara_uiBox.cpp
BigBossErndog/Amara-RPG
0a95a35fcddd69775a7ca7b34f3f23be9eb77178
[ "MIT" ]
null
null
null
amara/amara_uiBox.cpp
BigBossErndog/Amara-RPG
0a95a35fcddd69775a7ca7b34f3f23be9eb77178
[ "MIT" ]
null
null
null
#pragma once #ifndef AMARA_UIBOX #define AMARA_UIBOX #include "amara.h" namespace Amara { class UIBox: public Amara::Actor { public: SDL_Renderer* gRenderer = nullptr; SDL_Texture* canvas = nullptr; Amara::ImageTexture* texture = nullptr; std::string textureKey; SDL_Rect viewport; SDL_Rect srcRect; SDL_FRect destRect; SDL_FPoint origin; bool pixelLocked = false; SDL_BlendMode blendMode = SDL_BLENDMODE_BLEND; float recWidth = -1; float recHeight = -1; int width = 0; int height = 0; int minWidth = 0; int minHeight = 0; int openWidth = 0; int openHeight = 0; bool lockOpen = false; int openSpeedX = 0; int openSpeedY = 0; int closeSpeedX = 0; int closeSpeedY = 0; int boxTextureWidth = 0; int boxTextureHeight = 0; int imageWidth = 0; int imageHeight = 0; int partitionTop = 0; int partitionBottom = 0; int partitionLeft = 0; int partitionRight = 0; int frame = 0; float originX = 0; float originY = 0; Amara::Alignment boxHorizontalAlignment = ALIGN_CENTER; Amara::Alignment boxVerticalAlignment = ALIGN_CENTER; Amara::StateManager* copySm = nullptr; Amara::StateManager mySm; bool keepOpen = false; Entity* content = nullptr; UIBox() {} UIBox(Amara::StateManager* gsm) { copyStateManager(gsm); setVisible(false); } UIBox(float gx, float gy, int gw, int gh, std::string gTextureKey): UIBox() { x = gx; y = gy; width = gw; height = gh; openWidth = width; openHeight = height; textureKey = gTextureKey; } UIBox(int gw, int gh, std::string gTextureKey): UIBox(0, 0, gw, gh, gTextureKey) {} virtual void init(Amara::GameProperties* gameProperties, Amara::Scene* givenScene, Amara::Entity* givenParent) { properties = gameProperties; load = properties->loader; gRenderer = properties->gRenderer; if (!textureKey.empty()) { setTexture(textureKey); } setSize(width, height); Amara::Actor::init(gameProperties, givenScene, givenParent); entityType = "uiBox"; } virtual void configure(nlohmann::json config) { Amara::Actor::configure(config); if (config.find("width") != config.end()) { width = config["width"]; openWidth = width; } if (config.find("height") != config.end()) { height = config["height"]; openHeight = height; } if (config.find("xFromRight") != config.end()) { int xFromRight = config["xFromRight"]; x = scene->mainCamera->width - width - xFromRight; } if (config.find("yFromBottom") != config.end()) { int yFromBottom = config["yFromBottom"]; y = scene->mainCamera->height - height - yFromBottom; } if (config.find("relativeXFromRight") != config.end()) { float relativeX = config["relativeXFromRight"]; x = scene->mainCamera->width - scene->mainCamera->width*relativeX - width; } if (config.find("relativeYFromBottom") != config.end()) { float relativeY = config["relativeYFromBottom"]; y = scene->mainCamera->height - scene->mainCamera->height*relativeY - height; } if (config.find("relativeXFromCenter") != config.end()) { float relativeX = config["relativeXFromCenter"]; x = scene->mainCamera->width/2.0 + scene->mainCamera->width*relativeX/2.0 - width/2.0; } if (config.find("relativeYFromCenter") != config.end()) { float relativeY = config["relativeYFromCenter"]; y = scene->mainCamera->height/2.0 + scene->mainCamera->height*relativeY/2.0 - height/2.0; } if (config.find("minWidth") != config.end()) { minWidth = config["minWidth"]; } if (config.find("minHeight") != config.end()) { minHeight = config["minHeight"]; } if (config.find("texture") != config.end()) { setTexture(config["texture"]); } if (config.find("openSpeedX") != config.end()) { openSpeedX = config["openSpeedX"]; } if (config.find("openSpeedY") != config.end()) { openSpeedY = config["openSpeedY"]; } if (config.find("closeSpeedX") != config.end()) { closeSpeedX = config["closeSpeedX"]; } if (config.find("closeSpeedY") != config.end()) { closeSpeedY = config["closeSpeedY"]; } if (config.find("openCloseSpeedX") != config.end()) { openSpeedX = config["openCloseSpeedX"]; closeSpeedX = config["openCloseSpeedX"]; } if (config.find("openCloseSpeedY") != config.end()) { openSpeedY = config["openCloseSpeedY"]; closeSpeedY = config["openCloseSpeedY"]; } if (config.find("openCloseSpeed") != config.end()) { setOpenCloseSpeed(config["openCloseSpeed"], config["openCloseSpeed"]); } if (config.find("fixedWithinBounds") != config.end() && config["fixedWithinBounds"]) { if (x < 0) x = 0; if (y < 0) y = 0; if (x + width > scene->mainCamera->width) { x = scene->mainCamera->width - width; } if (y + height > scene->mainCamera->height) { y = scene->mainCamera->height - height; } } if (config.find("partitionTop") != config.end()) { partitionTop = config["partitionTop"]; } if (config.find("partitionBottom") != config.end()) { partitionBottom = config["partitionBottom"]; } if (config.find("partitionLeft") != config.end()) { partitionLeft = config["partitionLeft"]; } if (config.find("partitionRight") != config.end()) { partitionRight = config["partitionRight"]; } if (config.find("boxHorizontalAlignment") != config.end()) { boxHorizontalAlignment = config["boxHorizontalAlignment"]; } if (config.find("boxVerticalAlignment") != config.end()) { boxVerticalAlignment = config["boxVerticalAlignment"]; } setOpenSpeed(openSpeedX, openSpeedY); setCloseSpeed(closeSpeedX, closeSpeedY); } virtual void drawBoxPart(int part) { bool skipDrawing = false; int partX = 0, partY = 0, partWidth = 0, partHeight = 0; float horizontalAlignmentFactor = 0.5; float verticalAlignmentFactor = 0.5; switch (boxHorizontalAlignment) { case ALIGN_LEFT: horizontalAlignmentFactor = 0; break; case ALIGN_RIGHT: horizontalAlignmentFactor = 1; break; } switch(boxVerticalAlignment) { case ALIGN_TOP: verticalAlignmentFactor = 0; break; case ALIGN_BOTTOM: verticalAlignmentFactor = 1; break; } switch (part % 3) { case 0: partX = 0; partWidth = partitionLeft; destRect.x = (width - openWidth)*horizontalAlignmentFactor; destRect.w = partWidth; break; case 1: partX = partitionLeft; partWidth = boxTextureWidth - partitionLeft - partitionRight; destRect.x = (width - openWidth)*horizontalAlignmentFactor + partitionLeft; destRect.w = openWidth - partitionLeft - partitionRight; break; case 2: partX = boxTextureWidth - partitionRight; partWidth = partitionRight; destRect.x = (width - openWidth)*horizontalAlignmentFactor + openWidth - partitionRight; destRect.w = partWidth; break; } switch ((int)floor(part/(float)3)) { case 0: partY = 0; partHeight = partitionTop; destRect.y = (height - openHeight)*verticalAlignmentFactor; destRect.h = partHeight; break; case 1: partY = partitionTop; partHeight = boxTextureHeight - partitionTop - partitionBottom; destRect.y = (height - openHeight)*verticalAlignmentFactor + partitionTop; destRect.h = openHeight - partitionTop - partitionBottom; break; case 2: partY = boxTextureHeight - partitionBottom; partHeight = partitionBottom; destRect.y = (height - openHeight)*verticalAlignmentFactor + openHeight - partitionBottom; destRect.h = partHeight; break; } if (destRect.w <= 0) skipDrawing = true; if (destRect.h <= 0) skipDrawing = true; if (!skipDrawing) { if (texture != nullptr) { SDL_Texture* tx = (SDL_Texture*)texture->asset; switch (texture->type) { case IMAGE: frame = 0; srcRect.x = partX; srcRect.y = partY; srcRect.w = partWidth; srcRect.h = partHeight; break; case SPRITESHEET: Amara::Spritesheet* spr = (Amara::Spritesheet*)texture; int maxFrame = ((texture->width / spr->frameWidth) * (texture->height / spr->frameHeight)); frame = frame % maxFrame; srcRect.x = (frame % (texture->width / spr->frameWidth)) * spr->frameWidth + partX; srcRect.y = floor(frame / (texture->width / spr->frameWidth)) * spr->frameHeight + partY; srcRect.w = partWidth; srcRect.h = partHeight; break; } SDL_RenderCopyF( gRenderer, (SDL_Texture*)(texture->asset), &srcRect, &destRect ); } } } virtual void draw(int vx, int vy, int vw, int vh) override { if (!isVisible) return; if (width < minWidth) width = minWidth; if (height < minHeight) height = minHeight; if (recWidth != width || recHeight != height) { recWidth = width; recHeight = height; if (openWidth > width) openWidth = width; if (openHeight > height) openHeight = height; createNewCanvasTexture(); } if (lockOpen) { openWidth = width; openHeight = height; } SDL_Texture* recTarget = SDL_GetRenderTarget(properties->gRenderer); SDL_SetRenderTarget(properties->gRenderer, canvas); SDL_SetTextureBlendMode(canvas, SDL_BLENDMODE_BLEND); SDL_SetTextureAlphaMod(canvas, 255); SDL_SetRenderDrawColor(gRenderer, 0, 0, 0, 0); SDL_RenderClear(gRenderer); SDL_RenderSetViewport(properties->gRenderer, NULL); for (int i = 0; i < 9; i++) { drawBoxPart(i); } SDL_SetRenderTarget(properties->gRenderer, recTarget); bool skipDrawing = false; if (alpha < 0) alpha = 0; if (alpha > 1) alpha = 1; viewport.x = vx; viewport.y = vy; viewport.w = vw; viewport.h = vh; SDL_RenderSetViewport(properties->gRenderer, &viewport); float nzoomX = 1 + (properties->zoomX-1)*zoomFactorX*properties->zoomFactorX; float nzoomY = 1 + (properties->zoomY-1)*zoomFactorY*properties->zoomFactorY; destRect.x = ((x*scaleX - properties->scrollX*scrollFactorX + properties->offsetX - (originX * width * scaleX)) * nzoomX); destRect.y = ((y*scaleY - properties->scrollY*scrollFactorY + properties->offsetY - (originY * height * scaleY)) * nzoomY); destRect.w = ((width * scaleX) * nzoomX); destRect.h = ((height * scaleY) * nzoomY); if (pixelLocked) { destRect.x = floor(destRect.x); destRect.y = floor(destRect.y); destRect.w = ceil(destRect.w); destRect.h = ceil(destRect.h); } origin.x = destRect.w * originX; origin.y = destRect.h * originY; int hx, hy, hw, hh = 0; hw = destRect.w; hh = destRect.h; if (destRect.x + destRect.w <= 0) skipDrawing = true; if (destRect.y + destRect.h <= 0) skipDrawing = true; if (destRect.x >= vw) skipDrawing = true; if (destRect.y >= vh) skipDrawing = true; if (destRect.w <= 0) skipDrawing = true; if (destRect.h <= 0) skipDrawing = true; if (!skipDrawing) { if (destRect.x >= 0) { hx = destRect.x + vx; } else { hw -= -(destRect.x); hx = vx; } if (destRect.y >= 0) { hy = destRect.y + vy; } else { hh -= -(destRect.y); hy = vy; } if (hx + hw > vx + vw) hw = ((vx + vw) - hx); if (hy + hh > vy + vh) hh = ((vy + vh) - hy); checkForHover(hx, hy, hw, hh); if (canvas != nullptr) { SDL_SetTextureBlendMode(canvas, blendMode); SDL_SetTextureAlphaMod(canvas, alpha * properties->alpha * 255); SDL_RenderCopyExF( properties->gRenderer, canvas, NULL, &destRect, angle + properties->angle, &origin, SDL_FLIP_NONE ); } } if (openWidth == width && openHeight == height) { Amara::Entity::draw(vx, vy, vw, vh); } } void createNewCanvasTexture() { if (canvas != nullptr) { SDL_DestroyTexture(canvas); } canvas = SDL_CreateTexture( properties->gRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, floor(width), floor(height) ); } bool setTexture(std::string gTextureKey) { if (texture) removeTexture(); if (load == nullptr || properties == nullptr) { textureKey = gTextureKey; return true; } texture = (Amara::ImageTexture*)(load->get(gTextureKey)); if (texture != nullptr) { textureKey = texture->key; if (texture->type == SPRITESHEET) { boxTextureWidth = ((Amara::Spritesheet*)texture)->frameWidth; boxTextureHeight = ((Amara::Spritesheet*)texture)->frameHeight; } else { boxTextureWidth = texture->width; boxTextureHeight = texture->height; } imageWidth = boxTextureWidth; imageHeight = boxTextureHeight; partitionLeft = imageWidth/3.0; partitionRight = imageWidth/3.0; partitionTop = imageHeight/3.0; partitionBottom = imageHeight/3.0; return true; } else { std::cout << "Texture with key: \"" << gTextureKey << "\" was not found." << std::endl; } return false; } bool removeTexture() { textureKey.clear(); if (texture && texture->temp) delete texture; texture = nullptr; } void setSize(int nw, int nh) { width = nw; height = nh; } void setOpenSize(int nw, int nh) { openWidth = nw; openHeight = nh; if (openWidth > width) openWidth = width; if (openHeight > height) openHeight = height; if (openWidth < minWidth) openWidth = minWidth; if (openHeight < minHeight) openHeight = minHeight; } void changeOpenSize(int gx, int gy) { setOpenSize(openWidth + gx, openHeight + gy); } void setOrigin(float gx, float gy) { originX = gx; originY = gy; } void setOrigin(float gi) { setOrigin(gi, gi); } void setOriginPosition(float gx, float gy) { originX = gx/width; originY = gy/height; } void setOriginPosition(float g) { setOriginPosition(g, g); } void copyStateManager(Amara::StateManager* gsm) { copySm = gsm; } void copyStateManager(Amara::StateManager& gsm) { copySm = &gsm; } Amara::StateManager& checkSm() { if (copySm != nullptr) { return *copySm; } else { return mySm; } } virtual bool show() { Amara::StateManager& sm = checkSm(); if (sm.once()) { setVisible(true); return true; } return false; } virtual bool hide() { Amara::StateManager& sm = checkSm(); if (sm.once()) { setVisible(false); return true; } return false; } virtual void onOpen() {} virtual void onClose() {} virtual bool open() { Amara::StateManager& sm = checkSm(); bool toReturn = false; if (sm.once()) { if (!keepOpen) { resetOpenSize(); } } if (show()) { toReturn = true; } if (sm.evt()) { bool complete = true; if (openSpeedX > 0) { openWidth += openSpeedX; if (openWidth >= width) { openWidth = width; } else { complete = false; } } if (openSpeedY > 0) { openHeight += openSpeedY; if (openHeight >= height) { openHeight = height; } else { complete = false; } } if (complete) { keepOpen = true; sm.nextEvt(); } toReturn = true; } if (sm.once()) { if (content) content->setVisible(true); onOpen(); toReturn = true; } return toReturn; } virtual bool close() { Amara::StateManager& sm = checkSm(); bool toReturn = false; if (sm.once()) { if (content) content->setVisible(false); onClose(); toReturn = true; } if (sm.evt()) { bool complete = true; if (closeSpeedX > 0) { openWidth -= closeSpeedX; if (openWidth <= minWidth) { openWidth = minWidth; } else { complete = false; } } if (closeSpeedY > 0) { openHeight -= closeSpeedY; if (openHeight <= minHeight) { openHeight = minHeight; } else { complete = false; } } if (complete) { keepOpen = false; sm.nextEvt(); } toReturn = true; } if (hide()) { toReturn = true; } return toReturn; } void setOpenSpeed(int gx, int gy) { openSpeedX = gx; openSpeedY = gy; if (openSpeedX < 0) openSpeedX = 0; if (openSpeedY < 0) openSpeedY = 0; resetOpenSize(); lockOpen = false; } void setOpenSpeed(int gy) { setOpenSpeed(0, gy); } void setOpenSpeed() { setOpenSpeed(0); } void setCloseSpeed(int gx, int gy) { closeSpeedX = gx; closeSpeedY = gy; if (closeSpeedX < 0) closeSpeedX = 0; if (closeSpeedY < 0) closeSpeedY = 0; if (openWidth < minWidth) openWidth = minWidth; if (openHeight < minHeight) openHeight = minHeight; lockOpen = false; } void setCloseSpeed(int gy) { setCloseSpeed(0, gy); } void setCloseSpeed() { setCloseSpeed(0); } void setOpenCloseSpeed(int gx, int gy) { setOpenSpeed(gx, gy); setCloseSpeed(gx, gy); } void setOpenCloseSpeed(int gy) { setOpenCloseSpeed(0, gy); } void setOpenCloseSpeed() { setOpenCloseSpeed(0); } void resetOpenSize() { if (openSpeedX > 0) setOpenSize(0, openHeight); if (openSpeedY > 0) setOpenSize(openWidth, 0); } ~UIBox() { SDL_DestroyTexture(canvas); } }; class UIBox_Open: public Script { public: UIBox* box; UIBoxOpen() {} void prepare() { box = (UIBox*)parent; box->copyStateManager(this); } void script() { start(); box->open(); finishEvt(); } }; class UIBox_Close: public Script { public: UIBox* box; UIBoxOpen() {} void prepare() { box = (UIBox*)parent; box->copyStateManager(this); } void script() { start(); box->close(); finishEvt(); } }; } #endif
35.264305
139
0.42478
BigBossErndog
6f4d3fc0b0beb8d9cdded7f3b25a283b0cc65d00
5,923
cpp
C++
tests/knnshow.cpp
HIPERT-SRL/libnabo
b3864c8ecab86932e27bd4d463977bfa4e3dc584
[ "BSD-3-Clause" ]
null
null
null
tests/knnshow.cpp
HIPERT-SRL/libnabo
b3864c8ecab86932e27bd4d463977bfa4e3dc584
[ "BSD-3-Clause" ]
null
null
null
tests/knnshow.cpp
HIPERT-SRL/libnabo
b3864c8ecab86932e27bd4d463977bfa4e3dc584
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010--2011, Stephane Magnenat, ASL, ETHZ, Switzerland You can contact the author at <stephane at magnenat dot net> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ETH-ASL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "nabo/nabo.h" #include <iostream> #include <fstream> #include <stdexcept> using namespace std; using namespace Nabo; template<typename T> typename NearestNeighbourSearch<T>::Matrix load(const char *fileName) { typedef typename NearestNeighbourSearch<T>::Matrix Matrix; ifstream ifs(fileName); if (!ifs.good()) throw runtime_error(string("Cannot open file ") + fileName); vector<T> data; int dim(0); bool firstLine(true); while (!ifs.eof()) { char line[1024]; ifs.getline(line, sizeof(line)); line[sizeof(line)-1] = 0; char *token = strtok(line, " \t,;"); while (token) { if (firstLine) ++dim; data.push_back(atof(token)); //cout << atof(token) << " "; token = strtok(NULL, " \t,;"); // FIXME: non reentrant, use strtok_r } firstLine = false; } return Matrix::Map(&data[0], dim, data.size() / dim); } template<typename T> void dumpCoordinateForSVG(const typename NearestNeighbourSearch<T>::Vector coord, const float zoom = 1, const float ptSize = 1, const char* style = "stroke=\"black\" fill=\"red\"") { if (coord.size() == 2) cout << "<circle cx=\"" << zoom*coord(0) << "\" cy=\"" << zoom*coord(1) << "\" r=\"" << ptSize << "\" stroke-width=\"" << 0.2 * ptSize << "\" " << style << "/>" << endl; else assert(false); } int main(int argc, char* argv[]) { typedef Nabo::NearestNeighbourSearch<float>::Matrix Matrix; typedef Nabo::NearestNeighbourSearch<float>::Vector Vector; typedef Nabo::NearestNeighbourSearch<float>::Index Index; typedef Nabo::NearestNeighbourSearch<float>::Indexes Indexes; typedef Nabo::BruteForceSearch<float> BFSF; typedef Nabo::KDTree<float> KDTF; if (argc != 2) { cerr << "Usage " << argv[0] << " DATA" << endl; return 1; } Matrix d(load<float>(argv[1])); BFSF bfs(d); KDTF kdt(d); const Index K(10); // uncomment to compare KDTree with brute force search if (K >= d.size()) return 2; const int itCount(100); for (int i = 0; i < itCount; ++i) { //Vector q(bfs.minBound.size()); //for (int i = 0; i < q.size(); ++i) // q(i) = bfs.minBound(i) + float(rand()) * (bfs.maxBound(i) - bfs.minBound(i)) / float(RAND_MAX); Vector q(d.col(rand() % d.cols())); q.cwise() += 0.01; //cerr << "bfs:\n"; Indexes indexes_bf(bfs.knn(q, K, false)); //cerr << "kdt:\n"; Indexes indexes_kdtree(kdt.knn(q, K, false)); //cout << indexes_bf.size() << " " << indexes_kdtree.size() << " " << K << endl; if (ndexes_bf.size() != indexes_kdtree.size()) return 2; assert(indexes_bf.size() == indexes_kdtree.size()); assert(indexes_bf.size() == K); //cerr << "\nquery:\n" << q << "\n\n"; for (size_t j = 0; j < K; ++j) { Vector pbf(d.col(indexes_bf[j])); Vector pkdtree(d.col(indexes_kdtree[j])); //cerr << "index " << j << ": " << indexes_bf[j] << ", " << indexes_kdtree[j] << "\n"; //cerr << "point " << j << ": " << "\nbf:\n" << pbf << "\nkdtree:\n" << pkdtree << "\n\n"; assert(indexes_bf[j] == indexes_kdtree[j]); assert(dist2(pbf, pkdtree) < numeric_limits<float>::epsilon()); } } cerr << "stats kdtree: " << kdt.getStatistics().totalVisitCount << " on " << itCount * d.cols() << " (" << double(100 * kdt.getStatistics().totalVisitCount) / double(itCount * d.cols()) << " %" << ")" << endl; /* // uncomment to randomly get a point and find its minimum cout << "<?xml version=\"1.0\" standalone=\"no\"?>" << endl; cout << "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">" << endl; cout << "<svg width=\"100%\" height=\"100%\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">" << endl; srand(time(0)); for (int i = 0; i < d.cols(); ++i) dumpCoordinateForSVG<float>(d.col(i), 100, 1); Vector q(bfs.minBound.size()); for (int i = 0; i < q.size(); ++i) q(i) = bfs.minBound(i) + float(rand()) * (bfs.maxBound(i) - bfs.minBound(i)) / float(RAND_MAX); Indexes indexes_bf(bfs.knn(q, K, false)); for (size_t i = 0; i < K; ++i) dumpCoordinateForSVG<float>(d.col(indexes_bf[i]), 100, 1, "stroke=\"black\" fill=\"green\""); dumpCoordinateForSVG<float>(q, 100, 1, "stroke=\"black\" fill=\"blue\""); cout << "</svg>" << endl; */ //cout << "Average KDTree visit count: " << double(totKDTreeVisitCount) * 100. / double(itCount * d.cols()) << " %" << endl; return 0; }
35.467066
180
0.650346
HIPERT-SRL
6f4fe5bc42841fbf76bea2508a67be5874d8abff
836
cpp
C++
application/main.cpp
Italo1994/SimuladorMips
075bfd9e1bc6e47f8c37f14208afe450bfad46b1
[ "MIT" ]
null
null
null
application/main.cpp
Italo1994/SimuladorMips
075bfd9e1bc6e47f8c37f14208afe450bfad46b1
[ "MIT" ]
null
null
null
application/main.cpp
Italo1994/SimuladorMips
075bfd9e1bc6e47f8c37f14208afe450bfad46b1
[ "MIT" ]
null
null
null
#include "conjuntoInstrucoes.h" #include "operador.h" #include "registrador.h" #include "tokenizacao.h" #include "pipeline.h" #include "dependencias.h" //#include "tela.h" #include <iostream> #include <string> #include <vector> using namespace std; int main() { //Simulador simulador; //simulador.criarInstrucoes(); //mostrarNaTela(9); //Registrador registrador[32]; //Operador operador[7]; vector<vector<string> > matrizInstrucoes; //criarRegistradores(registrador); //mostrarRegistradores(registrador); //criarOperadores(operador); //mostrarOperadores(operador); cout << endl; inicializarInstrucoes(&matrizInstrucoes, 3); //mostrarInstrucoes(matrizInstrucoes); //pipeline(2, matrizInstrucoes, 1); verificarDependencias(matrizInstrucoes, 3); //verificarDependencias(matrizInstrucoes, 2); return 0; }
17.061224
46
0.741627
Italo1994
6f568b8959b2d624e7df9210b2fa793e83de6fd0
11,250
hpp
C++
public/anton/algorithm.hpp
kociap/atl
a7dc9b35c14453040db82dbbeca3c305bb25c66e
[ "MIT" ]
null
null
null
public/anton/algorithm.hpp
kociap/atl
a7dc9b35c14453040db82dbbeca3c305bb25c66e
[ "MIT" ]
null
null
null
public/anton/algorithm.hpp
kociap/atl
a7dc9b35c14453040db82dbbeca3c305bb25c66e
[ "MIT" ]
1
2020-12-15T13:51:38.000Z
2020-12-15T13:51:38.000Z
#pragma once #include <anton/algorithm/sort.hpp> #include <anton/array.hpp> #include <anton/iterators.hpp> #include <anton/math/math.hpp> #include <anton/memory.hpp> #include <anton/pair.hpp> #include <anton/swap.hpp> namespace anton { // fill_with_consecutive // Fills range [first, last[ with consecutive values starting at value. // template<typename Forward_Iterator, typename T> void fill_with_consecutive(Forward_Iterator first, Forward_Iterator last, T value) { for(; first != last; ++first, ++value) { *first = value; } } // find // Linearily searches the range [first, last[. // // Returns: The iterator to the first element in the range [first, last[ that satisfies // the condition *iterator == value or last if no such iterator is found. // // Complexity: At most 'last - first' comparisons. // template<typename Input_Iterator, typename T> [[nodiscard]] Input_Iterator find(Input_Iterator first, Input_Iterator last, T const& value) { while(first != last && *first != value) { ++first; } return first; } // find_if // Linearily searches the range [first, last[. // // Returns: The iterator to the first element in the range [first, last[ that satisfies // the condition predicate(*iterator) == true or last if no such iterator is found. // // Complexity: At most 'last - first' applications of the predicate. // template<typename Input_Iterator, typename Predicate> [[nodiscard]] Input_Iterator find_if(Input_Iterator first, Input_Iterator last, Predicate predicate) { while(first != last && !predicate(*first)) { ++first; } return first; } template<typename Input_Iterator, typename Predicate> [[nodiscard]] bool any_of(Input_Iterator first, Input_Iterator last, Predicate predicate) { for(; first != last; ++first) { if(predicate(*first)) { return true; } } return false; } // rotate_left // Performs left rotation on the range by swapping elements so that middle becomes the first element. // [first, last[ must be a valid range, middle must be within [first, last[. // // This function works on forward iterators meaning it supports lists, however you can get much better // performance by using splice operations instead (O(1) instead of O(n)). // // Returns: Position of the first element after rotate. // // Complexity: At most last - first swaps. // template<typename Forward_Iterator> Forward_Iterator rotate_left(Forward_Iterator first, Forward_Iterator middle, Forward_Iterator last) { using anton::swap; Forward_Iterator i = middle; while(true) { swap(*first, *i); ++first; ++i; if(i == last) { break; } if(first == middle) { middle = i; } } Forward_Iterator r = first; if(first != middle) { i = middle; while(true) { swap(*first, *i); ++first; ++i; if(i == last) { if(first == middle) { break; } i = middle; } else if(first == middle) { middle = i; } } } return r; } // unique // Eliminates all except the first element from every consecutive group of equivalent elements from // the range [first, last[ and returns a past-the-end iterator for the new logical end of the range. // template<typename Forward_Iterator, typename Predicate> Forward_Iterator unique(Forward_Iterator first, Forward_Iterator last, Predicate predicate) { if(first == last) { return last; } // Find first group that consists of > 2 duplicates. Forward_Iterator next = first; ++next; while(next != last && !predicate(*first, *next)) { ++first; ++next; } if(next != last) { for(; next != last; ++next) { if(!predicate(*first, *next)) { ++first; *first = ANTON_MOV(*next); } } return ++first; } else { return last; } } // unique // Eliminates all except the first element from every consecutive group of equivalent elements from // the range [first, last[ and returns a past-the-end iterator for the new logical end of the range. // template<typename Forward_Iterator> Forward_Iterator unique(Forward_Iterator first, Forward_Iterator last) { using value_type = typename Iterator_Traits<Forward_Iterator>::value_type; return unique(first, last, [](value_type const& lhs, value_type const& rhs) { return lhs == rhs; }); } // set_difference // Copies elements from [first1, last1[ that are not present in [first2, last2[ to // the destination range starting at dest. // // Requires: // Both input ranges must be sorted and neither must overlap with destination range. // (*first1 < *first2) and (*first2 < *first1) must be valid expressions. // // Returns: The end of the destination range. // // Complexity: TODO // template<typename Input_Iterator1, typename Input_Iterator2, typename Output_Iterator> Output_Iterator set_difference(Input_Iterator1 first1, Input_Iterator1 last1, Input_Iterator2 first2, Input_Iterator2 last2, Output_Iterator dest) { while(first1 != last1 && first2 != last2) { if(*first1 < *first2) { *dest = *first1; ++dest; ++first1; } else if(*first2 < *first1) { ++first2; } else { ++first1; ++first2; } } for(; first1 != last1; ++first1, ++dest) { *dest = *first1; } return dest; } // set_difference overload with custom comparison predicate which enforces strict ordering (<). // template<typename Input_Iterator1, typename Input_Iterator2, typename Output_Iterator, typename Compare> Output_Iterator set_difference(Input_Iterator1 first1, Input_Iterator1 last1, Input_Iterator2 first2, Input_Iterator2 last2, Output_Iterator dest, Compare compare) { while(first1 != last1 && first2 != last2) { if(compare(*first1, *first2)) { *dest = *first1; ++dest; ++first1; } else if(compare(*first2, *first1)) { ++first2; } else { ++first1; ++first2; } } for(; first1 != last1; ++first1, ++dest) { *dest = *first1; } return dest; } // mismatch // Finds the first mismatching pair of elements in the two ranges // defined by [first1, last1[ and [first2, first2 + (last1 - first1)[. // The elements are compared using operator==. // // Parameters: // first1, last1 - first range of elements. // first2, last2 - seconds range of elements. // p - predicate that returns true when the elements should be treated as equal. // The signature should be equivalent to bool(Type1 const&, Type2 const&) // // Returns: // Pair of iterators to the first elements that are not equal. // If no mismatches are found, one or both iterators are the end iterators. // template<typename Input_Iterator1, typename Input_Iterator2> Pair<Input_Iterator1, Input_Iterator2> mismatch(Input_Iterator1 first1, Input_Iterator1 last1, Input_Iterator2 first2) { while(first1 != last1 && *first1 == *first2) { ++first1; ++first2; } return {first1, first2}; } // mismatch // Finds the first mismatching pair of elements in the two ranges // defined by [first1, last1[ and [first2, first2 + (last1 - first1)[. // The elements are compared using the predicate p. // // Parameters: // first1, last1 - first range of elements. // first2, last2 - seconds range of elements. // p - predicate that returns true when the elements should be treated as equal. // The signature should be equivalent to bool(Type1 const&, Type2 const&) // // Returns: // Pair of iterators to the first elements that are not equal. // If no mismatches are found, one or both iterators are the end iterators. // template<typename Input_Iterator1, typename Input_Iterator2, typename Predicate> Pair<Input_Iterator1, Input_Iterator2> mismatch(Input_Iterator1 first1, Input_Iterator1 last1, Input_Iterator2 first2, Predicate p) { while(first1 != last1 && p(*first1, *first2)) { ++first1; ++first2; } return {first1, first2}; } // mismatch // Finds the first mismatching pair of elements in the two ranges defined by [first1, last1[ and [first2, last2[. // The elements are compared using operator==. // // Parameters: // first1, last1 - first range of elements. // first2, last2 - seconds range of elements. // // Returns: // Pair of iterators to the first elements that are not equal. // If no mismatches are found, one or both iterators are the end iterators. // template<typename Input_Iterator1, typename Input_Iterator2> Pair<Input_Iterator1, Input_Iterator2> mismatch(Input_Iterator1 first1, Input_Iterator1 last1, Input_Iterator2 first2, Input_Iterator2 last2) { while(first1 != last1 && first2 != last2 && *first1 == *first2) { ++first1; ++first2; } return {first1, first2}; } // mismatch // Finds the first mismatching pair of elements in the two ranges defined by [first1, last1[ and [first2, last2[. // The elements are compared using the predicate p. // // Parameters: // first1, last1 - first range of elements. // first2, last2 - seconds range of elements. // p - predicate that returns true when the elements should be treated as equal. // The signature should be equivalent to bool(Type1 const&, Type2 const&) // // Returns: // Pair of iterators to the first elements that are not equal. // If no mismatches are found, one or both iterators are the end iterators. // template<typename Input_Iterator1, typename Input_Iterator2, typename Predicate> Pair<Input_Iterator1, Input_Iterator2> mismatch(Input_Iterator1 first1, Input_Iterator1 last1, Input_Iterator2 first2, Input_Iterator2 last2, Predicate p) { while(first1 != last1 && first2 != last2 && p(*first1, *first2)) { ++first1; ++first2; } return {first1, first2}; } } // namespace anton
36.407767
160
0.594133
kociap
6f591527b2be7029eee4abfee918a2c3df84cc94
11,940
cc
C++
dcmpstat/libsrc/dvpsspl.cc
trice-imaging/dcmtk
60b158654dc7215d938a9ddba92ef5e93ded298d
[ "Apache-2.0" ]
10
2016-07-03T12:16:58.000Z
2021-12-18T06:15:50.000Z
dcmpstat/libsrc/dvpsspl.cc
trice-imaging/dcmtk
60b158654dc7215d938a9ddba92ef5e93ded298d
[ "Apache-2.0" ]
1
2020-04-30T07:55:55.000Z
2020-04-30T07:55:55.000Z
dcmpstat/libsrc/dvpsspl.cc
trice-imaging/dcmtk
60b158654dc7215d938a9ddba92ef5e93ded298d
[ "Apache-2.0" ]
9
2017-02-09T02:16:39.000Z
2021-01-06T02:49:24.000Z
/* * * Copyright (C) 1998-2010, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmpstat * * Author: Marco Eichelberg * * Purpose: * classes: DVPSStoredPrint_PList * */ #include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */ #include "dcmtk/dcmpstat/dvpsspl.h" #include "dcmtk/dcmpstat/dvpssp.h" /* for DVPSStoredPrint */ #include "dcmtk/dcmpstat/dvpsib.h" /* for DVPSImageBoxContent */ #include "dcmtk/dcmpstat/dviface.h" #include "dcmtk/dcmpstat/dvpsdef.h" #include "dcmtk/dcmpstat/dvpsov.h" /* for DVPSOverlay, needed by MSVC5 with STL */ #include "dcmtk/dcmpstat/dvpsgl.h" /* for DVPSGraphicLayer, needed by MSVC5 with STL */ #include "dcmtk/dcmpstat/dvpsrs.h" /* for DVPSReferencedSeries, needed by MSVC5 with STL */ #include "dcmtk/dcmpstat/dvpsal.h" /* for DVPSOverlayCurveActivationLayer, needed by MSVC5 with STL */ #include "dcmtk/dcmpstat/dvpsga.h" /* for DVPSGraphicAnnotation, needed by MSVC5 with STL */ #include "dcmtk/dcmpstat/dvpscu.h" /* for DVPSCurve, needed by MSVC5 with STL */ #include "dcmtk/dcmpstat/dvpsvl.h" /* for DVPSVOILUT, needed by MSVC5 with STL */ #include "dcmtk/dcmpstat/dvpsvw.h" /* for DVPSVOIWindow, needed by MSVC5 with STL */ #include "dcmtk/dcmpstat/dvpsda.h" /* for DVPSDisplayedArea, needed by MSVC5 with STL */ #include "dcmtk/dcmpstat/dvpssv.h" /* for DVPSSoftcopyVOI, needed by MSVC5 with STL */ #include "dcmtk/dcmpstat/dvpsab.h" /* for DVPSAnnotationContent, needed by MSVC5 with STL */ #include "dcmtk/dcmpstat/dvpstx.h" /* for DVPSTextObject, needed by MSVC5 with STL */ #include "dcmtk/dcmpstat/dvpsgr.h" /* for DVPSGraphicObject, needed by MSVC5 with STL */ #include "dcmtk/dcmpstat/dvpsri.h" /* for DVPSReferencedImage, needed by MSVC5 with STL */ DVPSStoredPrint_PList::DVPSStoredPrint_PList() : list_() { } DVPSStoredPrint_PList::DVPSStoredPrint_PList(const DVPSStoredPrint_PList &arg) : list_() { OFListConstIterator(DVPSStoredPrint *) first = arg.list_.begin(); OFListConstIterator(DVPSStoredPrint *) last = arg.list_.end(); while (first != last) { list_.push_back((*first)->clone()); ++first; } } DVPSStoredPrint_PList::~DVPSStoredPrint_PList() { clear(); } void DVPSStoredPrint_PList::clear() { OFListIterator(DVPSStoredPrint *) first = list_.begin(); OFListIterator(DVPSStoredPrint *) last = list_.end(); while (first != last) { delete (*first); first = list_.erase(first); } } void DVPSStoredPrint_PList::printSCPBasicFilmBoxSet( DVConfiguration& cfg, const char *cfgname, T_DIMSE_Message& rq, DcmDataset *rqDataset, T_DIMSE_Message& rsp, DcmDataset *& rspDataset, OFBool presentationLUTnegotiated, DVPSPresentationLUT_PList& globalPresentationLUTList) { OFListIterator(DVPSStoredPrint *) first = list_.begin(); OFListIterator(DVPSStoredPrint *) last = list_.end(); OFBool found = OFFalse; while ((first != last) && (!found)) { if ((*first)->isFilmBoxInstance(rq.msg.NSetRQ.RequestedSOPInstanceUID)) found = OFTrue; else ++first; } if (found) { DVPSStoredPrint *newSP = new DVPSStoredPrint(*(*first)); if (newSP) { if (newSP->printSCPSet(cfg, cfgname, rqDataset, rsp, rspDataset, presentationLUTnegotiated, globalPresentationLUTList)) { // N-SET successful, replace entry in list delete (*first); list_.erase(first); list_.push_back(newSP); } else delete newSP; } else { DCMPSTAT_WARN("cannot update film box, out of memory."); rsp.msg.NSetRSP.DimseStatus = STATUS_N_ProcessingFailure; } } else { // film box does not exist or wrong instance UID DCMPSTAT_WARN("cannot update film box, object not found."); rsp.msg.NSetRSP.DimseStatus = STATUS_N_NoSuchObjectInstance; } } void DVPSStoredPrint_PList::printSCPBasicGrayscaleImageBoxSet( DVInterface& cfg, const char *cfgname, T_DIMSE_Message& rq, DcmDataset *rqDataset, T_DIMSE_Message& rsp, DcmDataset *& rspDataset, OFBool presentationLUTnegotiated) { OFListIterator(DVPSStoredPrint *) first = list_.begin(); OFListIterator(DVPSStoredPrint *) last = list_.end(); DVPSStoredPrint *sp = NULL; DVPSImageBoxContent *newib = NULL; while ((first != last) && (sp == NULL)) { newib = (*first)->duplicateImageBox(rq.msg.NSetRQ.RequestedSOPInstanceUID); if (newib) sp = *first; else ++first; } if (newib && sp) { DcmFileFormat imageFile; DcmDataset *imageDataset = imageFile.getDataset(); if (newib->printSCPSet(cfg, cfgname, rqDataset, rsp, rspDataset, *imageDataset, sp->getReferencedPresentationLUTAlignment(), presentationLUTnegotiated)) { if (EC_Normal == sp->writeHardcopyImageAttributes(*imageDataset)) { // check for image position clash if (sp->haveImagePositionClash(rq.msg.NSetRQ.RequestedSOPInstanceUID, newib->getImageBoxPosition())) { delete rspDataset; rspDataset = NULL; DCMPSTAT_WARN("cannot update basic grayscale image box, image position collision."); rsp.msg.NSetRSP.DimseStatus = STATUS_N_InvalidAttributeValue; } else { if (EC_Normal == cfg.saveFileFormatToDB(imageFile)) { sp->replaceImageBox(newib); } else { delete rspDataset; rspDataset = NULL; rsp.msg.NSetRSP.DimseStatus = STATUS_N_ProcessingFailure; } } } else { delete rspDataset; rspDataset = NULL; DCMPSTAT_WARN("cannot update basic grayscale image box, out of memory."); rsp.msg.NSetRSP.DimseStatus = STATUS_N_ProcessingFailure; } } } else { // image box does not exist or wrong instance UID DCMPSTAT_WARN("cannot update basic grayscale image box, object not found."); rsp.msg.NSetRSP.DimseStatus = STATUS_N_NoSuchObjectInstance; } } void DVPSStoredPrint_PList::printSCPBasicFilmBoxAction( DVInterface& cfg, const char *cfgname, T_DIMSE_Message& rq, T_DIMSE_Message& rsp, DVPSPresentationLUT_PList& globalPresentationLUTList) { OFListIterator(DVPSStoredPrint *) first = list_.begin(); OFListIterator(DVPSStoredPrint *) last = list_.end(); OFBool found = OFFalse; while ((first != last) && (!found)) { if ((*first)->isFilmBoxInstance(rq.msg.NActionRQ.RequestedSOPInstanceUID)) found = OFTrue; else ++first; } if (found) { DcmFileFormat spFile; DcmDataset *spDataset = spFile.getDataset(); DVPSStoredPrint *sp = *first; OFBool writeRequestedImageSize = cfg.getTargetPrinterSupportsRequestedImageSize(cfgname); sp->updatePresentationLUTList(globalPresentationLUTList); sp->clearInstanceUID(); if ((*first)->emptyPageWarning()) { DCMPSTAT_INFO("empty page, will not be stored in database"); if (STATUS_Success == rsp.msg.NActionRSP.DimseStatus) rsp.msg.NActionRSP.DimseStatus = STATUS_N_PRINT_BFB_Warn_EmptyPage; } else { if (EC_Normal == sp->write(*spDataset, writeRequestedImageSize, OFFalse, OFFalse, OFTrue)) { if (EC_Normal == cfg.saveFileFormatToDB(spFile)) { // N-ACTION successful. } else { rsp.msg.NActionRSP.DimseStatus = STATUS_N_ProcessingFailure; } } else { DCMPSTAT_WARN("cannot print basic film box, out of memory."); rsp.msg.NActionRSP.DimseStatus = STATUS_N_ProcessingFailure; } } } else { // film box does not exist or wrong instance UID DCMPSTAT_WARN("cannot print film box, object not found."); rsp.msg.NActionRSP.DimseStatus = STATUS_N_NoSuchObjectInstance; } } void DVPSStoredPrint_PList::printSCPBasicFilmSessionAction( DVInterface& cfg, const char *cfgname, T_DIMSE_Message& rsp, DVPSPresentationLUT_PList& globalPresentationLUTList) { if (size() > 0) { OFBool writeRequestedImageSize = cfg.getTargetPrinterSupportsRequestedImageSize(cfgname); OFListIterator(DVPSStoredPrint *) first = list_.begin(); OFListIterator(DVPSStoredPrint *) last = list_.end(); while (first != last) { DcmFileFormat spFile; DcmDataset *spDataset = spFile.getDataset(); (*first)->updatePresentationLUTList(globalPresentationLUTList); (*first)->clearInstanceUID(); if ((*first)->emptyPageWarning()) { DCMPSTAT_INFO("empty page, will not be stored in database"); if (STATUS_Success == rsp.msg.NActionRSP.DimseStatus) rsp.msg.NActionRSP.DimseStatus = STATUS_N_PRINT_BFS_Warn_EmptyPage; } else { if (EC_Normal == (*first)->write(*spDataset, writeRequestedImageSize, OFFalse, OFFalse, OFTrue)) { if (EC_Normal == cfg.saveFileFormatToDB(spFile)) { // success for this film box } else { rsp.msg.NActionRSP.DimseStatus = STATUS_N_ProcessingFailure; } } else { DCMPSTAT_WARN("cannot print basic film session, out of memory."); rsp.msg.NActionRSP.DimseStatus = STATUS_N_ProcessingFailure; } } ++first; } } else { // no film boxes to print DCMPSTAT_WARN("cannot print film session, no film box."); rsp.msg.NActionRSP.DimseStatus = STATUS_N_PRINT_BFS_Fail_NoFilmBox; } } void DVPSStoredPrint_PList::printSCPBasicFilmBoxDelete(T_DIMSE_Message& rq, T_DIMSE_Message& rsp) { OFListIterator(DVPSStoredPrint *) first = list_.begin(); OFListIterator(DVPSStoredPrint *) last = list_.end(); OFBool found = OFFalse; while ((first != last) && (!found)) { if ((*first)->isFilmBoxInstance(rq.msg.NDeleteRQ.RequestedSOPInstanceUID)) found = OFTrue; else ++first; } if (found) { delete (*first); list_.erase(first); } else { // film box does not exist or wrong instance UID DCMPSTAT_WARN("cannot delete film box with instance UID '" << rq.msg.NDeleteRQ.RequestedSOPInstanceUID << "': object does not exist."); rsp.msg.NDeleteRSP.DimseStatus = STATUS_N_NoSuchObjectInstance; } } OFBool DVPSStoredPrint_PList::haveFilmBoxInstance(const char *uid) { if (uid==NULL) return OFFalse; OFListIterator(DVPSStoredPrint *) first = list_.begin(); OFListIterator(DVPSStoredPrint *) last = list_.end(); while (first != last) { if ((*first)->isFilmBoxInstance(uid)) return OFTrue; else ++first; } return OFFalse; } OFBool DVPSStoredPrint_PList::usesPresentationLUT(const char *uid) { if (uid==NULL) return OFFalse; OFListIterator(DVPSStoredPrint *) first = list_.begin(); OFListIterator(DVPSStoredPrint *) last = list_.end(); while (first != last) { if ((*first)->usesPresentationLUT(uid)) return OFTrue; else ++first; } return OFFalse; } OFBool DVPSStoredPrint_PList::matchesPresentationLUT(DVPSPrintPresentationLUTAlignment align) const { OFBool result = OFTrue; OFListConstIterator(DVPSStoredPrint *) first = list_.begin(); OFListConstIterator(DVPSStoredPrint *) last = list_.end(); while (first != last) { result = result && (*first)->matchesPresentationLUT(align); ++first; } return result; } void DVPSStoredPrint_PList::overridePresentationLUTSettings( DcmUnsignedShort& newIllumination, DcmUnsignedShort& newReflectedAmbientLight, DcmUniqueIdentifier& newReferencedPLUT, DVPSPrintPresentationLUTAlignment newAlignment) { OFListIterator(DVPSStoredPrint *) first = list_.begin(); OFListIterator(DVPSStoredPrint *) last = list_.end(); while (first != last) { (*first)->overridePresentationLUTSettings(newIllumination, newReflectedAmbientLight, newReferencedPLUT, newAlignment); ++first; } }
33.633803
139
0.687102
trice-imaging
6f5b5c581e62b3d363fc5bd1a32840b839d2bf77
1,736
cpp
C++
src/helpers/Utils.cpp
mnaveedb/finalmq
3c3b2b213fa07bb5427a1364796b19d732890ed2
[ "MIT" ]
11
2020-10-13T11:50:29.000Z
2022-02-27T11:47:34.000Z
src/helpers/Utils.cpp
mnaveedb/finalmq
3c3b2b213fa07bb5427a1364796b19d732890ed2
[ "MIT" ]
15
2020-10-07T18:01:27.000Z
2021-07-08T09:09:13.000Z
src/helpers/Utils.cpp
mnaveedb/finalmq
3c3b2b213fa07bb5427a1364796b19d732890ed2
[ "MIT" ]
2
2020-10-07T21:29:06.000Z
2020-10-14T18:02:17.000Z
//MIT License //Copyright (c) 2020 bexoft GmbH ([email protected]) //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 "finalmq/helpers/Utils.h" #include <assert.h> namespace finalmq { void Utils::split(const std::string& src, ssize_t indexBegin, ssize_t indexEnd, char delimiter, std::vector<std::string>& dest) { while (indexBegin < indexEnd) { size_t pos = src.find_first_of(delimiter, indexBegin); if (pos == std::string::npos || static_cast<ssize_t>(pos) > indexEnd) { pos = indexEnd; } ssize_t len = pos - indexBegin; assert(len >= 0); dest.emplace_back(&src[indexBegin], len); indexBegin += len + 1; } } } // namespace finalmq
37.73913
127
0.718318
mnaveedb
6f5bca818e2a3c464f8effe2a8604306e66e4ab7
327
cpp
C++
Semestr_1/HomeWork_11/Number_1/Number_1/test.cpp
SaveliyLipaev/HomeWork
06994ce6ab6f12dd69507fffb6f2d3ba361f0069
[ "MIT" ]
null
null
null
Semestr_1/HomeWork_11/Number_1/Number_1/test.cpp
SaveliyLipaev/HomeWork
06994ce6ab6f12dd69507fffb6f2d3ba361f0069
[ "MIT" ]
1
2018-11-06T05:30:37.000Z
2018-11-06T05:30:37.000Z
Semestr_1/HomeWork_11/Number_1/Number_1/test.cpp
SaveliyLipaev/HomeWork
06994ce6ab6f12dd69507fffb6f2d3ba361f0069
[ "MIT" ]
null
null
null
#include "KMP.h" using namespace std; int readAndTest(string str) { ifstream file("Text.txt"); int temp = find(file, str); file.close(); return temp; } bool test() { string str1 = "dda"; string str2 = "fff"; string str3 = "egj"; return readAndTest(str1) == -1 && readAndTest(str2) == 40 && readAndTest(str3) == 17; }
17.210526
86
0.642202
SaveliyLipaev
6f5d00c5fc96374548bde085971e7a8b45fecae6
14,791
cpp
C++
tests/LineTests.cpp
lindale-dev/MathGeoLib
bdd01c86b2d1450dfa323366e3b6646e2796e873
[ "Apache-2.0" ]
null
null
null
tests/LineTests.cpp
lindale-dev/MathGeoLib
bdd01c86b2d1450dfa323366e3b6646e2796e873
[ "Apache-2.0" ]
null
null
null
tests/LineTests.cpp
lindale-dev/MathGeoLib
bdd01c86b2d1450dfa323366e3b6646e2796e873
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include "../src/MathGeoLib.h" #include "../src/Math/myassert.h" #include "TestRunner.h" MATH_IGNORE_UNUSED_VARS_WARNING Line RandomLineContainingPoint(const vec &pt); Ray RandomRayContainingPoint(const vec &pt); LineSegment RandomLineSegmentContainingPoint(const vec &pt); RANDOMIZED_TEST(ParallelLineLineClosestPoint) { vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); Line a = RandomLineContainingPoint(pt); Line b = a; vec displacement = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); b.pos += displacement; if (rng.Int()%2) b.dir = -b.dir; float d, d2; vec closestPointA = a.ClosestPoint(b, d, d2); vec closestPointB = b.GetPoint(d2); vec perpDistance = displacement - displacement.ProjectTo(a.dir); mgl_assert2(EqualAbs(closestPointA.Distance(closestPointB), perpDistance.Length()), closestPointA.Distance(closestPointB), perpDistance.Length()); } RANDOMIZED_TEST(ParallelLineRayClosestPoint) { vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); Line a = RandomLineContainingPoint(pt); Ray b; vec displacement = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); b.pos = a.pos + displacement; b.dir = a.dir; if (rng.Int()%2) b.dir = -b.dir; float d, d2; vec closestPointA = a.ClosestPoint(b, d, d2); vec closestPointB = b.GetPoint(d2); vec perpDistance = displacement - displacement.ProjectTo(a.dir); mgl_assert2(EqualAbs(closestPointA.Distance(closestPointB), perpDistance.Length()), closestPointA.Distance(closestPointB), perpDistance.Length()); } RANDOMIZED_TEST(ParallelLineLineSegmentClosestPoint) { vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); Line a = RandomLineContainingPoint(pt); LineSegment b; vec displacement = vec::RandomBox(rng, DIR_VEC_SCALAR(-SCALE), DIR_VEC_SCALAR(SCALE)); b.a = a.pos + displacement; float len = rng.Float(1e-3f, SCALE) * (rng.Int(0,1) ? 1.f : -1.f); b.b = b.a + len * a.dir; float d, d2; vec closestPointA = a.ClosestPoint(b, d, d2); vec closestPointB = b.GetPoint(d2); vec perpDistance = displacement - displacement.ProjectTo(a.dir); mgl_assert2(EqualAbs(closestPointA.Distance(closestPointB), perpDistance.Length()), closestPointA.Distance(closestPointB), perpDistance.Length()); } RANDOMIZED_TEST(ParallelRayRayClosestPoint) { vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); Ray a = RandomRayContainingPoint(pt); Ray b = a; vec displacement = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); b.pos += displacement; if (rng.Int()%2) b.dir = -b.dir; float d, d2; vec closestPointA = a.ClosestPoint(b, d, d2); vec closestPointB = b.GetPoint(d2); float cpd = closestPointA.Distance(closestPointB); mgl_assert(cpd <= displacement.Length()+1e-4f); MARK_UNUSED(cpd); float t = a.pos.Distance(b.pos); mgl_assert(cpd <= t+1e-4f); MARK_UNUSED(t); } RANDOMIZED_TEST(ParallelRayLineSegmentClosestPoint) { vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); Ray a = RandomRayContainingPoint(pt); LineSegment b; vec displacement = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); b.a = a.pos + displacement; vec dir = rng.Float(1e-3f, SCALE) * a.dir; if (rng.Int()%2) dir = -dir; b.b = b.a + dir; float d, d2; vec closestPointA = a.ClosestPoint(b, d, d2); vec closestPointB = b.GetPoint(d2); float cpd = closestPointA.Distance(closestPointB); mgl_assert(cpd <= displacement.Length()+1e-4f); MARK_UNUSED(cpd); float t1 = a.pos.Distance(b.a); float t2 = a.pos.Distance(b.b); mgl_assert(cpd <= t1+1e-4f); mgl_assert(cpd <= t2+1e-4f); MARK_UNUSED(t1); MARK_UNUSED(t2); } RANDOMIZED_TEST(ParallelLineSegmentLineSegmentClosestPoint) { vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); LineSegment a = RandomLineSegmentContainingPoint(pt); LineSegment b; vec displacement = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); b.a = a.a + displacement; if (rng.Int()%2) { vec dir = (b.a - a.a).ScaledToLength(rng.Float(1e-3f, SCALE)); if (rng.Int()%2) dir = -dir; b.b = b.a + dir; } else { b.b = a.b + displacement; } if (rng.Int()%2) std::swap(b.a, b.b); float d, d2; vec closestPointA = a.ClosestPoint(b, d, d2); vec closestPointB = b.GetPoint(d2); float cpd = closestPointA.Distance(closestPointB); mgl_assert(cpd <= displacement.Length()+1e-4f); MARK_UNUSED(cpd); float t1 = a.a.Distance(b.a); float t2 = a.a.Distance(b.b); float t3 = a.b.Distance(b.a); float t4 = a.b.Distance(b.b); mgl_assert(cpd <= t1+1e-4f); mgl_assert(cpd <= t2+1e-4f); mgl_assert(cpd <= t3+1e-4f); mgl_assert(cpd <= t4+1e-4f); MARK_UNUSED(t1); MARK_UNUSED(t2); MARK_UNUSED(t3); MARK_UNUSED(t4); } RANDOMIZED_TEST(LineLineClosestPoint) { vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); vec pt2 = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); Line a = RandomLineContainingPoint(pt); Line b = RandomLineContainingPoint(pt2); float d, d2; vec closestPointA = a.ClosestPoint(b, d, d2); mgl_assert3(closestPointA.Equals(a.GetPoint(d), 1e-2f), closestPointA, a.GetPoint(d), closestPointA.Distance(a.GetPoint(d))); vec closestPointB = b.GetPoint(d2); float D, D2; vec closestPointB2 = b.ClosestPoint(a, D, D2); mgl_assert2(EqualAbs(d, D2, 1e-2f) || EqualRel(d, D2, 1e-2f), d, D2); mgl_assert2(EqualAbs(D, d2, 1e-2f) || EqualRel(D, d2, 1e-2f), D, d2); mgl_assert2(closestPointB.Equals(closestPointB2, 1e-2f), closestPointB.SerializeToCodeString(), closestPointB2.SerializeToCodeString()); vec closestPointA2 = a.GetPoint(D2); mgl_assert2(closestPointA.Equals(closestPointA2, 1e-2f), closestPointA.SerializeToCodeString(), closestPointA2.SerializeToCodeString()); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, pt.Distance(pt2) + 1e-3f); mgl_assert(EqualAbs(a.Distance(b), closestPointA.Distance(closestPointB), 1e-2f)); mgl_assert(EqualAbs(b.Distance(a), closestPointA.Distance(closestPointB), 1e-2f)); } RANDOMIZED_TEST(LineRayClosestPoint) { vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); vec pt2 = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); Line a = RandomLineContainingPoint(pt); Ray b = RandomRayContainingPoint(pt2); float d, d2; vec closestPointA = a.ClosestPoint(b, d, d2); vec closestPointAd = a.GetPoint(d); mgl_assert3(closestPointA.Equals(closestPointAd, 1e-1f), closestPointA, closestPointAd, closestPointA.Distance(closestPointAd)); vec closestPointB = b.GetPoint(d2); float D, D2; vec closestPointB2 = b.ClosestPoint(a, D, D2); // mgl_assert2(EqualAbs(d, D2, 1e-2f) || EqualRel(d, D2, 1e-2f), d, D2); // mgl_assert2(EqualAbs(D, d2, 1e-2f) || EqualRel(D, d2, 1e-2f), D, d2); mgl_assert(closestPointB.Equals(closestPointB2, 1e-1f)); vec closestPointA2 = a.GetPoint(D2); mgl_assert(closestPointA.Equals(closestPointA2, 1e-1f)); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, pt.Distance(pt2) + 1e-2f); mgl_assert(EqualAbs(a.Distance(b), closestPointA.Distance(closestPointB), 1e-1f)); mgl_assert(EqualAbs(b.Distance(a), closestPointA.Distance(closestPointB), 1e-1f)); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointA.Distance(b.pos) + 1e-2f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, a.Distance(b.pos) + 1e-2f); } RANDOMIZED_TEST(LineLineSegmentClosestPoint) { vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); vec pt2 = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); Line a = RandomLineContainingPoint(pt); LineSegment b = RandomLineSegmentContainingPoint(pt2); float d, d2; vec closestPointA = a.ClosestPoint(b, d, d2); mgl_assert3(closestPointA.Equals(a.GetPoint(d), 1e-2f), closestPointA, a.GetPoint(d), closestPointA.Distance(a.GetPoint(d))); vec closestPointB = b.GetPoint(d2); float D, D2; vec closestPointB2 = b.ClosestPoint(a, D, D2); // mgl_assert2(EqualAbs(d, D2, 1e-2f) || EqualRel(d, D2, 1e-2f), d, D2); // mgl_assert2(EqualAbs(D, d2, 1e-2f) || EqualRel(D, d2, 1e-2f), D, d2); mgl_assert2(closestPointB.Equals(closestPointB2, 1e-2f), closestPointB.SerializeToCodeString(), closestPointB2.SerializeToCodeString()); vec closestPointA2 = a.GetPoint(D2); mgl_assert2(closestPointA.Equals(closestPointA2, 1e-2f), closestPointA.SerializeToCodeString(), closestPointA2.SerializeToCodeString()); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, pt.Distance(pt2) + 1e-3f); mgl_assert(EqualAbs(a.Distance(b), closestPointA.Distance(closestPointB), 1e-2f)); mgl_assert(EqualAbs(b.Distance(a), closestPointA.Distance(closestPointB), 1e-2f)); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointA.Distance(b.a) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointA.Distance(b.b) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, a.Distance(b.a) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, a.Distance(b.b) + 1e-3f); } RANDOMIZED_TEST(RayRayClosestPoint) { vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); vec pt2 = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); Ray a = RandomRayContainingPoint(pt); Ray b = RandomRayContainingPoint(pt2); float d, d2; vec closestPointA = a.ClosestPoint(b, d, d2); vec closestPointA2 = a.GetPoint(d); mgl_assert3(closestPointA.Equals(closestPointA2, 1e-2f), closestPointA, closestPointA2, closestPointA.Distance(closestPointA2)); vec closestPointB = b.GetPoint(d2); float D, D2; vec closestPointB2 = b.ClosestPoint(a, D, D2); // mgl_assert2(EqualAbs(d, D2, 1e-2f) || EqualRel(d, D2, 1e-2f), d, D2); // mgl_assert2(EqualAbs(D, d2, 1e-2f) || EqualRel(D, d2, 1e-2f), D, d2); mgl_assert2(closestPointB.Equals(closestPointB2, 1e-2f), closestPointB.SerializeToCodeString(), closestPointB2.SerializeToCodeString()); closestPointA2 = a.GetPoint(D2); mgl_assert2(closestPointA.Equals(closestPointA2, 1e-2f), closestPointA.SerializeToCodeString(), closestPointA2.SerializeToCodeString()); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, pt.Distance(pt2) + 1e-3f); mgl_assert(EqualAbs(a.Distance(b), closestPointA.Distance(closestPointB), 1e-2f)); mgl_assert(EqualAbs(b.Distance(a), closestPointA.Distance(closestPointB), 1e-2f)); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointA.Distance(b.pos) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, a.Distance(b.pos) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointB.Distance(a.pos) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, b.Distance(a.pos) + 1e-3f); } RANDOMIZED_TEST(RayLineSegmentClosestPoint) { vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); vec pt2 = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); Ray a = RandomRayContainingPoint(pt); LineSegment b = RandomLineSegmentContainingPoint(pt2); float d, d2; vec closestPointA = a.ClosestPoint(b, d, d2); mgl_assert3(closestPointA.Equals(a.GetPoint(d), 1e-2f), closestPointA, a.GetPoint(d), closestPointA.Distance(a.GetPoint(d))); vec closestPointB = b.GetPoint(d2); float D, D2; vec closestPointB2 = b.ClosestPoint(a, D, D2); // mgl_assert2(EqualAbs(d, D2, 1e-2f) || EqualRel(d, D2, 1e-2f), d, D2); // mgl_assert2(EqualAbs(D, d2, 1e-2f) || EqualRel(D, d2, 1e-2f), D, d2); mgl_assert2(closestPointB.Equals(closestPointB2, 1e-2f), closestPointB.SerializeToCodeString(), closestPointB2.SerializeToCodeString()); vec closestPointA2 = a.GetPoint(D2); mgl_assert2(closestPointA.Equals(closestPointA2, 1e-2f), closestPointA.SerializeToCodeString(), closestPointA2.SerializeToCodeString()); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, pt.Distance(pt2) + 1e-3f); mgl_assert(EqualAbs(a.Distance(b), closestPointA.Distance(closestPointB), 1e-2f)); mgl_assert(EqualAbs(b.Distance(a), closestPointA.Distance(closestPointB), 1e-2f)); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointA.Distance(b.a) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointA.Distance(b.b) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, a.Distance(b.a) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, a.Distance(b.b) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointB.Distance(a.pos) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, b.Distance(a.pos) + 1e-3f); } RANDOMIZED_TEST(LineSegmentLineSegmentClosestPoint) { vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); vec pt2 = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE)); LineSegment a = RandomLineSegmentContainingPoint(pt); LineSegment b = RandomLineSegmentContainingPoint(pt2); float d, d2; vec closestPointA = a.ClosestPoint(b, d, d2); mgl_assert3(closestPointA.Equals(a.GetPoint(d), 1e-2f), closestPointA, a.GetPoint(d), closestPointA.Distance(a.GetPoint(d))); vec closestPointB = b.GetPoint(d2); float D, D2; vec closestPointB2 = b.ClosestPoint(a, D, D2); // mgl_assert2(EqualAbs(d, D2, 1e-2f) || EqualRel(d, D2, 1e-2f), d, D2); // mgl_assert2(EqualAbs(D, d2, 1e-2f) || EqualRel(D, d2, 1e-2f), D, d2); mgl_assert2(closestPointB.Equals(closestPointB2, 1e-2f), closestPointB.SerializeToCodeString(), closestPointB2.SerializeToCodeString()); vec closestPointA2 = a.GetPoint(D2); mgl_assert2(closestPointA.Equals(closestPointA2, 1e-2f), closestPointA.SerializeToCodeString(), closestPointA2.SerializeToCodeString()); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, pt.Distance(pt2) + 1e-3f); mgl_assert(EqualAbs(a.Distance(b), closestPointA.Distance(closestPointB), 1e-2f)); mgl_assert(EqualAbs(b.Distance(a), closestPointA.Distance(closestPointB), 1e-2f)); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointA.Distance(b.a) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointA.Distance(b.b) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, a.Distance(b.a) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, a.Distance(b.b) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointB.Distance(a.a) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointB.Distance(a.b) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, b.Distance(a.a) + 1e-3f); mgl_assertcmp(closestPointA.Distance(closestPointB), <=, b.Distance(a.b) + 1e-3f); }
45.371166
147
0.747279
lindale-dev
6f5d4f14fed83eb31f03d6488066852d15840ad1
28,327
cc
C++
src/protos/Docflow/DocumentWithDocflowV3.pb.cc
Edw-K/diadocsdk-cpp
c50c5ceb5e0c897c9322bd7b66c028cdbc82047e
[ "MIT" ]
7
2016-05-31T17:37:54.000Z
2022-01-17T14:28:18.000Z
src/protos/Docflow/DocumentWithDocflowV3.pb.cc
Edw-K/diadocsdk-cpp
c50c5ceb5e0c897c9322bd7b66c028cdbc82047e
[ "MIT" ]
22
2017-02-07T09:34:02.000Z
2021-09-06T08:08:34.000Z
src/protos/Docflow/DocumentWithDocflowV3.pb.cc
Edw-K/diadocsdk-cpp
c50c5ceb5e0c897c9322bd7b66c028cdbc82047e
[ "MIT" ]
23
2016-06-07T06:11:47.000Z
2020-10-06T13:00:21.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Docflow/DocumentWithDocflowV3.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "Docflow/DocumentWithDocflowV3.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 Diadoc { namespace Api { namespace Proto { namespace Docflow { namespace { const ::google::protobuf::Descriptor* DocumentWithDocflowV3_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* DocumentWithDocflowV3_reflection_ = NULL; const ::google::protobuf::Descriptor* LastEvent_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* LastEvent_reflection_ = NULL; } // namespace void protobuf_AssignDesc_Docflow_2fDocumentWithDocflowV3_2eproto() { protobuf_AddDesc_Docflow_2fDocumentWithDocflowV3_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "Docflow/DocumentWithDocflowV3.proto"); GOOGLE_CHECK(file != NULL); DocumentWithDocflowV3_descriptor_ = file->message_type(0); static const int DocumentWithDocflowV3_offsets_[4] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DocumentWithDocflowV3, documentid_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DocumentWithDocflowV3, lastevent_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DocumentWithDocflowV3, documentinfo_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DocumentWithDocflowV3, docflow_), }; DocumentWithDocflowV3_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( DocumentWithDocflowV3_descriptor_, DocumentWithDocflowV3::default_instance_, DocumentWithDocflowV3_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DocumentWithDocflowV3, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DocumentWithDocflowV3, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(DocumentWithDocflowV3)); LastEvent_descriptor_ = file->message_type(1); static const int LastEvent_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LastEvent, eventid_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LastEvent, timestamp_), }; LastEvent_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( LastEvent_descriptor_, LastEvent::default_instance_, LastEvent_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LastEvent, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LastEvent, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(LastEvent)); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_Docflow_2fDocumentWithDocflowV3_2eproto); } void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( DocumentWithDocflowV3_descriptor_, &DocumentWithDocflowV3::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( LastEvent_descriptor_, &LastEvent::default_instance()); } } // namespace void protobuf_ShutdownFile_Docflow_2fDocumentWithDocflowV3_2eproto() { delete DocumentWithDocflowV3::default_instance_; delete DocumentWithDocflowV3_reflection_; delete LastEvent::default_instance_; delete LastEvent_reflection_; } void protobuf_AddDesc_Docflow_2fDocumentWithDocflowV3_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::Diadoc::Api::Proto::protobuf_AddDesc_DocumentId_2eproto(); ::Diadoc::Api::Proto::protobuf_AddDesc_Timestamp_2eproto(); ::Diadoc::Api::Proto::Docflow::protobuf_AddDesc_Docflow_2fDocumentInfoV3_2eproto(); ::Diadoc::Api::Proto::Docflow::protobuf_AddDesc_Docflow_2fDocflowV3_2eproto(); ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n#Docflow/DocumentWithDocflowV3.proto\022\030D" "iadoc.Api.Proto.Docflow\032\020DocumentId.prot" "o\032\017Timestamp.proto\032\034Docflow/DocumentInfo" "V3.proto\032\027Docflow/DocflowV3.proto\"\367\001\n\025Do" "cumentWithDocflowV3\0220\n\nDocumentId\030\001 \002(\0132" "\034.Diadoc.Api.Proto.DocumentId\0226\n\tLastEve" "nt\030\002 \002(\0132#.Diadoc.Api.Proto.Docflow.Last" "Event\022>\n\014DocumentInfo\030\003 \002(\0132(.Diadoc.Api" ".Proto.Docflow.DocumentInfoV3\0224\n\007Docflow" "\030\004 \002(\0132#.Diadoc.Api.Proto.Docflow.Docflo" "wV3\"L\n\tLastEvent\022\017\n\007EventId\030\001 \002(\t\022.\n\tTim" "estamp\030\002 \002(\0132\033.Diadoc.Api.Proto.Timestam" "p", 481); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "Docflow/DocumentWithDocflowV3.proto", &protobuf_RegisterTypes); DocumentWithDocflowV3::default_instance_ = new DocumentWithDocflowV3(); LastEvent::default_instance_ = new LastEvent(); DocumentWithDocflowV3::default_instance_->InitAsDefaultInstance(); LastEvent::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_Docflow_2fDocumentWithDocflowV3_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_Docflow_2fDocumentWithDocflowV3_2eproto { StaticDescriptorInitializer_Docflow_2fDocumentWithDocflowV3_2eproto() { protobuf_AddDesc_Docflow_2fDocumentWithDocflowV3_2eproto(); } } static_descriptor_initializer_Docflow_2fDocumentWithDocflowV3_2eproto_; // =================================================================== #ifndef _MSC_VER const int DocumentWithDocflowV3::kDocumentIdFieldNumber; const int DocumentWithDocflowV3::kLastEventFieldNumber; const int DocumentWithDocflowV3::kDocumentInfoFieldNumber; const int DocumentWithDocflowV3::kDocflowFieldNumber; #endif // !_MSC_VER DocumentWithDocflowV3::DocumentWithDocflowV3() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3) } void DocumentWithDocflowV3::InitAsDefaultInstance() { documentid_ = const_cast< ::Diadoc::Api::Proto::DocumentId*>(&::Diadoc::Api::Proto::DocumentId::default_instance()); lastevent_ = const_cast< ::Diadoc::Api::Proto::Docflow::LastEvent*>(&::Diadoc::Api::Proto::Docflow::LastEvent::default_instance()); documentinfo_ = const_cast< ::Diadoc::Api::Proto::Docflow::DocumentInfoV3*>(&::Diadoc::Api::Proto::Docflow::DocumentInfoV3::default_instance()); docflow_ = const_cast< ::Diadoc::Api::Proto::Docflow::DocflowV3*>(&::Diadoc::Api::Proto::Docflow::DocflowV3::default_instance()); } DocumentWithDocflowV3::DocumentWithDocflowV3(const DocumentWithDocflowV3& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3) } void DocumentWithDocflowV3::SharedCtor() { _cached_size_ = 0; documentid_ = NULL; lastevent_ = NULL; documentinfo_ = NULL; docflow_ = NULL; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } DocumentWithDocflowV3::~DocumentWithDocflowV3() { // @@protoc_insertion_point(destructor:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3) SharedDtor(); } void DocumentWithDocflowV3::SharedDtor() { if (this != default_instance_) { delete documentid_; delete lastevent_; delete documentinfo_; delete docflow_; } } void DocumentWithDocflowV3::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* DocumentWithDocflowV3::descriptor() { protobuf_AssignDescriptorsOnce(); return DocumentWithDocflowV3_descriptor_; } const DocumentWithDocflowV3& DocumentWithDocflowV3::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_Docflow_2fDocumentWithDocflowV3_2eproto(); return *default_instance_; } DocumentWithDocflowV3* DocumentWithDocflowV3::default_instance_ = NULL; DocumentWithDocflowV3* DocumentWithDocflowV3::New() const { return new DocumentWithDocflowV3; } void DocumentWithDocflowV3::Clear() { if (_has_bits_[0 / 32] & 15) { if (has_documentid()) { if (documentid_ != NULL) documentid_->::Diadoc::Api::Proto::DocumentId::Clear(); } if (has_lastevent()) { if (lastevent_ != NULL) lastevent_->::Diadoc::Api::Proto::Docflow::LastEvent::Clear(); } if (has_documentinfo()) { if (documentinfo_ != NULL) documentinfo_->::Diadoc::Api::Proto::Docflow::DocumentInfoV3::Clear(); } if (has_docflow()) { if (docflow_ != NULL) docflow_->::Diadoc::Api::Proto::Docflow::DocflowV3::Clear(); } } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool DocumentWithDocflowV3::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3) 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 .Diadoc.Api.Proto.DocumentId DocumentId = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_documentid())); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_LastEvent; break; } // required .Diadoc.Api.Proto.Docflow.LastEvent LastEvent = 2; case 2: { if (tag == 18) { parse_LastEvent: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_lastevent())); } else { goto handle_unusual; } if (input->ExpectTag(26)) goto parse_DocumentInfo; break; } // required .Diadoc.Api.Proto.Docflow.DocumentInfoV3 DocumentInfo = 3; case 3: { if (tag == 26) { parse_DocumentInfo: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_documentinfo())); } else { goto handle_unusual; } if (input->ExpectTag(34)) goto parse_Docflow; break; } // required .Diadoc.Api.Proto.Docflow.DocflowV3 Docflow = 4; case 4: { if (tag == 34) { parse_Docflow: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_docflow())); } 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:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3) return true; failure: // @@protoc_insertion_point(parse_failure:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3) return false; #undef DO_ } void DocumentWithDocflowV3::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3) // required .Diadoc.Api.Proto.DocumentId DocumentId = 1; if (has_documentid()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->documentid(), output); } // required .Diadoc.Api.Proto.Docflow.LastEvent LastEvent = 2; if (has_lastevent()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->lastevent(), output); } // required .Diadoc.Api.Proto.Docflow.DocumentInfoV3 DocumentInfo = 3; if (has_documentinfo()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->documentinfo(), output); } // required .Diadoc.Api.Proto.Docflow.DocflowV3 Docflow = 4; if (has_docflow()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, this->docflow(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3) } ::google::protobuf::uint8* DocumentWithDocflowV3::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3) // required .Diadoc.Api.Proto.DocumentId DocumentId = 1; if (has_documentid()) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 1, this->documentid(), target); } // required .Diadoc.Api.Proto.Docflow.LastEvent LastEvent = 2; if (has_lastevent()) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 2, this->lastevent(), target); } // required .Diadoc.Api.Proto.Docflow.DocumentInfoV3 DocumentInfo = 3; if (has_documentinfo()) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 3, this->documentinfo(), target); } // required .Diadoc.Api.Proto.Docflow.DocflowV3 Docflow = 4; if (has_docflow()) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 4, this->docflow(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3) return target; } int DocumentWithDocflowV3::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required .Diadoc.Api.Proto.DocumentId DocumentId = 1; if (has_documentid()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->documentid()); } // required .Diadoc.Api.Proto.Docflow.LastEvent LastEvent = 2; if (has_lastevent()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->lastevent()); } // required .Diadoc.Api.Proto.Docflow.DocumentInfoV3 DocumentInfo = 3; if (has_documentinfo()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->documentinfo()); } // required .Diadoc.Api.Proto.Docflow.DocflowV3 Docflow = 4; if (has_docflow()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->docflow()); } } 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 DocumentWithDocflowV3::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const DocumentWithDocflowV3* source = ::google::protobuf::internal::dynamic_cast_if_available<const DocumentWithDocflowV3*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void DocumentWithDocflowV3::MergeFrom(const DocumentWithDocflowV3& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_documentid()) { mutable_documentid()->::Diadoc::Api::Proto::DocumentId::MergeFrom(from.documentid()); } if (from.has_lastevent()) { mutable_lastevent()->::Diadoc::Api::Proto::Docflow::LastEvent::MergeFrom(from.lastevent()); } if (from.has_documentinfo()) { mutable_documentinfo()->::Diadoc::Api::Proto::Docflow::DocumentInfoV3::MergeFrom(from.documentinfo()); } if (from.has_docflow()) { mutable_docflow()->::Diadoc::Api::Proto::Docflow::DocflowV3::MergeFrom(from.docflow()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void DocumentWithDocflowV3::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void DocumentWithDocflowV3::CopyFrom(const DocumentWithDocflowV3& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool DocumentWithDocflowV3::IsInitialized() const { if ((_has_bits_[0] & 0x0000000f) != 0x0000000f) return false; if (has_documentid()) { if (!this->documentid().IsInitialized()) return false; } if (has_lastevent()) { if (!this->lastevent().IsInitialized()) return false; } if (has_documentinfo()) { if (!this->documentinfo().IsInitialized()) return false; } if (has_docflow()) { if (!this->docflow().IsInitialized()) return false; } return true; } void DocumentWithDocflowV3::Swap(DocumentWithDocflowV3* other) { if (other != this) { std::swap(documentid_, other->documentid_); std::swap(lastevent_, other->lastevent_); std::swap(documentinfo_, other->documentinfo_); std::swap(docflow_, other->docflow_); 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 DocumentWithDocflowV3::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = DocumentWithDocflowV3_descriptor_; metadata.reflection = DocumentWithDocflowV3_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int LastEvent::kEventIdFieldNumber; const int LastEvent::kTimestampFieldNumber; #endif // !_MSC_VER LastEvent::LastEvent() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:Diadoc.Api.Proto.Docflow.LastEvent) } void LastEvent::InitAsDefaultInstance() { timestamp_ = const_cast< ::Diadoc::Api::Proto::Timestamp*>(&::Diadoc::Api::Proto::Timestamp::default_instance()); } LastEvent::LastEvent(const LastEvent& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:Diadoc.Api.Proto.Docflow.LastEvent) } void LastEvent::SharedCtor() { ::google::protobuf::internal::GetEmptyString(); _cached_size_ = 0; eventid_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); timestamp_ = NULL; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } LastEvent::~LastEvent() { // @@protoc_insertion_point(destructor:Diadoc.Api.Proto.Docflow.LastEvent) SharedDtor(); } void LastEvent::SharedDtor() { if (eventid_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete eventid_; } if (this != default_instance_) { delete timestamp_; } } void LastEvent::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* LastEvent::descriptor() { protobuf_AssignDescriptorsOnce(); return LastEvent_descriptor_; } const LastEvent& LastEvent::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_Docflow_2fDocumentWithDocflowV3_2eproto(); return *default_instance_; } LastEvent* LastEvent::default_instance_ = NULL; LastEvent* LastEvent::New() const { return new LastEvent; } void LastEvent::Clear() { if (_has_bits_[0 / 32] & 3) { if (has_eventid()) { if (eventid_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { eventid_->clear(); } } if (has_timestamp()) { if (timestamp_ != NULL) timestamp_->::Diadoc::Api::Proto::Timestamp::Clear(); } } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool LastEvent::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:Diadoc.Api.Proto.Docflow.LastEvent) 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 string EventId = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_eventid())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->eventid().data(), this->eventid().length(), ::google::protobuf::internal::WireFormat::PARSE, "eventid"); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_Timestamp; break; } // required .Diadoc.Api.Proto.Timestamp Timestamp = 2; case 2: { if (tag == 18) { parse_Timestamp: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_timestamp())); } 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:Diadoc.Api.Proto.Docflow.LastEvent) return true; failure: // @@protoc_insertion_point(parse_failure:Diadoc.Api.Proto.Docflow.LastEvent) return false; #undef DO_ } void LastEvent::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:Diadoc.Api.Proto.Docflow.LastEvent) // required string EventId = 1; if (has_eventid()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->eventid().data(), this->eventid().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "eventid"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->eventid(), output); } // required .Diadoc.Api.Proto.Timestamp Timestamp = 2; if (has_timestamp()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->timestamp(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:Diadoc.Api.Proto.Docflow.LastEvent) } ::google::protobuf::uint8* LastEvent::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:Diadoc.Api.Proto.Docflow.LastEvent) // required string EventId = 1; if (has_eventid()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->eventid().data(), this->eventid().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "eventid"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->eventid(), target); } // required .Diadoc.Api.Proto.Timestamp Timestamp = 2; if (has_timestamp()) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 2, this->timestamp(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:Diadoc.Api.Proto.Docflow.LastEvent) return target; } int LastEvent::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required string EventId = 1; if (has_eventid()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->eventid()); } // required .Diadoc.Api.Proto.Timestamp Timestamp = 2; if (has_timestamp()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->timestamp()); } } 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 LastEvent::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const LastEvent* source = ::google::protobuf::internal::dynamic_cast_if_available<const LastEvent*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void LastEvent::MergeFrom(const LastEvent& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_eventid()) { set_eventid(from.eventid()); } if (from.has_timestamp()) { mutable_timestamp()->::Diadoc::Api::Proto::Timestamp::MergeFrom(from.timestamp()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void LastEvent::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void LastEvent::CopyFrom(const LastEvent& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool LastEvent::IsInitialized() const { if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; if (has_timestamp()) { if (!this->timestamp().IsInitialized()) return false; } return true; } void LastEvent::Swap(LastEvent* other) { if (other != this) { std::swap(eventid_, other->eventid_); std::swap(timestamp_, other->timestamp_); 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 LastEvent::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = LastEvent_descriptor_; metadata.reflection = LastEvent_reflection_; return metadata; } // @@protoc_insertion_point(namespace_scope) } // namespace Docflow } // namespace Proto } // namespace Api } // namespace Diadoc // @@protoc_insertion_point(global_scope)
34.629584
146
0.70198
Edw-K
6f640aab4b430e2a29e45c5ec9aeaac9dee7d887
36,232
cpp
C++
src/CTimeUnits.cpp
MenaceSan/GrayCore
244e394adaefa17399232896fbd04b7aaeebac21
[ "MIT" ]
1
2020-12-18T04:55:27.000Z
2020-12-18T04:55:27.000Z
src/CTimeUnits.cpp
MenaceSan/GrayCore
244e394adaefa17399232896fbd04b7aaeebac21
[ "MIT" ]
null
null
null
src/CTimeUnits.cpp
MenaceSan/GrayCore
244e394adaefa17399232896fbd04b7aaeebac21
[ "MIT" ]
null
null
null
// //! @file cTimeUnits.cpp //! @copyright 1992 - 2020 Dennis Robinson (http://www.menasoft.com) // #include "pch.h" #include "cTimeUnits.h" #include "cTimeInt.h" #include "cTimeZone.h" #include "StrChar.h" #include "StrT.h" #include "cBits.h" #ifdef __linux__ #include "cTimeVal.h" #endif namespace Gray { // Stock date time string formats. const GChar_t cTimeUnits::k_SepsAll[8] = _GT("/ :T.,-"); // All/Any separator that might occur in k_StrFormats. const GChar_t* cTimeUnits::k_StrFormats[TIME_FORMAT_QTY + 1] = { //! strftime() type string formats. //! @todo USE k_TimeSeparator _GT("%Y/%m/%d %H:%M:%S"), // TIME_FORMAT_DEFAULT = default Sortable/linear format. "2008/07/09 13:47:10" _GT("%Y-%m-%d %H:%M:%S"), // TIME_FORMAT_DB = Sorted time = "2008-04-10 13:30:00" _GT("%Y-%m-%d %H:%M:%S %Z"), // TIME_FORMAT_TZ = Sorted Universal/GMT time = "2008-04-10 13:30:00Z" _GT("%m/%d/%Y %H:%M:%S"), // TIME_FORMAT_AMERICAN = "07/19/2008 13:47:10" _GT("%a, %d %b %Y %H:%M:%S %z"), // TIME_FORMAT_HTTP = RFC1123 format "Tue, 03 Oct 2000 22:44:56 GMT" _GT("%d %b %Y %H:%M:%S %z"), // TIME_FORMAT_SMTP = SMTP wants this format. "7 Aug 2001 10:12:12 GMT" _GT("%Y/%m/%dT%H:%M:%S"), // TIME_FORMAT_ISO _GT("%Y/%m/%dT%H:%M:%S%z"), // TIME_FORMAT_ISO_TZ _GT("%Y%m%d%H%M%S%z"), // TIME_FORMAT_ASN // 01/06/2016, 11:45 AM (-03:00) nullptr, }; const CTimeUnit cTimeUnits::k_Units[TIMEUNIT_QTY] = { // m_uSubRatio { _GT("year"), _GT("Y"), 1, 3000, 12, 365 * 24 * 60 * 60, 365.25 }, // approximate, depends on leap year. { _GT("month"), _GT("M"), 1, 12, 30, 30 * 24 * 60 * 60, 30.43 }, // approximate, depends on month { _GT("day"), _GT("d"), 1, 31, 24, 24 * 60 * 60, 1.0 }, { _GT("hour"), _GT("h"), 0, 23, 60, 60 * 60, 1.0 / (24.0) }, { _GT("minute"), _GT("m"), 0, 59, 60, 60, 1.0 / (24.0*60.0) }, { _GT("second"), _GT("s"), 0, 59, 1000, 1, 1.0 / (24.0*60.0*60.0) }, { _GT("millisec"), _GT("ms"), 0, 999, 1000, 0, 1.0 / (24.0*60.0*60.0*1000.0) }, { _GT("microsec"), _GT("us"), 0, 999, 0, 0, 1.0 / (24.0*60.0*60.0*1000.0*1000.0) }, { _GT("TZ"), _GT("TZ"), -24 * 60, 24 * 60, 0, 0, 1.0 }, // TIMEUNIT_TZ }; const BYTE cTimeUnits::k_MonthDays[2][TIMEMONTH_QTY] = // Jan=0 { { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, // normal year { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } // leap year }; const WORD cTimeUnits::k_MonthDaySums[2][TIMEMONTH_QTY + 1] = // Jan=0 { { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }, // normal year { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 } // leap year }; const GChar_t* const cTimeUnits::k_MonthName[TIMEMONTH_QTY + 1] = // Jan=0 { _GT("January"), _GT("February"), _GT("March"), _GT("April"), _GT("May"), _GT("June"), _GT("July"), _GT("August"), _GT("September"), _GT("October"), _GT("November"), _GT("December"), nullptr }; const GChar_t* const cTimeUnits::k_MonthAbbrev[TIMEMONTH_QTY + 1] = // Jan=0 { _GT("Jan"), _GT("Feb"), _GT("Mar"), _GT("Apr"), _GT("May"), _GT("Jun"), _GT("Jul"), _GT("Aug"), _GT("Sep"), _GT("Oct"), _GT("Nov"), _GT("Dec"), nullptr, }; const GChar_t* const cTimeUnits::k_DayName[TIMEDOW_QTY + 1] = // Sun=0 { _GT("Sunday"), _GT("Monday"), _GT("Tuesday"), _GT("Wednesday"), _GT("Thursday"), _GT("Friday"), _GT("Saturday"), nullptr }; const GChar_t* const cTimeUnits::k_DayAbbrev[TIMEDOW_QTY + 1] = // Sun=0 { _GT("Sun"), _GT("Mon"), _GT("Tue"), _GT("Wed"), _GT("Thu"), _GT("Fri"), _GT("Sat"), nullptr }; const GChar_t cTimeUnits::k_Seps[3] = _GT("/:"); // Normal date string separators. "/:" GChar_t cTimeUnits::sm_DateSeparator = '/'; //!< might be . for Germans, bool cTimeUnits::sm_time24Mode = false; //****************************************************************************************** #ifdef _WIN32 cTimeUnits::cTimeUnits(const SYSTEMTIME& sysTime) : m_wYear(sysTime.wYear) , m_wMonth(sysTime.wMonth) // 1 based. , m_wDay(sysTime.wDay) , m_wHour(sysTime.wHour) , m_wMinute(sysTime.wMinute) , m_wSecond(sysTime.wSecond) , m_wMillisecond(sysTime.wMilliseconds) , m_wMicrosecond(0) , m_nTZ(0) { ASSERT(isValidTimeUnits()); } bool cTimeUnits::GetSys(SYSTEMTIME& sysTime) const noexcept { sysTime.wYear = m_wYear; sysTime.wMonth = m_wMonth; // 1 based. sysTime.wDayOfWeek = (WORD)get_DOW(); // Sunday - [0,6] TIMEDOW_TYPE sysTime.wDay = m_wDay; sysTime.wHour = m_wHour; sysTime.wMinute = m_wMinute; sysTime.wSecond = m_wSecond; sysTime.wMilliseconds = m_wMillisecond; return true; } void cTimeUnits::SetSys(const SYSTEMTIME& sysTime) { m_wYear = sysTime.wYear; m_wMonth = sysTime.wMonth; // 1 based. m_wDay = sysTime.wDay; m_wHour = sysTime.wHour; m_wMinute = sysTime.wMinute; m_wSecond = sysTime.wSecond; m_wMillisecond = sysTime.wMilliseconds; m_wMicrosecond = 0; ASSERT(isValidTimeUnits()); } #endif void cTimeUnits::SetZeros() { cMem::Zero(&m_wYear, TIMEUNIT_QTY * sizeof(m_wYear)); m_wYear = 1; // m_uMin m_wMonth = 1; m_wDay = 1; } bool cTimeUnits::InitTimeNow(TZ_TYPE nTimeZoneOffset) { //! Get the current time, and adjust units for timezone. nDST ?? //! like _WIN32 GetLocalTime(st), GetSystemTime(st) cTimeInt t; t.InitTimeNow(); return t.GetTimeUnits(*this, nTimeZoneOffset); } COMPARE_TYPE cTimeUnits::Compare(cTimeUnits& b) const { //! Compare relevant parts of 2 times. if (b.m_nTZ != this->m_nTZ) { //! @note TODO DOES NOT FACTOR TIMEUNIT_TZ } for (int i = TIMEUNIT_Year; i <= TIMEUNIT_Microsecond; i++) // TIMEUNIT_TYPE { TIMEUNIT_t nThis = GetUnit((TIMEUNIT_TYPE)i); TIMEUNIT_t nB = b.GetUnit((TIMEUNIT_TYPE)i); if (nThis != nB) { return (nThis > nB) ? COMPARE_Greater : COMPARE_Less; } } return COMPARE_Equal; } bool cTimeUnits::isTimeFuture() const { cTimeUnits tNow; tNow.InitTimeNow((TZ_TYPE)m_nTZ); return Compare(tNow) >= COMPARE_Greater; } bool cTimeUnits::IsValidUnit(TIMEUNIT_TYPE i) const { TIMEUNIT_t iUnit = GetUnit(i); if (iUnit < k_Units[i].m_uMin) return false; if (iUnit > k_Units[i].m_uMax) return false; return true; } bool cTimeUnits::isValidTimeUnits() const { //! Are the values in valid range ? //! @note If we are just using this for time math values may go out of range ? if (!isValidMonth()) return false; if (m_wDay < 1 || m_wDay > get_DaysInMonth()) return false; if (((UINT)m_wHour) > 23) return false; if (((UINT)m_wMinute) > 59) return false; if (((UINT)m_wSecond) > 59) return false; return true; } bool cTimeUnits::isReasonableTimeUnits() const { //! Is this data reasonable for most purposes? if (m_wYear < 1900) return false; if (m_wYear > 2500) return false; return isValidTimeUnits(); } int GRAYCALL cTimeUnits::IsLeapYear(TIMEUNIT_t wYear) // static { //! 0 or 1 NOT Boolean - for array access. //! Every year divisible by 4 is a leap year. //! But every year divisible by 100 is NOT a leap year //! Unless the year is also divisible by 400, then it is still a leap year. if ((wYear & 3) != 0) // not multiple of 4 = not leap year. return 0; if ((wYear % 100) == 0) // multiple of 100. i.e. 1900 is not a leap year. { if ((wYear % 400) == 0) // multiple of 400. i.e. 2000 is a leap year. return 1; return 0; } return 1; } int GRAYCALL cTimeUnits::GetLeapYearsSince2K(TIMEUNIT_t wYear) // static { //! calculate the number of leap days/years since Jan 1 of a year to Jan 1 2000. //! (Jan 1 2000 = TIMEDOW_Sat) to Jan 1 wYear //! can be negative if wYear < 2000 int iYear = wYear - 2000; int iDays = (iYear > 0) ? 1 : 0; iYear -= iDays; iDays += iYear / 4; // add multiple 4 year days iDays += iYear / 400; // add multiple 400 years days. iDays -= iYear / 100; // remove multiple 100 years days return iDays; } TIMEDOW_TYPE GRAYCALL cTimeUnits::GetDOW(TIMEUNIT_t wYear, TIMEUNIT_t wMonth, TIMEUNIT_t wDay) // static { //! @return day of week for a particular date. TIMEDOW_TYPE //! wMonth = 1 based //! wDay = 1 based. ASSERT(wMonth > 0 && wMonth <= 12); ASSERT(wDay > 0); int iDays = (wYear - 2000); // should be *365 but since (364%7)==0 we can omit that. iDays += GetLeapYearsSince2K(wYear); // can be negative if wYear < 2000 iDays += k_MonthDaySums[IsLeapYear(wYear)][wMonth - 1]; iDays += (wDay - 1) + TIMEDOW_Sat; // (Jan 1 2000 = Sat) iDays %= TIMEDOW_QTY; // mod 7 if (iDays < 0) { iDays += TIMEDOW_QTY; } return (TIMEDOW_TYPE)iDays; } int GRAYCALL cTimeUnits::GetDOY(TIMEUNIT_t wYear, TIMEUNIT_t wMonth, TIMEUNIT_t wDay) // static { //! Day of the year. 0 to 365 //! wMonth = 1 based //! wDay = 1 based. ASSERT(wMonth > 0 && wMonth <= 12); return k_MonthDaySums[IsLeapYear(wYear)][wMonth - 1] + wDay - 1; } bool cTimeUnits::isInDST() const { //! Is this Date DST? Assuming local time zone honors DST. //! http://www.worldtimezone.com/daylight.html //! like the C internal function _isindst(const struct tm *tb) //! @note //! rule for years < 1987: //! begin after 2 AM on the last Sunday in April //! end 1 AM on the last Sunday in October. //! //! rule for years >= 1987: //! begin after 2 AM on the first Sunday in April //! end 1 AM on the last Sunday in October. //! //! rule for years >= 2007: //! begin Second Sunday in March 2AM //! end First Sunday in November 2AM TIMEUNIT_t wMonthLo; TIMEUNIT_t wMonthHi; if (m_wYear >= 2007) { // New US idiot rules. wMonthLo = 3; wMonthHi = 11; } else { wMonthLo = 4; wMonthHi = 10; } // If the month is before April or after October, then we know immediately it can't be DST. if (m_wMonth < wMonthLo || m_wMonth > wMonthHi) return false; // If the month is after April and before October then we know immediately it must be DST. if (m_wMonth > wMonthLo && m_wMonth < wMonthHi) return true; // Month is April or October see if date falls between appropriate Sundays. bool bLow = (m_wMonth < 6); // What day (of the month) is the Sunday of interest? TIMEUNIT_t wHour; int iSunday; if (m_wYear < 1987) { iSunday = 3; // always last Sunday wHour = (bLow) ? 2 : 1; } else if (m_wYear < 2007) { iSunday = (bLow) ? 1 : 3; // first or last. wHour = (bLow) ? 2 : 1; } else // >= 2007 { iSunday = (bLow) ? 2 : 1; // second or first. wHour = 2; } int iDayMin; switch (iSunday) { case 1: // First Sunday of the month iDayMin = 1; break; case 2: // Second Sunday of the month iDayMin = 8; break; default: // Last Sunday in month iDayMin = k_MonthDays[IsLeapYear(m_wYear)][m_wMonth - 1] - 6; break; } TIMEDOW_TYPE eDOW = GetDOW(m_wYear, m_wMonth, (TIMEUNIT_t)iDayMin); // sun = 0 iSunday = iDayMin + ((7 - eDOW) % 7); // the next Sunday. if (bLow) { return (m_wDay > iSunday || (m_wDay == iSunday && m_wHour >= wHour)); } else { return (m_wDay < iSunday || (m_wDay == iSunday && m_wHour < wHour)); } } //****************************************************************** void cTimeUnits::put_DosDate(UINT32 ulDosDate) { //! unpack 32 bit DosDate format. for ZIP files and old FAT file system. //! we could use DosDateTimeToFileTime and LocalFileTimeToFileTime for _WIN32 //! 0-4 =Day of the month (1-31) //! 5-8 =Month (1 = January, 2 = February, and so on) //! 9-15 =Year offset from 1980 (add 1980 to get actual year) . 6 bits = 63 years = 2043 failure. WORD wFatDate = HIWORD(ulDosDate); // 0-4 =Second divided by 2 // 5-10 =Minute (0-59) // 11-15 =Hour (0-23 on a 24-hour clock) WORD wFatTime = LOWORD(ulDosDate); this->m_wSecond = (TIMEUNIT_t)(2 * (wFatTime & 0x1f)); // 2 second accurate. this->m_wMinute = (TIMEUNIT_t)((wFatTime >> 5) & 0x3f); this->m_wHour = (TIMEUNIT_t)((wFatTime >> 11)); this->m_wDay = (TIMEUNIT_t)(wFatDate & 0x1f); this->m_wMonth = (TIMEUNIT_t)((wFatDate >> 5) & 0x0f); this->m_wYear = (TIMEUNIT_t)(1980 + (wFatDate >> 9)); // up to 2043 } UINT32 cTimeUnits::get_DosDate() const { //! get/pack a 32 bit DOS date format. for ZIP files. and old FAT file system. //! ASSUME isValidTimeUnits(). UINT32 year = (UINT32)this->m_wYear; // 1980 to 2043 if (year > 1980) year -= 1980; else if (year > 80) year -= 80; return (UINT32)(((this->m_wDay) + (32 * (this->m_wMonth)) + (512 * year)) << 16) | ((this->m_wSecond / 2) + (32 * this->m_wMinute) + (2048 * (UINT32)this->m_wHour)); } void cTimeUnits::AddMonths(int iMonths) { //! Add months to this structure. months are not exact time measures, but there are always 12 per year. //! @arg iMonths = 0 based. Can be <0 iMonths += m_wMonth - 1; m_wMonth = (TIMEUNIT_t)(1 + (iMonths % 12)); m_wYear = (TIMEUNIT_t)(m_wYear + (iMonths / 12)); // adjust years. } void cTimeUnits::AddDays(int iDays) { //! Add Days. Adjust for the fact that months and years are not all the same number of days. //! @arg iDays can be negative. //! Do we cross years ? for (;;) { // Use GetLeapYearsSince2K to optimize this? don't bother, its never that big. int iDayOfYear = get_DayOfYear(); int iDaysInYear = get_DaysInYear(); int iDays2 = iDayOfYear + iDays; if (iDays2 >= iDaysInYear) // advance to next year. { ASSERT(iDays > 0); iDays -= iDaysInYear - iDayOfYear; m_wYear++; m_wMonth = 1; m_wDay = 1; } else if (iDays2 < 0) // previous year. { ASSERT(iDays < 0); iDays += iDaysInYear; m_wYear--; m_wMonth = 12; m_wDay = 31; } else break; } // Do we cross months? for (;;) { int iDayOfMonth = (m_wDay - 1); int iDaysInMonth = get_DaysInMonth(); int iDays2 = iDayOfMonth + iDays; if (iDays2 >= iDaysInMonth) // next month. { ASSERT(iDays > 0); iDays -= iDaysInMonth - iDayOfMonth; m_wMonth++; m_wDay = 1; } else if (iDays2 < 0) // previous month { ASSERT(iDays < 0); iDays += iDayOfMonth; m_wMonth--; m_wDay = get_DaysInMonth(); } else { m_wDay += (TIMEUNIT_t)iDays; break; } } } void cTimeUnits::AddSeconds(TIMESECD_t nSeconds) { //! Add TimeUnits with seconds. handles very large values of seconds. //! Used to adjust for TZ and DST. //! nSeconds can be negative. int nSecondOfDay = get_SecondOfDay(); int nSeconds2 = nSeconds + nSecondOfDay; int iDays = 0; if (nSeconds2 >= k_nSecondsPerDay) // Test days as special case since months are not uniform. { // Cross into next day(s). TIMEUNIT_Day ASSERT(nSeconds > 0); iDays = nSeconds2 / k_nSecondsPerDay; do_days: AddDays(iDays); nSeconds2 -= iDays * k_nSecondsPerDay; } else if (nSeconds2 < 0) { // Back to previous day(s). TIMEUNIT_Day ASSERT(nSeconds < 0); iDays = (nSeconds2 / k_nSecondsPerDay) - 1; goto do_days; } int iTicksA = ABS(nSeconds2); ASSERT(iTicksA < k_nSecondsPerDay); int iUnitDiv = 60 * 60; for (UINT i = TIMEUNIT_Hour; i <= TIMEUNIT_Second; i++) { TIMEUNIT_t iUnits = (TIMEUNIT_t)(nSeconds2 / iUnitDiv); SetUnit((TIMEUNIT_TYPE)i, iUnits); ASSERT(IsValidUnit((TIMEUNIT_TYPE)i)); nSeconds2 -= iUnits * iUnitDiv; iUnitDiv /= 60; } } void cTimeUnits::AddTZ(TZ_TYPE nTimeZoneOffset) { //! add TZ Offset in minutes. if (nTimeZoneOffset == TZ_LOCAL) { nTimeZoneOffset = cTimeZoneMgr::GetLocalTimeZoneOffset(); } m_nTZ = (TIMEUNIT_t)nTimeZoneOffset; if (nTimeZoneOffset == TZ_UTC) // adjust for timezone and DST, TZ_GMT = 0 return; TIMESECD_t nAdjustMinutes = -(nTimeZoneOffset); if (isInDST()) { nAdjustMinutes += 60; // add hour. } // adjust for TZ/DST offsets. may be new day or year ? AddSeconds(nAdjustMinutes * 60); } //****************************************************************** StrLen_t cTimeUnits::GetTimeSpanStr(GChar_t* pszOut, StrLen_t iOutSizeMax, TIMEUNIT_TYPE eUnitHigh, int iUnitsDesired, bool bShortText) const { //! A delta/span time string. from years to milliseconds. //! Get a text description of amount of time span (delta) //! @arg //! eUnitHigh = the highest unit, TIMEUNIT_Day, TIMEUNIT_Minute //! iUnitsDesired = the number of units up the cTimeUnits::k_Units ladder to go. default=2 //! @return //! length of string in chars if (iUnitsDesired < 1) { iUnitsDesired = 1; // must have at least 1. } if (IS_INDEX_BAD_ARRAY(eUnitHigh, cTimeUnits::k_Units)) { eUnitHigh = TIMEUNIT_Day; // days is highest unit by default. months is not accurate! } int iUnitsPrinted = 0; StrLen_t iOutLen = 0; UINT64 nUnits = 0; int i = TIMEUNIT_Year; // 0 for (; i < eUnitHigh; i++) { nUnits = (nUnits + GetUnit0((TIMEUNIT_TYPE)i)) * k_Units[i].m_uSubRatio; } for (; i < TIMEUNIT_Microsecond; i++) // highest to lowest. { nUnits += GetUnit0((TIMEUNIT_TYPE)i); if (!nUnits) // just skip empty units. { continue; } if (iOutLen) { iOutLen += StrT::CopyLen(pszOut + iOutLen, _GT(" "), iOutSizeMax - iOutLen); // " and "; } if (bShortText) { iOutLen += StrT::sprintfN(pszOut + iOutLen, iOutSizeMax - iOutLen, _GT("%u%s"), (int)nUnits, StrArg<GChar_t>(cTimeUnits::k_Units[i].m_pszUnitNameS)); } else if (nUnits == 1) { iOutLen += StrT::CopyLen(pszOut + iOutLen, _GT("1 "), iOutSizeMax - iOutLen); iOutLen += StrT::CopyLen(pszOut + iOutLen, cTimeUnits::k_Units[i].m_pszUnitNameL, iOutSizeMax - iOutLen); } else { iOutLen += StrT::sprintfN(pszOut + iOutLen, iOutSizeMax - iOutLen, _GT("%u %ss"), (int)nUnits, cTimeUnits::k_Units[i].m_pszUnitNameL); } if (++iUnitsPrinted >= iUnitsDesired) // only print iUnitsDesired most significant units of time break; nUnits = 0; } if (iUnitsPrinted == 0) { // just 0 iOutLen = StrT::CopyLen(pszOut, bShortText ? _GT("0s") : _GT("0 seconds"), iOutSizeMax); } return iOutLen; } StrLen_t cTimeUnits::GetFormStr(GChar_t* pszOut, StrLen_t iOutSizeMax, const GChar_t* pszFormat) const { //! Get the time as a formatted string using "C" strftime() //! build formatted string from cTimeUnits. //! similar to C stdlib strftime() http://linux.die.net/man/3/strftime //! add TZ as postfix if desired?? //! used by cTimeDouble::GetTimeFormStr and cTimeInt::GetTimeFormStr //! @return //! length of string in chars. <= 0 = failed. if (((UINT_PTR)pszFormat) < TIME_FORMAT_QTY) // IS_INTRESOURCE() { pszFormat = k_StrFormats[((UINT_PTR)pszFormat)]; } GChar_t szTmp[2]; StrLen_t iOut = 0; for (StrLen_t i = 0; iOut < iOutSizeMax; i++) { GChar_t ch = pszFormat[i]; if (ch == '\0') break; if (ch != '%') { pszOut[iOut++] = ch; continue; } ch = pszFormat[++i]; if (ch == '\0') break; if (ch == '#') // As in the printf function, the # flag may prefix/modify any formatting code { ch = pszFormat[++i]; if (ch == '\0') break; } const GChar_t* pszVal = nullptr; int iValPad = 0; short wVal = 0; switch (ch) { case '/': szTmp[0] = sm_DateSeparator; szTmp[1] = '\0'; pszVal = szTmp; break; case '%': pszVal = _GT("%"); break; case 'y': // Year without century, as decimal number (00 to 99) wVal = m_wYear % 100; iValPad = 2; break; case 'Y': // Year with century, as decimal number wVal = m_wYear; iValPad = 0; break; case 'b': // Abbreviated month name case 'h': if (m_wMonth == 0) break; pszVal = k_MonthAbbrev[m_wMonth - 1]; break; case 'B': // Full month name if (m_wMonth == 0) break; pszVal = k_MonthName[m_wMonth - 1]; break; case 'm': // Month as decimal number (01 to 12) wVal = m_wMonth; iValPad = 2; break; case 'd': // Day of month as decimal number (01 to 31) wVal = m_wDay; iValPad = 2; break; case 'a': pszVal = k_DayAbbrev[get_DOW()]; break; case 'A': pszVal = k_DayName[get_DOW()]; break; case 'w': // Weekday as decimal number (0 to 6; Sunday is 0) wVal = (WORD)get_DOW(); iValPad = 0; break; case 'j': // Day of year as decimal number (001 to 366) wVal = (WORD)get_DOY(); iValPad = 3; break; case 'H': // Hour in 24-hour format (00 to 23) wVal = m_wHour; iValPad = 2; break; case 'k': wVal = m_wHour; iValPad = 0; break; case 'I': // Hour in 12-hour format (01 to 12) wVal = (m_wHour % 12); iValPad = 2; if (!wVal) wVal = 12; break; case 'p': // Current locale's A.M./P.M. indicator for 12-hour clock pszVal = (m_wHour < 12) ? _GT("AM") : _GT("PM"); break; case 'M': // Minute as decimal number (00 to 59) wVal = m_wMinute; iValPad = 2; break; case 'S': // Second as decimal number (00 to 59) wVal = m_wSecond; iValPad = 2; break; case 'Z': // Either the time-zone name or time zone abbreviation, depending on registry settings; no characters if time zone is unknown { const cTimeZone* pTZ = cTimeZoneMgr::FindTimeZone((TZ_TYPE)m_nTZ); if (pTZ != nullptr) { pszVal = pTZ->m_pszTimeZoneName; } else { pszVal = _GT(""); // +00 for timezone. } break; } case 'z': { const cTimeZone* pTZ = cTimeZoneMgr::FindTimeZone((TZ_TYPE)m_nTZ); if (pTZ != nullptr) { pszVal = pTZ->m_pszTimeZoneName; } else { pszVal = _GT(""); } break; } // TIMEUNIT_Millisecond // TIMEUNIT_Microsecond case 'F': // equiv to "%Y-%m-%d" for ISO case 'c': // Date and time representation appropriate for locale. NOT SUPPORTED. case 'U': // Week of year as decimal number, with Sunday as first day of week (00 to 53) case 'W': // Week of year as decimal number, with Monday as first day of week (00 to 53) case 'x': // Date representation for current locale case 'X': // Time representation for current locale default: ASSERT(0); break; } GChar_t* pszOutCur = pszOut + iOut; StrLen_t iOutSizeLeft = iOutSizeMax - iOut; if (pszVal != nullptr) { iOut += StrT::CopyLen(pszOutCur, pszVal, iOutSizeLeft); } else if (iValPad > 0 && iValPad < iOutSizeLeft) { // right padded number. GChar_t* pszMSD = StrT::ULtoA2(wVal, pszOutCur, iValPad + 1, 10, 'A'); while (pszMSD > pszOutCur) { *(--pszMSD) = '0'; } iOut += iValPad; } else { iOut += StrT::UtoA(wVal, pszOutCur, iOutSizeLeft); } } pszOut[iOut] = '\0'; return iOut; } //****************************************************************** HRESULT cTimeUnits::SetTimeStr(const GChar_t* pszDateTime, TZ_TYPE nTimeZoneOffset) { //! set cTimeUnits from a string. //! @arg //! pszDateTime = "2008/10/23 12:0:0 PM GMT" //! rnTimeZoneOffset = if found a time zone indicator in the string. do not set if nothing found. //! @note //! Must support all regular TIME_FORMAT_QTY types. //! @return //! > 0 length = OK, <=0 = doesn't seem like a valid datetime. //! e.g. "Sat, 07 Aug 2004 01:20:20", "" //! toJSON method: "2012-04-23T18:25:43.511Z" is sortable. SetZeros(); cTimeParser parser; HRESULT hRes = parser.ParseString(pszDateTime, nullptr); if (FAILED(hRes)) return hRes; if (!parser.TestMatches()) // try all formats i know. return MK_E_SYNTAX; m_nTZ = (TIMEUNIT_t)nTimeZoneOffset; // allowed to be overridden by cTimeParser.GetTimeUnits hRes = parser.GetTimeUnits(*this); if (m_nTZ == TZ_LOCAL) { m_nTZ = (TIMEUNIT_t)cTimeZoneMgr::GetLocalTimeZoneOffset(); } return hRes; } //****************************************************************************************** StrLen_t cTimeParser::ParseNamedUnit(const GChar_t* pszName) { // Get values for named units. TIMEUNIT_Month, TIMEUNIT_TZ or TIMEUNIT_QTY (for DOW) ITERATE_t iStart = STR_TABLEFIND_NH(pszName, cTimeUnits::k_MonthName); if (iStart >= 0) { m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_Month; m_Unit[m_iUnitsParsed].m_nValue = (TIMEUNIT_t)(iStart + 1); return StrT::Len(cTimeUnits::k_MonthName[iStart]); } iStart = STR_TABLEFIND_NH(pszName, cTimeUnits::k_MonthAbbrev); if (iStart >= 0) { m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_Month; m_Unit[m_iUnitsParsed].m_nValue = (TIMEUNIT_t)(iStart + 1); return StrT::Len(cTimeUnits::k_MonthAbbrev[iStart]); } iStart = STR_TABLEFIND_NH(pszName, cTimeUnits::k_DayName); if (iStart >= 0) { m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_DOW; // Temporary for DOW m_Unit[m_iUnitsParsed].m_nValue = (TIMEUNIT_t)iStart; return StrT::Len(cTimeUnits::k_DayName[iStart]); } iStart = STR_TABLEFIND_NH(pszName, cTimeUnits::k_DayAbbrev); if (iStart >= 0) { m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_DOW; // Temporary for DOW m_Unit[m_iUnitsParsed].m_nValue = (TIMEUNIT_t)iStart; return StrT::Len(cTimeUnits::k_DayAbbrev[iStart]); } const cTimeZone* pTZ = cTimeZoneMgr::FindTimeZoneHead(pszName); if (pTZ != nullptr) { m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_TZ; m_Unit[m_iUnitsParsed].m_nValue = (TIMEUNIT_t)(pTZ->m_nTimeZoneOffset); return StrT::Len(pTZ->m_pszTimeZoneName); } // AM / PM if (!StrT::CmpHeadI(_GT("PM"), pszName)) { // Add 12 hours. m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_Hour; m_Unit[m_iUnitsParsed].m_nValue = 12; return 2; } if (!StrT::CmpHeadI(_GT("AM"), pszName)) { // Add 0 hours. m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_Hour; m_Unit[m_iUnitsParsed].m_nValue = 0; return 2; } return 0; } HRESULT cTimeParser::ParseString(const GChar_t* pszTimeString, const GChar_t* pszSeparators) { //! parse the pszTimeString to look for things that look like a date time. //! parse 3 types of things: Separators, numbers and unit names (e.g. Sunday). //! @return: m_iUnitsParsed //! @todo parse odd time zone storage . (-03:00) if (pszTimeString == nullptr) return E_POINTER; const GChar_t* pszSepFind = nullptr; bool bNeedSep = false; m_iUnitsParsed = 0; if (pszSeparators == nullptr) pszSeparators = cTimeUnits::k_SepsAll; int i = 0; for (;;) { int iStart = i; i += StrT::GetNonWhitespaceI(pszTimeString + i); GChar_t ch = pszTimeString[i]; if ((pszSepFind = StrT::FindChar(pszSeparators, ch)) != nullptr) // its a legal separator char? { do_sep: m_Unit[m_iUnitsParsed].m_iOffsetSep = i; m_Unit[m_iUnitsParsed].m_Separator = ch; if (!bNeedSep) { // Was just empty!? NOT ALLOWED. break; } bNeedSep = false; m_iUnitsParsed++; if (m_iUnitsParsed >= (int)_countof(m_Unit)) break; if (ch == '\0') // done. break; i++; continue; } if (bNeedSep) // must complete the previous first. { if (iStart == i) // needed a space separator but didn't get one. { if (ch == 'T' && StrChar::IsDigit(pszTimeString[i + 1])) // ISO can use this as a separator. { goto do_sep; } //! @todo parse odd time zone storage . (-03:00) // Check for terminating TZ with no separator. const cTimeZone* pTZ = cTimeZoneMgr::FindTimeZoneHead(pszTimeString + i); if (pTZ != nullptr) { // Insert fake separator. ch = ' '; i--; goto do_sep; } break; // quit. } // Was whitespace separator. m_Unit[m_iUnitsParsed].m_iOffsetSep = iStart; m_Unit[m_iUnitsParsed].m_Separator = ' '; bNeedSep = false; m_iUnitsParsed++; if (m_iUnitsParsed >= (int)_countof(m_Unit)) break; } if (ch == '\0') // done. break; m_Unit[m_iUnitsParsed].Init(); const GChar_t* pszStart = pszTimeString + i; if (StrChar::IsDigit(ch)) { // We found a number. good. use it. m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_Numeric; // this just means its a number. don't care what kind yet. resolve later. const GChar_t* pszEnd = nullptr; m_Unit[m_iUnitsParsed].m_nValue = (TIMEUNIT_t)StrT::toI(pszStart, &pszEnd, 10); if (pszStart >= pszEnd || pszEnd == nullptr) break; i += StrT::Diff(pszEnd, pszStart); bNeedSep = true; continue; } else if (StrChar::IsAlpha(ch)) // specific named units . DOW, TZ, Month. { int iLen = ParseNamedUnit(pszStart); if (iLen <= 0) break; i += iLen; bNeedSep = true; continue; } // nothing more so stop. break; } // The End. post process. // Identify stuff near : as Time. Always in hour:min:sec format. int iHourFound = -1; int iYearFound = -1; int iMonthFound = -1; for (i = 0; i < m_iUnitsParsed; i++) { if (iMonthFound < 0 && m_Unit[i].m_Type == TIMEUNIT_Month) { iMonthFound = i; } if (iYearFound < 0 && m_Unit[i].m_Type == TIMEUNIT_Numeric && m_Unit[i].m_nValue > 366) { // This must be the year. iYearFound = i; m_Unit[i].m_Type = TIMEUNIT_Year; } if (iHourFound < 0 && m_Unit[i].m_Type == TIMEUNIT_Numeric && m_Unit[i].m_Separator == ':') { iHourFound = i; m_Unit[i].m_Type = TIMEUNIT_Hour; i++; m_Unit[i].m_Type = TIMEUNIT_Minute; if (i + 1 < m_iUnitsParsed && m_Unit[i + 1].m_Type == TIMEUNIT_Numeric && m_Unit[i].m_Separator == ':') { i++; m_Unit[i].m_Type = TIMEUNIT_Second; if (i + 1 < m_iUnitsParsed && m_Unit[i + 1].m_Type == TIMEUNIT_Numeric && m_Unit[i].m_Separator == '.') { i++; m_Unit[i].m_Type = TIMEUNIT_Millisecond; } } } if (iHourFound >= 0 && m_Unit[i].m_Type == TIMEUNIT_Hour) // PM ? { m_Unit[i].m_Type = TIMEUNIT_Ignore; // Ignore this from now on. if (m_Unit[iHourFound].m_nValue < 12) { m_Unit[iHourFound].m_nValue += m_Unit[i].m_nValue; // Add 'PM' } } } // Fail is there are type dupes. // Find day if month is found ? // We are not reading a valid time/date anymore. done. stop. m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_UNUSED; // end return m_iUnitsParsed; } TIMEUNIT_TYPE GRAYCALL cTimeParser::GetTypeFromFormatCode(GChar_t ch) // static { switch (ch) { case 'y': // Year without century, as decimal number (00 to 99) case 'Y': // Year with century, as decimal number return TIMEUNIT_Year; case 'b': // Abbreviated month name case 'h': case 'B': // Full month name case 'm': // Month as decimal number (01 to 12) return TIMEUNIT_Month; case 'd': // Day of month as decimal number (01 to 31) return TIMEUNIT_Day; case 'H': // Hour in 24-hour format (00 to 23) case 'I': // Hour in 12-hour format (01 to 12) return TIMEUNIT_Hour; case 'M': // Minute as decimal number (00 to 59) return TIMEUNIT_Minute; case 'S': // Second as decimal number (00 to 59) return TIMEUNIT_Second; case 'Z': // Either the time-zone name or time zone abbreviation, depending on registry settings; no characters if time zone is unknown case 'z': return TIMEUNIT_TZ; case 'a': case 'A': // Day of week. case 'w': // Weekday as decimal number (0 to 6; Sunday is 0) return TIMEUNIT_DOW; // No equiv. ignore. case 'j': // Day of year as decimal number (001 to 366) case 'p': // Current locale's A.M./P.M. indicator for 12-hour clock return TIMEUNIT_Ignore; // No equiv. ignore. } ASSERT(0); return TIMEUNIT_UNUSED; // bad } int cTimeParser::FindType(TIMEUNIT_TYPE t) const { // is this TIMEUNIT_TYPE already used ? for (int i = 0; i < m_iUnitsParsed; i++) { if (m_Unit[i].m_Type == t) return i; } return -1; // TIMEUNIT_TYPE not used. } void cTimeParser::SetUnitFormats(const GChar_t* pszFormat) { //! Similar to ParseString but assumes we just want to set units from a format string. m_iUnitsParsed = 0; int i = 0; for (;;) // TIMEUNIT_QTY2 { GChar_t ch = pszFormat[i]; if (ch == '\0') break; if (ch != '%') break; TIMEUNIT_TYPE eType = GetTypeFromFormatCode(pszFormat[i + 1]); m_Unit[m_iUnitsParsed].m_Type = eType; if (IS_INDEX_BAD(eType, TIMEUNIT_Numeric)) // this should not happen ?! bad format string! break; m_Unit[m_iUnitsParsed].m_nValue = -1; // set later. m_Unit[m_iUnitsParsed].m_iOffsetSep = i + 2; ch = pszFormat[i + 2]; m_Unit[m_iUnitsParsed].m_Separator = ch; m_iUnitsParsed++; if (ch == '\0') break; i += 3; i += StrT::GetNonWhitespaceI(pszFormat + i); } } bool GRAYCALL cTimeParser::TestMatchUnit(const cTimeParserUnit& u, TIMEUNIT_TYPE t) // static { // is the value and type in cTimeParserUnit compatible with type t; ASSERT(IS_INDEX_GOOD(u.m_Type, TIMEUNIT_QTY2)); ASSERT(IS_INDEX_GOOD(t, TIMEUNIT_Numeric)); if (IS_INDEX_GOOD_ARRAY(t, cTimeUnits::k_Units)) { if (u.m_nValue < cTimeUnits::k_Units[t].m_uMin) return false; if (u.m_nValue > cTimeUnits::k_Units[t].m_uMax) return false; } if (t == u.m_Type) // exact match is good. return true; // TIMEUNIT_Numeric is parsed wildcard (i don't know yet) type. if (u.m_Type == TIMEUNIT_Numeric) // known types must match. TIMEUNIT_Month or TIMEUNIT_DOW return true; // It looks like a match ? I guess. return false; // not a match. } bool cTimeParser::TestMatchFormat(const cTimeParser& parserFormat, bool bTrimJunk) { //! Does parserFormat fit with data in m_Units ? //! Does this contain compatible units with parserFormat? if so fix m_Unit types! //! @arg bTrimJunk = any unrecognized stuff beyond parserFormat can just be trimmed. ASSERT(m_iUnitsParsed <= (int)_countof(m_Unit)); if (m_iUnitsParsed <= 1) return false; int iUnitsMatched = 0; for (; iUnitsMatched < m_iUnitsParsed && iUnitsMatched < parserFormat.m_iUnitsParsed; iUnitsMatched++) // TIMEUNIT_QTY2 { if (!TestMatchUnit(m_Unit[iUnitsMatched], parserFormat.m_Unit[iUnitsMatched].m_Type)) // not all parserFormat matched. return false; } // All m_iUnitsParsed matches parserFormat, but is there more ? if (m_iUnitsParsed > parserFormat.m_iUnitsParsed) { // More arguments than the template supplies . is this OK? // As long as the extra units are assigned and not duplicated we are good. for (; iUnitsMatched < m_iUnitsParsed; iUnitsMatched++) { TIMEUNIT_TYPE t = m_Unit[iUnitsMatched].m_Type; if (t == TIMEUNIT_Numeric) // cant determine type. { if (bTrimJunk) break; return false; } if (parserFormat.FindType(t) >= 0) // duped. return false; if (FindType(t) < iUnitsMatched) // duped. return false; } } if (iUnitsMatched < parserFormat.m_iUnitsParsed) { if (parserFormat.m_iUnitsParsed <= 3) // must have at least 3 parsed units to be valid. return false; if (iUnitsMatched < 3) return false; // int iLeft = parserFormat.m_iUnitsParsed - m_iUnitsParsed; } // Its a match, so fix the ambiguous types. for (int i = 0; i < iUnitsMatched && i < parserFormat.m_iUnitsParsed; i++) { if (m_Unit[i].m_Type == TIMEUNIT_Numeric) m_Unit[i].m_Type = parserFormat.m_Unit[i].m_Type; } m_iUnitsMatched = iUnitsMatched; return true; // its compatible! } bool cTimeParser::TestMatch(const GChar_t* pszFormat) { //! Does pszFormat fit with data in m_Units ? if (pszFormat == nullptr) return false; if (m_iUnitsParsed <= 1) return false; cTimeParser t1; t1.SetUnitFormats(pszFormat); return TestMatchFormat(t1); } bool cTimeParser::TestMatches(const GChar_t** ppStrFormats) { //! Try standard k_StrFormats to match. if (m_iUnitsParsed <= 1) return false; if (ppStrFormats == nullptr) { ppStrFormats = cTimeUnits::k_StrFormats; } for (int i = 0; ppStrFormats[i] != nullptr; i++) { if (TestMatch(ppStrFormats[i])) return true; } // If all units have assignments then no match is needed ?? return false; } HRESULT cTimeParser::GetTimeUnits(OUT cTimeUnits& tu) const { //! Make a valid cTimeUnits class from what we already parsed. If i can. if (!isMatched()) return MK_E_SYNTAX; for (int i = 0; i < m_iUnitsMatched; i++) // <TIMEUNIT_QTY2 { if (m_Unit[i].m_Type >= TIMEUNIT_QTY) { continue; // TIMEUNIT_DOW, TIMEUNIT_Ignore ignored. } tu.SetUnit(m_Unit[i].m_Type, m_Unit[i].m_nValue); } return GetMatchedLength(); } }
28.664557
142
0.627953
MenaceSan
6f65e943f84922e051aab70aef8f82b5238e41a5
1,055
hpp
C++
Fw/Prm/PrmString.hpp
lahiruroot/fprime
8245dbd0c454e379af3504b70462e98d7f4353c2
[ "Apache-2.0" ]
4
2021-02-20T13:38:25.000Z
2021-05-04T17:20:34.000Z
Fw/Prm/PrmString.hpp
lahiruroot/fprime
8245dbd0c454e379af3504b70462e98d7f4353c2
[ "Apache-2.0" ]
4
2020-10-12T18:52:14.000Z
2021-09-02T22:38:58.000Z
Fw/Prm/PrmString.hpp
lahiruroot/fprime
8245dbd0c454e379af3504b70462e98d7f4353c2
[ "Apache-2.0" ]
5
2019-09-06T23:25:26.000Z
2021-06-22T03:01:07.000Z
#ifndef FW_PRM_STRING_TYPE_HPP #define FW_PRM_STRING_TYPE_HPP #include <Fw/Types/BasicTypes.hpp> #include <Fw/Types/StringType.hpp> #include <FpConfig.hpp> #include <Fw/Cfg/SerIds.hpp> namespace Fw { class ParamString : public Fw::StringBase { public: enum { SERIALIZED_TYPE_ID = FW_TYPEID_PRM_STR, SERIALIZED_SIZE = FW_PARAM_STRING_MAX_SIZE + sizeof(FwBuffSizeType) // size of buffer + storage of two size words }; ParamString(const char* src); ParamString(const StringBase& src); ParamString(const ParamString& src); ParamString(void); ParamString& operator=(const ParamString& other); ParamString& operator=(const StringBase& other); ParamString& operator=(const char* other); ~ParamString(void); const char* toChar(void) const; NATIVE_UINT_TYPE getCapacity(void) const; private: char m_buf[FW_PARAM_STRING_MAX_SIZE]; }; } #endif
27.051282
129
0.625592
lahiruroot
6f72053a49d3d65e4318d2a9fe335cfa808a5d8d
372
hpp
C++
src/EditorTraceBuilder.hpp
ryu-raptor/amf
33a42cf1025ea512f23c4769a5be27d6a0c335bc
[ "MIT" ]
1
2020-05-31T02:25:39.000Z
2020-05-31T02:25:39.000Z
src/EditorTraceBuilder.hpp
ryu-raptor/amf
33a42cf1025ea512f23c4769a5be27d6a0c335bc
[ "MIT" ]
null
null
null
src/EditorTraceBuilder.hpp
ryu-raptor/amf
33a42cf1025ea512f23c4769a5be27d6a0c335bc
[ "MIT" ]
null
null
null
#pragma once #include <fstream> #include <string> #include <vector> #include <memory> #include "Trace.hpp" #include "Pacemaker.hpp" namespace otoge2019 { /// ファイルからトレースを作成 class EditorTraceBuilder { public: /// @fn /// トレースをビルド std::shared_ptr<std::vector<std::shared_ptr<Trace>>> build(std::string, Pacemaker&); }; } // namespace otoge2019
19.578947
90
0.666667
ryu-raptor
4cf7e02d9d072783424bd496685228e748517e01
608
cpp
C++
PAT_B/PAT_B1067.cpp
EnhydraGod/PATCode
ff38ea33ba319af78b3aeba8aa6c385cc5e8329f
[ "BSD-2-Clause" ]
3
2019-07-08T05:20:28.000Z
2021-09-22T10:53:26.000Z
PAT_B/PAT_B1067.cpp
EnhydraGod/PATCode
ff38ea33ba319af78b3aeba8aa6c385cc5e8329f
[ "BSD-2-Clause" ]
null
null
null
PAT_B/PAT_B1067.cpp
EnhydraGod/PATCode
ff38ea33ba319af78b3aeba8aa6c385cc5e8329f
[ "BSD-2-Clause" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { string ansStr, tempStr; vector<string> strVec; int i, n; cin >> ansStr >> n; getchar(); while(1) { getline(cin, tempStr); if(tempStr == "#") break; else strVec.push_back(tempStr); } for (i = 0; i < n; i++) { if(i == strVec.size()) break; if(strVec[i] == ansStr) { printf("Welcome in\n"); return 0; } else printf("Wrong password: %s\n", strVec[i].c_str()); } if(i == n) printf("Account locked\n"); return 0; }
20.965517
63
0.483553
EnhydraGod
4cfb8a77b20fe613ad253e1681d17005225fda0b
5,465
cpp
C++
buffer_cache.cpp
cephalicmarble/drumlin
c86319fbb0670fa7cf9437e335f0a41ab7496028
[ "MIT" ]
null
null
null
buffer_cache.cpp
cephalicmarble/drumlin
c86319fbb0670fa7cf9437e335f0a41ab7496028
[ "MIT" ]
null
null
null
buffer_cache.cpp
cephalicmarble/drumlin
c86319fbb0670fa7cf9437e335f0a41ab7496028
[ "MIT" ]
null
null
null
#define TAOJSON #include "buffer_cache.h" #include <vector> #include <algorithm> #include <boost/date_time/posix_time/posix_time.hpp> #include "drumlin.h" namespace drumlin { namespace Buffers { /** * @brief BufferCache::BufferCache : only constructor */ BufferCache::BufferCache() { } /** * @brief BufferCache::~BufferCache : deletes buffers from the container, without flushing */ BufferCache::~BufferCache() { std::lock_guard<std::mutex> l(m_mutex); } /** * @brief BufferCache::isLocked : check the cache mutex * @return bool */ bool BufferCache::isLocked() { if(m_mutex.try_lock()){ m_mutex.unlock(); return false; } return true; } /** * @brief BufferCache::addBuffer : adds buffer to the container * @param std::pair<UseIdent, heap_ptr_type> * @return quint32 number of buffers dealt */ guint32 BufferCache::addAllocated(buffers_heap_map_type::value_type const& pair) { {LOGLOCK;Debug() << "Cache" << pair.first.getSourceName() << boost::posix_time::microsec_clock();} m_buffers.push_back(pair); int n = 0; std::for_each(pair.second->blocks.begin(), pair.second->blocks.end(), [this, &n](auto & heap){ publish((HeapBuffer*)heap.second); ++n; }); return n; } // /** // * @brief BufferCache::flushDeadBuffers : loop within loop to find subscribed transforms and flush the dead buffers // * @return number of buffers removed // */ // guint32 BufferCache::flushDeadBuffers() // { // guint32 c(0); // buffers.erase(std::remove_if(buffers.begin(),buffers.end(),[this,&c](buffers_type::value_type &buffer){ // if(buffer->isDead()){ // callSubscribed(buffer.get(),true); // c++; // return true; // } // return false; // }),buffers.end()); // for(subs_type::value_type &sub : subscriptions){ // sub.second->flush(nullptr); // } // return c; // } /** * @brief BufferCache::clearRelevantBuffers : loop to delete buffers by relevance * @return number of buffers removed */ guint32 BufferCache::clearAllocated(UseIdentFilter use) { std::vector<buffers_heap_map_type::value_type> pairs; int n = 0; std::for_each(m_buffers.begin(), m_buffers.end(), [&n, &pairs, use] (buffers_heap_map_type::value_type & pair) { if(use == pair.first) { n += pair.second->freeAll(); pairs.push_back(pair); } }); for(auto it : pairs) { m_buffers.erase(std::remove(m_buffers.begin(), m_buffers.end(), it)); } return n; } /** * @brief BufferCache::findRelevant : loop over buffers to find relevant entries * @param rel Relevance * @return Buffers::VectorOfBuffers* */ buffer_list_type BufferCache::findRelevant(UseIdentFilter use) { buffer_list_type relevant; std::for_each(m_buffers.begin(), m_buffers.end(), [&relevant, use](auto & buffer){ {LOGLOCK;Debug() << "Cache" << __func__ << buffer.first;} if(use == buffer.first) { for(auto & block : buffer.second->blocks) { relevant.push_back((HeapBuffer*)block.second); } } }); return relevant; } /** * @brief BufferCache::subscribe * @param std::pair<UseIdent, Acceptor*> (see Buffers::make_sub) * @return Buffers::VectorOfBuffers* relevant */ buffer_list_type BufferCache::subscribe(subs_map_type::value_type sub) { m_subscriptions.push_back(sub); return findRelevant(sub.first); } int BufferCache::unsubscribe(subs_map_type::value_type::second_type &acceptor) { int n = 0; std::vector<subs_map_type::iterator> pairs; for(auto it(m_subscriptions.begin()); it != m_subscriptions.end(); ++it) { if (it->second == acceptor) { ++n; pairs.push_back(it); } } for(auto & p : pairs) { m_subscriptions.erase(p); } return n; } /** * @brief BufferCache::callSubscribed : loop over subscriptions to find relevant transforms * @param buffer Buffer * @param flush bool * @return guint32 number of transforms called */ guint32 BufferCache::publish(HeapBuffer * buffer) { guint32 c(0); for(subs_map_type::value_type &sub : m_subscriptions) { if(sub.first == buffer->getUseIdent()){ sub.second->accept(buffer); c++; } } return c; } int BufferCache::getStatus(json::value *status) { json::value cache(json::empty_object); json::object_t &obj(cache.get_object()); json::value subs(json::empty_array); json::array_t &array(subs.get_array()); for(subs_map_type::value_type const& sub : m_subscriptions){ json::value _sub(json::empty_object); UseIdent(sub.first).toJson(&_sub); array.push_back(_sub); } obj.insert({"subs",subs}); status->get_object().insert({"cache",cache}); return 0; } /* * thread-safe calls */ addAllocated_t addAllocated(&BufferCache::addAllocated); clearAllocated_t clearAllocated(&BufferCache::clearAllocated); findRelevant_t findRelevant(&BufferCache::findRelevant); subscribe_t subscribe(&BufferCache::subscribe); unsubscribe_t unsubscribe(&BufferCache::unsubscribe); publish_t publish(&BufferCache::publish); getCacheStatus_t getCacheStatus(&BufferCache::getStatus); BufferCache access::s_cache; Allocator access::s_allocator; } // namespace Buffers } // namespace drumlin
26.921182
118
0.64172
cephalicmarble
4cfc46a690d41a0bdbb90b03c781d3a6861ececf
1,137
cc
C++
tests/invoke.cc
chip5441/ezy
4e4ed4edcfe182b4a6b5fd3459a67200474013ec
[ "MIT" ]
null
null
null
tests/invoke.cc
chip5441/ezy
4e4ed4edcfe182b4a6b5fd3459a67200474013ec
[ "MIT" ]
null
null
null
tests/invoke.cc
chip5441/ezy
4e4ed4edcfe182b4a6b5fd3459a67200474013ec
[ "MIT" ]
null
null
null
#include <catch.hpp> #include <ezy/invoke.h> int foo() { return 101; } SCENARIO("invoke") { GIVEN("a struct") { struct S { int f() { return 3; }; constexpr int cf() const { return 4; } int mem{5}; }; struct D : S {}; S s; WHEN("its pointer to member function invoked") { REQUIRE(ezy::invoke(&S::f, s) == 3); } WHEN("its pointer to member function invoked in compile time") { constexpr S cs; static_assert(ezy::invoke(&S::cf, cs) == 4); } WHEN("its pointer to member function invoked on derived") { D d; REQUIRE(ezy::invoke(&S::f, d) == 3); } WHEN("its pointer to member invoked") { S s; REQUIRE(ezy::invoke(&S::mem, s) == 5); //REQUIRE(ezy::invoke(&S::mem, s, 1, 2, 3) == 5); // "Args cannot be provided for member pointer" } } GIVEN("a function") { WHEN("it invoked") { REQUIRE(ezy::invoke(foo) == 101); } } GIVEN("a lambda") { constexpr auto l = [] { return 102; }; WHEN("it invoked") { REQUIRE(ezy::invoke(l) == 102); } } }
16.478261
103
0.510114
chip5441
4cfd341ed7cbb30d4c2e926e0efdc0a52470e86d
1,319
cpp
C++
qn3m.cpp
Gourav1695/pp_assignment2_part1
6cf3b1251741d161ff52c92eb0fcf1d985d1a8aa
[ "MIT" ]
null
null
null
qn3m.cpp
Gourav1695/pp_assignment2_part1
6cf3b1251741d161ff52c92eb0fcf1d985d1a8aa
[ "MIT" ]
null
null
null
qn3m.cpp
Gourav1695/pp_assignment2_part1
6cf3b1251741d161ff52c92eb0fcf1d985d1a8aa
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <time.h> using namespace std; struct node { int player_id; struct node *next; }; struct node *start, *ptr, *ptr1, *new_node, *beginn; int main() { int v2; srand(time(NULL)); int n, k, i, count; cout << "enter the no.of player : " << endl; cin >> n; v2 = rand() % n + 1; cout << v2 << endl; cout << "enter the value of k (person position that is to be eliminated player) : " << endl; cin >> k; start = new struct node; beginn = new struct node; beginn->player_id = v2; start->player_id = 1; ptr = start; ptr1 = beginn; for (i = v2 + 1; i <= n; i++) // for (i = 2; i <= n; i++)/ { new_node = new struct node; ptr->next = new_node; new_node->player_id = i; new_node->next = start; ptr = new_node; } for (count = n; count > v2; count--) // for (count = n; count > 1; count--) { for (int j = v2; j < v2 + k; ++j) // for (i = 1; i < k; ++i) ptr = ptr->next; cout << " " << ptr->next->player_id << " " << "deleted"; ptr->next = ptr->next->next; } cout << "\n" << "The winner is " << ptr->player_id; return 0; }
23.140351
97
0.461713
Gourav1695
9804f1cd2784d3bf0c2da9c8e89a89bdc09fd5d2
244
hpp
C++
typed_python/PyForwardInstance.hpp
npang1/nativepython
df311a5614a9660c15a8183b2dc606ff3e4600df
[ "Apache-2.0" ]
7
2018-08-07T15:41:54.000Z
2019-02-19T12:47:57.000Z
typed_python/PyForwardInstance.hpp
npang1/nativepython
df311a5614a9660c15a8183b2dc606ff3e4600df
[ "Apache-2.0" ]
38
2018-10-17T13:37:46.000Z
2019-04-11T20:50:14.000Z
typed_python/PyForwardInstance.hpp
npang1/nativepython
df311a5614a9660c15a8183b2dc606ff3e4600df
[ "Apache-2.0" ]
4
2019-02-11T17:44:55.000Z
2019-03-20T07:38:18.000Z
#pragma once #include "PyInstance.hpp" class PyForwardInstance : public PyInstance { public: typedef Forward modeled_type; static bool pyValCouldBeOfTypeConcrete(Type* t, PyObject* pyRepresentation) { return false; } };
17.428571
81
0.721311
npang1
98058cf9ef627263828704600f68564f95695420
831
cpp
C++
Lab 2/Chapter 3 Source Code/Ch3_ProgrammingEx4_Code.cpp
candr002/CS150
8270f60769fc8a9c18e5c5c46879b63663ba2117
[ "Unlicense" ]
null
null
null
Lab 2/Chapter 3 Source Code/Ch3_ProgrammingEx4_Code.cpp
candr002/CS150
8270f60769fc8a9c18e5c5c46879b63663ba2117
[ "Unlicense" ]
null
null
null
Lab 2/Chapter 3 Source Code/Ch3_ProgrammingEx4_Code.cpp
candr002/CS150
8270f60769fc8a9c18e5c5c46879b63663ba2117
[ "Unlicense" ]
null
null
null
//Logic errors. #include <iostream> #include <iomanip> using namespace std; int main() { double cost; double area; double bagSize; cout << fixed << showpoint << setprecision(2); cout << "Enter the amount of fertilizer, in pounds, " << "in one bag: "; cin >> bagSize; cout << endl; cout << "Enter the cost of the " << bagSize << " pound fertilizer bag: "; cin >> cost; cout << endl; cout << "Enter the area, in square feet, that can be " << "fertilized by one bag: "; cin >> area; cout << endl; cout << "The cost of the fertilizer per pound is: $" << bagSize / cost << endl; cout << "The cost of fertilizing per square foot is: $" << area / cost << endl; return 0; }
21.868421
60
0.519856
candr002
980f2bd43fd11162e852dac327bd4541255ab413
431
hpp
C++
src/TitleScreen.hpp
ara159/gravity
d990bcae0b2f980a05a50705ec5633d9532bc599
[ "MIT" ]
null
null
null
src/TitleScreen.hpp
ara159/gravity
d990bcae0b2f980a05a50705ec5633d9532bc599
[ "MIT" ]
null
null
null
src/TitleScreen.hpp
ara159/gravity
d990bcae0b2f980a05a50705ec5633d9532bc599
[ "MIT" ]
null
null
null
#ifndef TITLE_SCREEN #define TITLE_SCREEN 1 #include "MyGameObject.hpp" class TitleScreen : public MyGameObject { private: Texture* txTitle; Texture* txBtnStart; Texture* txBtnRank; Sprite* spTitle; Sprite* spBtnStart; Sprite* spBtnRank; public: TitleScreen(); ~TitleScreen(); void start(); void update(); void draw(RenderWindow*); void handleEvent(Event, RenderWindow*); }; #endif
18.73913
43
0.684455
ara159
980ff7498832c784eab718a8b886e82891047599
2,811
cpp
C++
lavaMD-sycl/util/num/num.cpp
BeauJoh/HeCBench
594b845171d686dc951971ce36ed59cf114dd2b4
[ "BSD-3-Clause" ]
58
2020-08-06T18:53:44.000Z
2021-10-01T07:59:46.000Z
lavaMD-sycl/util/num/num.cpp
BeauJoh/HeCBench
594b845171d686dc951971ce36ed59cf114dd2b4
[ "BSD-3-Clause" ]
66
2015-06-15T20:38:19.000Z
2020-08-26T00:11:43.000Z
lavaMD-sycl/util/num/num.cpp
BeauJoh/HeCBench
594b845171d686dc951971ce36ed59cf114dd2b4
[ "BSD-3-Clause" ]
34
2017-12-14T01:06:58.000Z
2022-02-14T09:40:35.000Z
#ifdef __cplusplus extern "C" { #endif //===============================================================================================================================================================================================================200 // DESCRIPTION //===============================================================================================================================================================================================================200 // Returns: 0 if string does not represent integer // 1 if string represents integer //===============================================================================================================================================================================================================200 // NUM CODE //===============================================================================================================================================================================================================200 //======================================================================================================================================================150 // ISINTEGER FUNCTION //======================================================================================================================================================150 int isInteger(char *str){ //====================================================================================================100 // make sure it's not empty //====================================================================================================100 if (*str == '\0'){ return 0; } //====================================================================================================100 // if any digit is not a number, return false //====================================================================================================100 for(; *str != '\0'; str++){ if (*str < 48 || *str > 57){ // digit characters (need to include . if checking for float) return 0; } } //====================================================================================================100 // it got past all my checks so I think it's a number //====================================================================================================100 return 1; } //===============================================================================================================================================================================================================200 // END NUM CODE //===============================================================================================================================================================================================================200 #ifdef __cplusplus } #endif
52.055556
212
0.144077
BeauJoh
98129e2010a742c1e942454501b9ee2cc01aa60d
23,600
hxx
C++
Utilities/itkVectorImageFileReader.hxx
KevinScholtes/ANTsX
5462269c0c32e5d65560bae4014c5a05cb02588d
[ "BSD-3-Clause" ]
null
null
null
Utilities/itkVectorImageFileReader.hxx
KevinScholtes/ANTsX
5462269c0c32e5d65560bae4014c5a05cb02588d
[ "BSD-3-Clause" ]
null
null
null
Utilities/itkVectorImageFileReader.hxx
KevinScholtes/ANTsX
5462269c0c32e5d65560bae4014c5a05cb02588d
[ "BSD-3-Clause" ]
1
2019-10-06T07:31:58.000Z
2019-10-06T07:31:58.000Z
/*========================================================================= Program: Advanced Normalization Tools Copyright (c) ConsortiumOfANTS. All rights reserved. See accompanying COPYING.txt or https://github.com/stnava/ANTs/blob/master/ANTSCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itkVectorImageFileReader_hxx #define _itkVectorImageFileReader_hxx #include "itkVectorImageFileReader.h" #include "itkObjectFactory.h" #include "itkImageIOFactory.h" #include "itkConvertPixelBuffer.h" #include "itkImageRegion.h" #include "itkPixelTraits.h" #include "itkVectorImage.h" #include "itkImageRegionIterator.h" #include <itksys/SystemTools.hxx> #include <fstream> namespace itk { template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::VectorImageFileReader() { m_ImageIO = 0; m_FileName = ""; m_UserSpecifiedImageIO = false; m_UseAvantsNamingConvention = true; } template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::~VectorImageFileReader() { } template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> void VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os, indent); if( m_ImageIO ) { os << indent << "ImageIO: \n"; m_ImageIO->Print(os, indent.GetNextIndent() ); } else { os << indent << "ImageIO: (null)" << "\n"; } os << indent << "UserSpecifiedImageIO flag: " << m_UserSpecifiedImageIO << "\n"; os << indent << "m_FileName: " << m_FileName << "\n"; } template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> void VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::SetImageIO( ImageIOBase * imageIO) { itkDebugMacro("setting ImageIO to " << imageIO ); if( this->m_ImageIO != imageIO ) { this->m_ImageIO = imageIO; this->Modified(); } m_UserSpecifiedImageIO = true; } template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> void VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::GenerateOutputInformation(void) { typename TVectorImage::Pointer output = this->GetOutput(); itkDebugMacro(<< "Reading file for GenerateOutputInformation()" << m_FileName); // Check to see if we can read the file given the name or prefix // if( m_FileName == "" ) { throw VectorImageFileReaderException(__FILE__, __LINE__, "FileName must be specified", ITK_LOCATION); } // Test if the files exist and if it can be open. // and exception will be thrown otherwise. // std::string tmpFileName = this->m_FileName; // Test if the file exists and if it can be opened. // An exception will be thrown otherwise. // We catch the exception because some ImageIO's may not actually // open a file. Still reports file error if no ImageIO is loaded. try { m_ExceptionMessage = ""; this->TestFileExistanceAndReadability(); } catch( itk::ExceptionObject & err ) { m_ExceptionMessage = err.GetDescription(); } std::string::size_type pos = this->m_FileName.rfind( "." ); std::string extension( this->m_FileName, pos, this->m_FileName.length() - 1 ); std::string filename = std::string( this->m_FileName, 0, pos ); std::string gzExtension( "" ); if( extension == std::string( ".gz" ) ) { gzExtension = extension; std::string::size_type pos2 = filename.rfind( "." ); extension = std::string( filename, pos2, filename.length() - 1 ); filename = std::string( this->m_FileName, 0, pos2 ); } // unsigned int dimension = itk::GetVectorDimension // <VectorImagePixelType>::VectorDimension; // Assume that the first image read contains all the information to generate // the output image. for( unsigned int i = 0; i <= 1; i++ ) { this->m_FileName = filename; if( this->m_UseAvantsNamingConvention ) { switch( i ) { case 0: { this->m_FileName += std::string( "xvec" ); } break; case 1: { this->m_FileName += std::string( "yvec" ); } break; case 2: { this->m_FileName += std::string( "zvec" ); } break; default: { this->m_FileName += std::string( "you_are_screwed_vec" ); } break; } } else { std::ostringstream buf; buf << i; this->m_FileName += ( std::string( "." ) + std::string( buf.str().c_str() ) ); } this->m_FileName += extension; if( !gzExtension.empty() ) { this->m_FileName += std::string( ".gz" ); } if( i == 0 ) { itkDebugMacro( << "Generating output information from the file " << this->m_FileName ); if( m_UserSpecifiedImageIO == false ) // try creating via factory { m_ImageIO = ImageIOFactory::CreateImageIO( m_FileName.c_str(), ImageIOFactory::ReadMode ); } if( m_ImageIO.IsNull() ) { std::ostringstream msg; msg << " Could not create IO object for file " << m_FileName.c_str() << std::endl; if( m_ExceptionMessage.size() ) { msg << m_ExceptionMessage; } else { msg << " Tried to create one of the following:" << std::endl; std::list<LightObject::Pointer> allobjects = ObjectFactoryBase::CreateAllInstance("itkImageIOBase"); for( std::list<LightObject::Pointer>::iterator i = allobjects.begin(); i != allobjects.end(); ++i ) { ImageIOBase* io = dynamic_cast<ImageIOBase *>(i->GetPointer() ); msg << " " << io->GetNameOfClass() << std::endl; } msg << " You probably failed to set a file suffix, or" << std::endl; msg << " set the suffix to an unsupported type." << std::endl; } VectorImageFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION); throw e; return; } // Got to allocate space for the image. Determine the characteristics of // the image. // m_ImageIO->SetFileName(m_FileName.c_str() ); m_ImageIO->ReadImageInformation(); typename TVectorImage::SizeType dimSize; double spacing[TVectorImage::ImageDimension]; double origin[TVectorImage::ImageDimension]; typename TVectorImage::DirectionType direction; std::vector<double> axis; for( unsigned int k = 0; k < TImage::ImageDimension; k++ ) { if( k < m_ImageIO->GetNumberOfDimensions() ) { dimSize[k] = m_ImageIO->GetDimensions(k); spacing[k] = m_ImageIO->GetSpacing(k); origin[k] = m_ImageIO->GetOrigin(k); // Please note: direction cosines are stored as columns of the // direction matrix axis = m_ImageIO->GetDirection(k); for( unsigned j = 0; j < TImage::ImageDimension; j++ ) { if( j < m_ImageIO->GetNumberOfDimensions() ) { direction[j][k] = axis[j]; } else { direction[j][k] = 0.0; } } } else { // Number of dimensions in the output is more than number of dimensions // in the ImageIO object (the file). Use default values for the size, // spacing, origin and direction for the final (degenerate) dimensions. dimSize[i] = 1; spacing[i] = 1.0; origin[i] = 0.0; for( unsigned j = 0; j < TImage::ImageDimension; j++ ) { if( i == j ) { direction[j][k] = 1.0; } else { direction[j][k] = 0.0; } } } } output->SetSpacing( spacing ); // Set the image spacing output->SetOrigin( origin ); // Set the image origin output->SetDirection( direction ); // Set the image direction cosines // Copy MetaDataDictionary from instantiated reader to output image. output->SetMetaDataDictionary(m_ImageIO->GetMetaDataDictionary() ); this->SetMetaDataDictionary(m_ImageIO->GetMetaDataDictionary() ); this->m_Image->SetSpacing( spacing ); this->m_Image->SetOrigin( origin ); this->m_Image->SetDirection( direction ); this->m_Image->SetMetaDataDictionary(m_ImageIO->GetMetaDataDictionary() ); typedef typename TVectorImage::IndexType IndexType; IndexType start; start.Fill(0); VectorImageRegionType region; region.SetSize(dimSize); region.SetIndex(start); ImageRegionType imageregion; imageregion.SetSize(dimSize); imageregion.SetIndex(start); // If a VectorImage, this requires us to set the // VectorLength before allocate // if( strcmp( output->GetNameOfClass(), "VectorImage" ) == 0 ) // { // typedef typename TImage::AccessorFunctorType AccessorFunctorType; // AccessorFunctorType::SetVectorLength( output, m_ImageIO->GetNumberOfComponents() ); // } output->SetLargestPossibleRegion( region ); this->m_Image->SetLargestPossibleRegion( imageregion ); } } this->m_FileName = tmpFileName; } template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> void VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::TestFileExistanceAndReadability() { std::string tmpFileName = this->m_FileName; std::string::size_type pos = this->m_FileName.rfind( "." ); std::string extension( this->m_FileName, pos, this->m_FileName.length() - 1 ); std::string filename = std::string( this->m_FileName, 0, pos ); std::string gzExtension( "" ); if( extension == std::string( ".gz" ) ) { gzExtension = extension; std::string::size_type pos2 = filename.rfind( "." ); extension = std::string( filename, pos2, filename.length() - 1 ); filename = std::string( this->m_FileName, 0, pos2 ); } unsigned int dimension = itk::GetVectorDimension <VectorImagePixelType>::VectorDimension; for( unsigned int i = 0; i < dimension; i++ ) { this->m_FileName = filename; if( this->m_UseAvantsNamingConvention ) { switch( i ) { case 0: { this->m_FileName += std::string( "xvec" ); } break; case 1: { this->m_FileName += std::string( "yvec" ); } break; case 2: { this->m_FileName += std::string( "zvec" ); } break; default: { this->m_FileName += std::string( "you_are_screwed_vec" ); } break; } } else { std::ostringstream buf; buf << i; this->m_FileName += ( std::string( "." ) + std::string( buf.str().c_str() ) ); } this->m_FileName += extension; if( !gzExtension.empty() ) { this->m_FileName += std::string( ".gz" ); } itkDebugMacro( << "Checking for the file " << this->m_FileName ); // Test if the file exists. if( !itksys::SystemTools::FileExists( m_FileName.c_str() ) ) { VectorImageFileReaderException e(__FILE__, __LINE__); std::ostringstream msg; msg << "The file doesn't exists. " << std::endl << "Filename = " << m_FileName << std::endl; e.SetDescription(msg.str().c_str() ); throw e; return; } // Test if the file can be open for reading access. std::ifstream readTester; readTester.open( m_FileName.c_str() ); if( readTester.fail() ) { readTester.close(); std::ostringstream msg; msg << "The file couldn't be opened for reading. " << std::endl << "Filename: " << m_FileName << std::endl; VectorImageFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION); throw e; return; } readTester.close(); } this->m_FileName = tmpFileName; } template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> void VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::EnlargeOutputRequestedRegion(DataObject *output) { typename TVectorImage::Pointer out = dynamic_cast<TVectorImage *>(output); // the ImageIO object cannot stream, then set the RequestedRegion to the // LargestPossibleRegion if( !m_ImageIO->CanStreamRead() ) { if( out ) { out->SetRequestedRegion( out->GetLargestPossibleRegion() ); } else { throw VectorImageFileReaderException(__FILE__, __LINE__, "Invalid output object type"); } } } template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> void VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::GenerateData() { typename TVectorImage::Pointer output = this->GetOutput(); // allocate the output buffer output->SetBufferedRegion( output->GetRequestedRegion() ); output->Allocate(); this->m_Image->SetBufferedRegion( output->GetRequestedRegion() ); this->m_Image->Allocate(); // Test if the file exist and if it can be open. // and exception will be thrown otherwise. try { m_ExceptionMessage = ""; this->TestFileExistanceAndReadability(); } catch( itk::ExceptionObject & err ) { m_ExceptionMessage = err.GetDescription(); } std::string tmpFileName = this->m_FileName; std::string::size_type pos = this->m_FileName.rfind( "." ); std::string extension( this->m_FileName, pos, this->m_FileName.length() - 1 ); std::string filename = std::string( this->m_FileName, 0, pos ); std::string gzExtension( "" ); if( extension == std::string( ".gz" ) ) { gzExtension = extension; std::string::size_type pos2 = filename.rfind( "." ); extension = std::string( filename, pos2, filename.length() - 1 ); filename = std::string( this->m_FileName, 0, pos2 ); } unsigned int dimension = itk::GetVectorDimension <VectorImagePixelType>::VectorDimension; for( unsigned int i = 0; i < dimension; i++ ) { this->m_FileName = filename; if( this->m_UseAvantsNamingConvention ) { switch( i ) { case 0: { this->m_FileName += std::string( "xvec" ); } break; case 1: { this->m_FileName += std::string( "yvec" ); } break; case 2: { this->m_FileName += std::string( "zvec" ); } break; default: { this->m_FileName += std::string( "you_are_screwed_vec" ); } break; } } else { std::ostringstream buf; buf << i; this->m_FileName += ( std::string( "." ) + std::string( buf.str().c_str() ) ); } this->m_FileName += extension; if( !gzExtension.empty() ) { this->m_FileName += std::string( ".gz" ); } itkDebugMacro( << "Reading image buffer from the file " << this->m_FileName ); // Tell the ImageIO to read the file m_ImageIO->SetFileName(m_FileName.c_str() ); this->m_FileName = tmpFileName; ImageIORegion ioRegion(TImage::ImageDimension); ImageIORegion::SizeType ioSize = ioRegion.GetSize(); ImageIORegion::IndexType ioStart = ioRegion.GetIndex(); typename TImage::SizeType dimSize; for( unsigned int j = 0; j < TImage::ImageDimension; j++ ) { if( j < m_ImageIO->GetNumberOfDimensions() ) { dimSize[j] = m_ImageIO->GetDimensions(j); } else { // Number of dimensions in the output is more than number of dimensions // in the ImageIO object (the file). Use default values for the size, // spacing, and origin for the final (degenerate) dimensions. dimSize[j] = 1; } } for( unsigned int j = 0; j < dimSize.GetSizeDimension(); ++j ) { ioSize[j] = dimSize[j]; } typedef typename TImage::IndexType IndexType; IndexType start; start.Fill(0); for( unsigned int j = 0; j < start.GetIndexDimension(); ++j ) { ioStart[j] = start[j]; } ioRegion.SetSize(ioSize); ioRegion.SetIndex(ioStart); itkDebugMacro(<< "ioRegion: " << ioRegion); m_ImageIO->SetIORegion(ioRegion); char *loadBuffer = 0; // the size of the buffer is computed based on the actual number of // pixels to be read and the actual size of the pixels to be read // (as opposed to the sizes of the output) try { if( /** FIXME */ // m_ImageIO->GetComponentTypeInfo() // != typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType) // || (m_ImageIO->GetNumberOfComponents() != ConvertPixelTraits::GetNumberOfComponents() ) ) { // the pixel types don't match so a type conversion needs to be // performed itkDebugMacro(<< "Buffer conversion required from: " << " FIXME m_ImageIO->GetComponentTypeInfo().name() " << " to: " << typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType).name() ); loadBuffer = new char[m_ImageIO->GetImageSizeInBytes()]; m_ImageIO->Read( static_cast<void *>(loadBuffer) ); // See note below as to why the buffered region is needed and // not actualIOregion this->DoConvertBuffer(static_cast<void *>(loadBuffer), output->GetBufferedRegion().GetNumberOfPixels() ); } else // a type conversion is not necessary { itkDebugMacro(<< "No buffer conversion required."); ImagePixelType *buffer = this->m_Image->GetPixelContainer()->GetBufferPointer(); m_ImageIO->Read( buffer ); } } catch( ... ) { // if an exception is thrown catch it if( loadBuffer ) { // clean up delete [] loadBuffer; loadBuffer = 0; } // then rethrow throw; } // clean up if( loadBuffer ) { delete [] loadBuffer; loadBuffer = 0; } ImageRegionIterator<TVectorImage> Id( this->GetOutput(), this->GetOutput()->GetLargestPossibleRegion() ); ImageRegionIterator<TImage> It( this->m_Image, this->m_Image->GetLargestPossibleRegion() ); Id.GoToBegin(); It.GoToBegin(); while( !Id.IsAtEnd() || !It.IsAtEnd() ) { VectorImagePixelType V = Id.Get(); V[i] = static_cast<typename VectorImagePixelType::ValueType>( It.Get() ); Id.Set( V ); ++Id; ++It; } } } template <typename TImage, typename TVectorImage, typename ConvertPixelTraits> void VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits> ::DoConvertBuffer(void* inputData, unsigned long numberOfPixels) { // get the pointer to the destination buffer ImagePixelType *imageData = this->m_Image->GetPixelContainer()->GetBufferPointer(); // TODO: // Pass down the PixelType (RGB, VECTOR, etc.) so that any vector to // scalar conversion be type specific. i.e. RGB to scalar would use // a formula to convert to luminance, VECTOR to scalar would use // vector magnitude. // Create a macro as this code is a bit lengthy and repetitive // if the ImageIO pixel type is typeid(type) then use the ConvertPixelBuffer // class to convert the data block to TImage's pixel type // see DefaultConvertPixelTraits and ConvertPixelBuffer // The first else if block applies only to images of type itk::VectorImage // VectorImage needs to copy out the buffer differently.. The buffer is of // type InternalPixelType, but each pixel is really 'k' consecutive pixels. #define ITK_CONVERT_BUFFER_IF_BLOCK(type) \ else if( true /** FIXME m_ImageIO->GetComponentTypeInfo() == typeid(type) ) */ ) \ { \ if( strcmp( this->GetOutput()->GetNameOfClass(), "VectorImage" ) == 0 ) \ { \ ConvertPixelBuffer< \ type, \ ImagePixelType, \ ConvertPixelTraits \ > \ ::ConvertVectorImage( \ static_cast<type *>(inputData), \ m_ImageIO->GetNumberOfComponents(), \ imageData, \ numberOfPixels); \ } \ else \ { \ ConvertPixelBuffer< \ type, \ ImagePixelType, \ ConvertPixelTraits \ > \ ::Convert( \ static_cast<type *>(inputData), \ m_ImageIO->GetNumberOfComponents(), \ imageData, \ numberOfPixels); \ } \ } if( 0 ) { } ITK_CONVERT_BUFFER_IF_BLOCK(unsigned char) ITK_CONVERT_BUFFER_IF_BLOCK(char) ITK_CONVERT_BUFFER_IF_BLOCK(unsigned short) ITK_CONVERT_BUFFER_IF_BLOCK( short) ITK_CONVERT_BUFFER_IF_BLOCK(unsigned int) ITK_CONVERT_BUFFER_IF_BLOCK( int) ITK_CONVERT_BUFFER_IF_BLOCK(unsigned long) ITK_CONVERT_BUFFER_IF_BLOCK( long) ITK_CONVERT_BUFFER_IF_BLOCK(float) ITK_CONVERT_BUFFER_IF_BLOCK( double) else { VectorImageFileReaderException e(__FILE__, __LINE__); std::ostringstream msg; msg << "Couldn't convert component type: " << std::endl << " " << m_ImageIO->GetComponentTypeAsString(m_ImageIO->GetComponentType() ) << std::endl << "to one of: " << std::endl << " " << typeid(unsigned char).name() << std::endl << " " << typeid(char).name() << std::endl << " " << typeid(unsigned short).name() << std::endl << " " << typeid(short).name() << std::endl << " " << typeid(unsigned int).name() << std::endl << " " << typeid(int).name() << std::endl << " " << typeid(unsigned long).name() << std::endl << " " << typeid(long).name() << std::endl << " " << typeid(float).name() << std::endl << " " << typeid(double).name() << std::endl; e.SetDescription(msg.str().c_str() ); e.SetLocation(ITK_LOCATION); throw e; return; } #undef ITK_CONVERT_BUFFER_IF_BLOCK } } // namespace ITK #endif
32.108844
105
0.579661
KevinScholtes
98140f5ab75cbb6a9f7d5201745af88b5a7383ba
6,750
cpp
C++
src/lib/rtm/SystemLogger.cpp
r-kurose/OpenRTM-aist
258c922c55a97c6d1265dbf45e1e8b2ea29b2d86
[ "RSA-MD" ]
15
2019-01-08T15:34:04.000Z
2022-03-01T08:36:17.000Z
src/lib/rtm/SystemLogger.cpp
r-kurose/OpenRTM-aist
258c922c55a97c6d1265dbf45e1e8b2ea29b2d86
[ "RSA-MD" ]
448
2018-12-27T03:13:56.000Z
2022-03-24T09:57:03.000Z
src/lib/rtm/SystemLogger.cpp
r-kurose/OpenRTM-aist
258c922c55a97c6d1265dbf45e1e8b2ea29b2d86
[ "RSA-MD" ]
31
2018-12-26T04:34:22.000Z
2021-11-25T04:39:51.000Z
// -*- C++ -*- /*! * @file SystemLogger.cpp * @brief RT component logger class * @date $Date: 2007-07-20 16:10:32 $ * @author Noriaki Ando <[email protected]> * * Copyright (C) 2003-2008 * Task-intelligence Research Group, * Intelligent Systems Research Institute, * National Institute of * Advanced Industrial Science and Technology (AIST), Japan * All rights reserved. * * $Id: SystemLogger.cpp 845 2008-09-25 11:10:40Z n-ando $ * */ #include <rtm/SystemLogger.h> #include <rtm/Manager.h> #include <sstream> #include <iomanip> #define MAXSIZE 256 namespace RTC { const char* const Logger::m_levelString[] = { "SILENT", "FATAL", "ERROR", "WARNING", "INFO", "DEBUG", "TRACE", "VERBOSE", "PARANOID" }; const char* const Logger::m_levelOutputString[] = { " SILENT: ", " FATAL: ", " ERROR: ", " WARNING: ", " INFO: ", " DEBUG: ", " TRACE: ", " VERBOSE: ", " PARANOID: " }; const char* const Logger::m_levelColor[] = { "\x1b[0m", // SLILENT (none) "\x1b[0m\x1b[31m", // FATAL (red) "\x1b[0m\x1b[35m", // ERROR (magenta) "\x1b[0m\x1b[33m", // WARN (yellow) "\x1b[0m\x1b[34m", // INFO (blue) "\x1b[0m\x1b[32m", // DEBUG (green) "\x1b[0m\x1b[36m", // TRACE (cyan) "\x1b[0m\x1b[39m", // VERBOSE (default) "\x1b[0m\x1b[37m" // PARANOID (white) }; Logger::Logger(const char* name) : ::coil::LogStream(&(Manager::instance().getLogStreamBuf()), RTL_SILENT, RTL_PARANOID, RTL_SILENT), m_name(name) { setLevel(Manager::instance().getLogLevel().c_str()); coil::Properties& prop(Manager::instance().getConfig()); if (prop.findNode("logger.date_format") != nullptr) { setDateFormat(prop["logger.date_format"].c_str()); } if (prop.findNode("logger.clock_type") != nullptr) { setClockType(prop["logger.clock_type"]); } } Logger::Logger(LogStreamBuf* streambuf) : ::coil::LogStream(streambuf, RTL_SILENT, RTL_PARANOID, RTL_SILENT) { setDateFormat(m_dateFormat.c_str()); } Logger::~Logger() = default; /*! * @if jp * @brief ログレベルを文字列で設定する * @else * @brief Set log level by string * @endif */ bool Logger::setLevel(const char* level) { return coil::LogStream::setLevel(strToLevel(level)); } /*! * @if jp * @brief ヘッダに付加する日時フォーマットを指定する。 * @else * @brief Set date/time format for adding the header * @endif */ void Logger::setDateFormat(const char* format) { std::string fmt(format); m_msEnable = std::string::npos != fmt.find("%Q"); m_usEnable = std::string::npos != fmt.find("%q"); if (m_msEnable){ fmt = coil::replaceString(std::move(fmt), "%Q", "#m#"); } if (m_usEnable){ fmt = coil::replaceString(std::move(fmt), "%q", "#u#"); } m_dateFormat = std::move(fmt); } void Logger::setClockType(const std::string& clocktype) { m_clock = &coil::ClockManager::instance().getClock(clocktype); } /*! * @if jp * @brief ヘッダの日時の後に付加する文字列を設定する。 * @else * @brief Set suffix of date/time string of header. * @endif */ void Logger::setName(const char* name) { m_name = name; } /*! * @if jp * @brief フォーマットされた現在日時文字列を取得する。 * @else * @brief Get the current formatted date/time string * @endif */ std::string Logger::getDate() { char buf[MAXSIZE]; auto tm = m_clock->gettime(); auto sec = std::chrono::duration_cast<std::chrono::seconds>(tm); time_t timer = sec.count(); #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) struct tm date; errno_t error = gmtime_s(&date, &timer); if (error == EOVERFLOW) { return std::string(); } strftime(buf, sizeof(buf), m_dateFormat.c_str(), &date); #else struct tm* date; date = gmtime(&timer); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat-nonliteral" // The format parameter is not literal, as it allows the user to change the format. // Therefore, we have controlled -Wformat-nonliteral with pragma. strftime(buf, sizeof(buf), m_dateFormat.c_str(), date); #pragma GCC diagnostic pop #endif std::string fmt(buf); if (m_msEnable) { auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(tm - sec); std::stringstream msec(""); msec << std::setfill('0') << std::setw(3) << ms.count(); fmt = coil::replaceString(std::move(fmt), "#m#", msec.str()); } if (m_usEnable) { auto us = std::chrono::duration_cast<std::chrono::microseconds>(tm - sec); std::stringstream usec(""); usec << std::setfill('0') << std::setw(6) << us.count(); fmt = coil::replaceString(std::move(fmt), "#u#", usec.str()); } return fmt; } /*! * @if jp * @brief ログレベル設定 * @else * @brief Set the log level * @endif */ int Logger::strToLevel(const char* level) { std::string lv(level); if (lv == "SILENT") return RTL_SILENT; else if (lv == "FATAL") return RTL_FATAL; else if (lv == "ERROR") return RTL_ERROR; else if (lv == "WARN") return RTL_WARN; else if (lv == "INFO") return RTL_INFO; else if (lv == "DEBUG") return RTL_DEBUG; else if (lv == "TRACE") return RTL_TRACE; else if (lv == "VERBOSE") return RTL_VERBOSE; else if (lv == "PARANOID") return RTL_PARANOID; else return RTL_SILENT; } /*! * @if jp * * @brief ログの出力 * * 指定したメッセージのログを出力する * * @param level ログレベル * @param mes メッセージ * * * @else * * @brief log output * * * * @param level log level * @param mes message * * @endif */ void Logger::write(int level, const std::string &mes) { if (ostream_type != nullptr) { std::string date = getDate(); ostream_type->write(level, m_name, date, mes); } } /*! * @if jp * * @brief ログの出力 * * 指定したプロパティを文字列に変換してログに出力する * * @param level ログレベル * @param prop プロパティ * * * @else * * @brief log output * * * * @param level log level * @param prop properties * * @endif */ void Logger::write(int level, const coil::Properties &prop) { if (ostream_type != nullptr) { std::vector<std::string> vec(prop); for (auto & str : vec) { ostream_type->write(level, m_name, getDate(), str); } } } } // namespace RTC
23.195876
87
0.560296
r-kurose
9815dd20ae1d892b46f7fe757df35eb2aa3adadc
1,163
cpp
C++
LeetCode/H/Merge-k-Sorted-List.cpp
luismoroco/ProgrCompetitiva
011cdb18749a16d17fd635a7c36a8a21b2b643d9
[ "BSD-3-Clause" ]
null
null
null
LeetCode/H/Merge-k-Sorted-List.cpp
luismoroco/ProgrCompetitiva
011cdb18749a16d17fd635a7c36a8a21b2b643d9
[ "BSD-3-Clause" ]
null
null
null
LeetCode/H/Merge-k-Sorted-List.cpp
luismoroco/ProgrCompetitiva
011cdb18749a16d17fd635a7c36a8a21b2b643d9
[ "BSD-3-Clause" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; ListNode* mergeKLists(vector<ListNode*>& lists) { priority_queue<int, vector<int>, greater<int>> dp; for (int i = 0; i < lists.size(); ++i) { struct ListNode *tmp = lists[i]; while (tmp) { dp.push(tmp -> val); tmp = tmp -> next; } } struct ListNode *reco = nullptr; struct ListNode *ans = nullptr; while (!dp.empty()) { struct ListNode *tmp = new ListNode(dp.top()); dp.pop(); if (!ans) ans = tmp; else { reco = ans; while (reco -> next != nullptr) { reco = reco -> next;} reco -> next = tmp; } } return ans; } int main(int argc, char const *argv[]) { priority_queue<int> x; x.push(1); x.push(2); x.push(-1); x.push(1); while (!x.empty()) { cout << x.top() << ' '; x.pop(); } return 0; }
20.403509
67
0.490972
luismoroco
982070a1a6ebe5e90785863829153ca3d78b46cb
1,632
cpp
C++
DawnBreakers/Source/DawnBreakers/GameLogic/GameRules/GameMode/ZombieSurvive/ZombieSurvivalHUD.cpp
954818696/FPSGame
bc82ceb1b56460a8e0e0c0e9a0da20fb5898e158
[ "MIT" ]
1
2017-01-21T14:08:06.000Z
2017-01-21T14:08:06.000Z
DawnBreakers/Source/DawnBreakers/GameLogic/GameRules/GameMode/ZombieSurvive/ZombieSurvivalHUD.cpp
954818696/FPSGame
bc82ceb1b56460a8e0e0c0e9a0da20fb5898e158
[ "MIT" ]
null
null
null
DawnBreakers/Source/DawnBreakers/GameLogic/GameRules/GameMode/ZombieSurvive/ZombieSurvivalHUD.cpp
954818696/FPSGame
bc82ceb1b56460a8e0e0c0e9a0da20fb5898e158
[ "MIT" ]
2
2017-11-14T10:36:01.000Z
2020-07-13T08:52:08.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "DawnBreakers.h" #include "ZombieSurvivalHUD.h" AZombieSurvivalHUD::AZombieSurvivalHUD(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer), m_ShowHUD(true) { static ConstructorHelpers::FObjectFinder<UTexture2D> CrosshiarTexObjDebug(TEXT("/Game/UI/HUD/T_CenterDot_M.T_CenterDot_M")); CrosshairTex = CrosshiarTexObjDebug.Object; DebugCenterDotIcon = UCanvas::MakeIcon(CrosshiarTexObjDebug.Object); } void AZombieSurvivalHUD::DrawHUD() { Super::DrawHUD(); ADBCharacter* ControlledPawn = Cast<ADBCharacter>(GetWorld()->GetFirstPlayerController()->GetPawn()); if (m_ShowHUD == false) { return; } if (ControlledPawn && ControlledPawn->GetHoldWeapon() == nullptr) { DrawDebugCrossHair(); } } void AZombieSurvivalHUD::DrawDebugCrossHair() { float CenterX = Canvas->ClipX / 2; float CenterY = Canvas->ClipY / 2; float CenterDotScale = 0.07f; Canvas->SetDrawColor(255, 255, 255, 255); Canvas->DrawIcon(DebugCenterDotIcon, CenterX - DebugCenterDotIcon.UL * CenterDotScale / 2.0f, CenterY - DebugCenterDotIcon.VL * CenterDotScale / 2.0f, CenterDotScale); } void AZombieSurvivalHUD::DrawDefaultCrossHair() { const FVector2D Center(Canvas->ClipX * 0.5f, Canvas->ClipY * 0.5f); const FVector2D CrosshairDrawPosition(Center.X, Center.Y); FCanvasTileItem TileItem(CrosshairDrawPosition, CrosshairTex->Resource, FLinearColor::White); TileItem.BlendMode = SE_BLEND_Translucent; Canvas->DrawItem(TileItem); } void AZombieSurvivalHUD::SetHUDVisibility(bool bShow) { m_ShowHUD = bShow; }
27.661017
125
0.765319
954818696
98219446db14f643fa7e1edcdcf079ce6842023a
3,007
hpp
C++
NativeCore/Shared/Keys.hpp
jesterret/ReClass.NET
0ee8a4cd6a00e2664f2ef3250a81089c32d69392
[ "MIT" ]
1,009
2018-02-07T05:07:34.000Z
2022-03-31T10:27:35.000Z
NativeCore/Shared/Keys.hpp
EliteOutlaws/ReClass.NET
8125eac282d56fa0b9040294ca49b2febd7d9237
[ "MIT" ]
161
2018-02-25T00:32:47.000Z
2022-03-31T21:02:50.000Z
NativeCore/Shared/Keys.hpp
EliteOutlaws/ReClass.NET
8125eac282d56fa0b9040294ca49b2febd7d9237
[ "MIT" ]
281
2018-02-07T05:07:43.000Z
2022-03-28T16:42:57.000Z
#pragma once enum class Keys : int32_t { None = 0, LButton = 1, RButton = 2, Cancel = 3, MButton = 4, XButton1 = 5, XButton2 = 6, Back = 8, Tab = 9, LineFeed = 10, Clear = 12, Return = 13, Enter = 13, ShiftKey = 16, ControlKey = 17, Menu = 18, Pause = 19, Capital = 20, CapsLock = 20, KanaMode = 21, HanguelMode = 21, HangulMode = 21, JunjaMode = 23, FinalMode = 24, HanjaMode = 25, KanjiMode = 25, Escape = 27, IMEConvert = 28, IMENonconvert = 29, IMEAccept = 30, IMEAceept = 30, IMEModeChange = 31, Space = 32, Prior = 33, PageUp = 33, Next = 34, PageDown = 34, End = 35, Home = 36, Left = 37, Up = 38, Right = 39, Down = 40, Select = 41, Print = 42, Execute = 43, Snapshot = 44, PrintScreen = 44, Insert = 45, Delete = 46, Help = 47, D0 = 48, D1 = 49, D2 = 50, D3 = 51, D4 = 52, D5 = 53, D6 = 54, D7 = 55, D8 = 56, D9 = 57, A = 65, B = 66, C = 67, D = 68, E = 69, F = 70, G = 71, H = 72, I = 73, J = 74, K = 75, L = 76, M = 77, N = 78, O = 79, P = 80, Q = 81, R = 82, S = 83, T = 84, U = 85, V = 86, W = 87, X = 88, Y = 89, Z = 90, LWin = 91, RWin = 92, Apps = 93, Sleep = 95, NumPad0 = 96, NumPad1 = 97, NumPad2 = 98, NumPad3 = 99, NumPad4 = 100, NumPad5 = 101, NumPad6 = 102, NumPad7 = 103, NumPad8 = 104, NumPad9 = 105, Multiply = 106, Add = 107, Separator = 108, Subtract = 109, Decimal = 110, Divide = 111, F1 = 112, F2 = 113, F3 = 114, F4 = 115, F5 = 116, F6 = 117, F7 = 118, F8 = 119, F9 = 120, F10 = 121, F11 = 122, F12 = 123, F13 = 124, F14 = 125, F15 = 126, F16 = 127, F17 = 128, F18 = 129, F19 = 130, F20 = 131, F21 = 132, F22 = 133, F23 = 134, F24 = 135, NumLock = 144, Scroll = 145, LShiftKey = 160, RShiftKey = 161, LControlKey = 162, RControlKey = 163, LMenu = 164, RMenu = 165, BrowserBack = 166, BrowserForward = 167, BrowserRefresh = 168, BrowserStop = 169, BrowserSearch = 170, BrowserFavorites = 171, BrowserHome = 172, VolumeMute = 173, VolumeDown = 174, VolumeUp = 175, MediaNextTrack = 176, MediaPreviousTrack = 177, MediaStop = 178, MediaPlayPause = 179, LaunchMail = 180, SelectMedia = 181, LaunchApplication1 = 182, LaunchApplication2 = 183, OemSemicolon = 186, Oem1 = 186, OemPlus = 187, OemComma = 188, OemMinus = 189, OemPeriod = 190, OemQuestion = 191, Oem2 = 191, Oemtilde = 192, Oem3 = 192, OemOpenBrackets = 219, Oem4 = 219, OemPipe = 220, Oem5 = 220, OemCloseBrackets = 221, Oem6 = 221, OemQuotes = 222, Oem7 = 222, Oem8 = 223, OemBackslash = 226, Oem102 = 226, ProcessKey = 229, Packet = 231, Attn = 246, Crsel = 247, Exsel = 248, EraseEof = 249, Play = 250, Zoom = 251, NoName = 252, Pa1 = 253, OemClear = 254, KeyCode = 65535, Shift = 65536, Control = 131072, Alt = 262144, Modifiers = -65536 }; inline Keys& operator|=(Keys& lhs, Keys rhs) { using T = std::underlying_type_t<Keys>; lhs = static_cast<Keys>(static_cast<T>(lhs) | static_cast<T>(rhs)); return lhs; }
14.319048
68
0.588959
jesterret
9822cd1f28ae392b5e549930721ef3a468c0eda7
46,171
cpp
C++
Test/Unit/future/FutureTest.cpp
erikzenker/asyncly
550dbec10c3e74c10303345e44ad7c9f98e3db06
[ "ECL-2.0", "Apache-2.0" ]
23
2020-02-25T14:11:58.000Z
2021-09-23T04:32:09.000Z
Test/Unit/future/FutureTest.cpp
erikzenker/asyncly
550dbec10c3e74c10303345e44ad7c9f98e3db06
[ "ECL-2.0", "Apache-2.0" ]
2
2020-03-11T14:04:19.000Z
2020-11-09T20:50:41.000Z
Test/Unit/future/FutureTest.cpp
erikzenker/asyncly
550dbec10c3e74c10303345e44ad7c9f98e3db06
[ "ECL-2.0", "Apache-2.0" ]
9
2020-02-25T14:12:39.000Z
2021-12-28T01:30:48.000Z
/* * Copyright 2019 LogMeIn * * 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. * * SPDX-License-Identifier: Apache-2.0 */ #include <chrono> #include <future> #include <thread> #include "gmock/gmock.h" #include "asyncly/future/Future.h" #include "StrandImplTestFactory.h" #include "asyncly/executor/ExecutorStoppedException.h" #include "asyncly/test/CurrentExecutorGuard.h" #include "asyncly/test/ExecutorTestFactories.h" #include "detail/ThrowingExecutor.h" namespace asyncly { using namespace testing; template <typename TExecutorFactory> class FutureTest : public Test { public: FutureTest() : factory_(std::make_unique<TExecutorFactory>()) , executor_(factory_->create()) { } std::unique_ptr<TExecutorFactory> factory_; std::shared_ptr<IExecutor> executor_; }; using ExecutorFactoryTypes = ::testing::Types< asyncly::test::AsioExecutorFactory<>, asyncly::test::DefaultExecutorFactory<>, asyncly::test::StrandImplTestFactory<>>; TYPED_TEST_SUITE(FutureTest, ExecutorFactoryTypes); TYPED_TEST(FutureTest, shouldRunASimpleContinuation) { std::promise<int> value; this->executor_->post([&value]() { make_ready_future(42).then([&value](int v) { value.set_value(v); return make_ready_future(); }); }); EXPECT_EQ(42, value.get_future().get()); } TYPED_TEST(FutureTest, shouldRunLValueContinuation) { std::promise<int> value; const auto lambda = [&value](int v) { value.set_value(v); return make_ready_future(); }; this->executor_->post([&lambda]() { make_ready_future(42).then(lambda); }); EXPECT_EQ(42, value.get_future().get()); } TYPED_TEST(FutureTest, shouldRunANoncopyableContinuation) { std::promise<int> value; auto future = value.get_future(); this->executor_->post([&value]() { make_ready_future(42).then([promise{ std::move(value) }](int v) mutable { promise.set_value(v); return make_ready_future(); }); }); EXPECT_EQ(42, future.get()); } TYPED_TEST(FutureTest, shouldRunANoncopyableContinuationReturningVoid) { std::promise<int> value; auto future = value.get_future(); this->executor_->post([&value]() { make_ready_future(42).then( [promise{ std::move(value) }](const int& v) mutable { promise.set_value(v); }); }); EXPECT_EQ(42, future.get()); } // TODO: remove with ASYNCLY-45 TYPED_TEST(FutureTest, shouldUnpackReturnedFutureTupleForSubsequentContinuation) { const int a = 42; const int b = 23; std::promise<std::tuple<int, int>> tuplePromise; this->executor_->post([&]() { make_ready_future(std::make_tuple(a, b)).then([&tuplePromise](int first, int second) { tuplePromise.set_value(std::make_tuple(first, second)); }); }); EXPECT_EQ(std::make_tuple(a, b), tuplePromise.get_future().get()); } // TODO: remove with ASYNCLY-45 TYPED_TEST(FutureTest, shouldUnpackReturnedTupleForSubsequentContinuation) { const int a = 42; const int b = 23; std::promise<std::tuple<int, int>> tuplePromise; this->executor_->post([&]() { make_ready_future() .then([&]() { return std::make_tuple(a, b); }) .then([&tuplePromise](auto first, auto second) { tuplePromise.set_value(std::make_tuple(first, second)); }); }); EXPECT_EQ(std::make_tuple(a, b), tuplePromise.get_future().get()); } TYPED_TEST(FutureTest, shouldRunAChainedContinuationWithFutures) { std::promise<int> value1; std::promise<float> value2; this->executor_->post([&value1, &value2]() { make_ready_future(42) .then([&value1](int v) { value1.set_value(v); return make_ready_future(v / 2.0f); }) .then([&value2](float v) { value2.set_value(v); }); }); EXPECT_EQ(42, value1.get_future().get()); EXPECT_FLOAT_EQ(21.0, value2.get_future().get()); } TYPED_TEST(FutureTest, shouldRunAChainedContinuationWithValues) { //! [Future Chain] std::promise<int> value1; std::promise<float> value2; this->executor_->post([&value1, &value2]() { make_ready_future(42) .then([&value1](int v) { value1.set_value(v); return v / 2.0f; }) .then([&value2](float v) { value2.set_value(v); }); }); EXPECT_EQ(42, value1.get_future().get()); EXPECT_FLOAT_EQ(21.0, value2.get_future().get()); //! [Future Chain] } TYPED_TEST(FutureTest, shouldWorkWithLazyFutures) { //! [Lazy Future] std::promise<void> called; this->executor_->post([&called]() { auto lazy = make_lazy_future<void>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); future.then([&called]() { called.set_value(); }); promise.set_value(); }); called.get_future().wait(); //! [Lazy Future] } TYPED_TEST(FutureTest, shouldCreateReadyFuturesFromLValues) { std::promise<int> called; this->executor_->post([&called]() { auto v = 1; make_ready_future(v).then([&called](int value) { called.set_value(value); }); }); EXPECT_EQ(1, called.get_future().get()); } TYPED_TEST(FutureTest, shouldCreateReadyFuturesFromRValues) { std::promise<int> called; this->executor_->post([&called]() { auto v = 1; make_ready_future(std::move(v)).then([&called](int value) { called.set_value(value); }); }); EXPECT_EQ(1, called.get_future().get()); } TYPED_TEST(FutureTest, shouldResolvePromisesFromRValues) { std::promise<bool> called; this->executor_->post([&called]() { auto value = true; auto lazy = make_lazy_future<bool>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); future.then([&called](bool v) { called.set_value(v); }); promise.set_value(std::move(value)); }); EXPECT_EQ(true, called.get_future().get()); } TYPED_TEST(FutureTest, shouldResolvePromisesFromLValues) { std::promise<bool> called; this->executor_->post([&called]() { auto value = true; auto lazy = make_lazy_future<bool>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); future.then([&called](bool v) { called.set_value(v); }); promise.set_value(value); }); EXPECT_EQ(true, called.get_future().get()); } TYPED_TEST(FutureTest, shouldCallThenInTheRightExecutorContext) { std::promise<std::thread::id> executorThreadIdPromise; this->executor_->post([&executorThreadIdPromise]() { executorThreadIdPromise.set_value(std::this_thread::get_id()); }); auto executorThreadId = executorThreadIdPromise.get_future().get(); auto lazy = make_lazy_future<void>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); std::promise<std::thread::id> continuationThreadIdPromise; this->executor_->post([&future, &continuationThreadIdPromise]() { future.then([&continuationThreadIdPromise]() { continuationThreadIdPromise.set_value(std::this_thread::get_id()); }); }); promise.set_value(); EXPECT_EQ(executorThreadId, continuationThreadIdPromise.get_future().get()); } TYPED_TEST(FutureTest, shouldCatchExceptionalFuture) { //! [Make Exceptional Future] std::promise<void> exception; this->executor_->post([&exception]() { std::exception_ptr e; try { throw std::runtime_error("test error"); } catch (...) { e = std::current_exception(); } auto future = make_exceptional_future<int>(e); future.catch_error([&exception](std::exception_ptr ex) { exception.set_exception(ex); }); }); EXPECT_THROW(exception.get_future().get(), std::runtime_error); //! [Make Exceptional Future] } TYPED_TEST(FutureTest, shouldCatchErrorsWithoutAChain) { std::promise<void> exception; this->executor_->post([&exception]() { auto lazy = make_lazy_future<void>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); future.then([]() { throw std::runtime_error("intentional exception"); }) .catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); }); promise.set_value(); }); EXPECT_THROW(exception.get_future().get(), std::runtime_error); } TYPED_TEST(FutureTest, shouldCatchErrorsWithoutAChainAndNonCopyableHandler) { std::promise<void> exception; auto future = exception.get_future(); this->executor_->post([exception{ std::move(exception) }]() mutable { auto lazy = make_lazy_future<void>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); future.then([]() { throw std::runtime_error("intentional exception"); }) .catch_error([exception{ std::move(exception) }](std::exception_ptr e) mutable { exception.set_exception(e); }); promise.set_value(); }); EXPECT_THROW(future.get(), std::runtime_error); } TYPED_TEST(FutureTest, shouldCatchErrorsInAChain) { std::promise<void> exception; bool shouldNeverBeTrue = false; this->executor_->post([&exception, &shouldNeverBeTrue]() { auto lazy = make_lazy_future<void>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); future.then([]() -> Future<void> { throw std::runtime_error("intentional exception"); }) .then([&shouldNeverBeTrue]() { shouldNeverBeTrue = true; }) .catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); }); promise.set_value(); }); EXPECT_THROW(exception.get_future().get(), std::runtime_error); EXPECT_FALSE(shouldNeverBeTrue); } TYPED_TEST(FutureTest, shouldMakeExceptionalFutureFromStdException) { std::promise<void> exception; this->executor_->post([&exception]() { make_exceptional_future<void>(std::logic_error{ "intentional exception" }) .catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); }); }); EXPECT_THROW(exception.get_future().get(), std::logic_error); } TYPED_TEST(FutureTest, shouldMakeExceptionalFutureFromStdString) { std::promise<void> exception; this->executor_->post([&exception]() { make_exceptional_future<void>(std::string{ "intentional exception" }) .catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); }); }); EXPECT_THROW(exception.get_future().get(), std::runtime_error); } TYPED_TEST(FutureTest, shouldMakeExceptionalFutureFromZeroTerminatedString) { std::promise<void> exception; this->executor_->post([&exception]() { make_exceptional_future<void>("intentional exception") .catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); }); }); EXPECT_THROW(exception.get_future().get(), std::runtime_error); } TYPED_TEST(FutureTest, shouldAllowForLazyExecptionsFromStdExceptionPtr) { std::promise<void> exception; this->executor_->post([&exception]() { auto lazy = make_lazy_future<void>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); future.catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); }); promise.set_exception(std::make_exception_ptr(std::logic_error{ "logic_error" })); }); EXPECT_THROW(exception.get_future().get(), std::logic_error); } TYPED_TEST(FutureTest, shouldAllowForLazyExecptionsFromStdException) { std::promise<void> exception; this->executor_->post([&exception]() { auto lazy = make_lazy_future<void>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); future.catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); }); promise.set_exception(std::logic_error{ "logic_error" }); }); EXPECT_THROW(exception.get_future().get(), std::logic_error); } TYPED_TEST(FutureTest, shouldAllowForLazyExecptionsFromStdString) { std::promise<void> exception; this->executor_->post([&exception]() { auto lazy = make_lazy_future<void>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); future.catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); }); promise.set_exception(std::string{ "logic_error" }); }); EXPECT_THROW(exception.get_future().get(), std::runtime_error); } TYPED_TEST(FutureTest, shouldAllowForLazyExecptionsFromCharPtr) { std::promise<void> exception; this->executor_->post([&exception]() { auto lazy = make_lazy_future<void>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); future.catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); }); promise.set_exception("logic_error"); }); EXPECT_THROW(exception.get_future().get(), std::runtime_error); } TYPED_TEST(FutureTest, shouldHandleLazyUserErrors) { std::promise<void> exception; this->executor_->post([&exception]() { std::exception_ptr e; try { throw std::runtime_error("test error"); } catch (...) { e = std::current_exception(); } make_ready_future() .then([e]() { return make_exceptional_future<int>(e); }) .catch_error([&exception](std::exception_ptr ex) { exception.set_exception(ex); }); }); EXPECT_THROW(exception.get_future().get(), std::runtime_error); } TYPED_TEST(FutureTest, shouldForwardValuesThroughCatch) { std::promise<int> propagated_value; this->executor_->post([&propagated_value]() { make_ready_future() .then([]() { return 5; }) .catch_error([](std::exception_ptr) {}) .then([&propagated_value](int value) { propagated_value.set_value(value); }); }); EXPECT_EQ(5, propagated_value.get_future().get()); } TYPED_TEST(FutureTest, shouldChooseTheRightErrorHandler) { //! [Error Chain] struct WrongException : std::exception { }; struct CorrectException : std::exception { }; std::promise<void> exception_container; this->executor_->post([&exception_container]() { make_ready_future() .then([]() { return 5; }) .catch_error([&exception_container](std::exception_ptr) { std::exception_ptr e; try { throw WrongException{}; } catch (...) { e = std::current_exception(); } exception_container.set_exception(e); }) .then([](int) -> Future<int> { throw CorrectException{}; }) .catch_error([&exception_container](std::exception_ptr e) { exception_container.set_exception(e); }) .then([](int value) { return value; }) .catch_error([&exception_container](std::exception_ptr) { std::exception_ptr e; try { throw WrongException{}; } catch (...) { e = std::current_exception(); } exception_container.set_exception(e); }); }); EXPECT_THROW(exception_container.get_future().get(), CorrectException); //! [Error Chain] } TYPED_TEST(FutureTest, shouldChooseTheRightErrorHandlerOnExceptionalFuture) { struct WrongException : std::exception { }; struct CorrectException : std::exception { }; std::promise<void> exception_container; this->executor_->post([&exception_container]() { make_exceptional_future<int>(CorrectException{}) .then([](int i) { return i; }) .catch_error([&exception_container](std::exception_ptr e) { exception_container.set_exception(e); }) .then([](int value) { return value; }) .catch_error([&exception_container](std::exception_ptr) { std::exception_ptr e; try { throw WrongException{}; } catch (...) { e = std::current_exception(); } exception_container.set_exception(e); }); }); EXPECT_THROW(exception_container.get_future().get(), CorrectException); } TYPED_TEST(FutureTest, shouldCatchAndForwardError) { struct CorrectException : std::exception { }; std::promise<void> exception1_container; std::promise<void> exception2_container; this->executor_->post([&exception1_container, &exception2_container]() { // Use case: handle error internally within a function but also externally on the caller // side. // Setup: // `auto foo() {return future.catch_and_forward_error(internal_error_handler);}` // `foo().then(continuation).catch_error(external_error_handler);` // Both error handlers (`internal_error_handler` and `external_error_handler`) should get // called. make_exceptional_future<int>(CorrectException{}) .then([](int i) { return i; }) .catch_and_forward_error([&exception1_container](std::exception_ptr e) { exception1_container.set_exception(e); }) .then([](int value) { return value; }) .catch_error([&exception2_container](std::exception_ptr e) { exception2_container.set_exception(e); }); }); EXPECT_THROW(exception1_container.get_future().get(), CorrectException); EXPECT_THROW(exception2_container.get_future().get(), CorrectException); } TYPED_TEST(FutureTest, shouldWorkWithFutureProxies) { auto callerExecutorControl = ThreadPoolExecutorController::create(1); auto callerExecutor = callerExecutorControl->get_executor(); auto calleeExecutorControl = ThreadPoolExecutorController::create(1); auto calleeExecutor = calleeExecutorControl->get_executor(); struct Interface { virtual ~Interface() = default; virtual Future<int> op() = 0; }; struct Implementation : public Interface { Future<int> op() override { return make_ready_future(42); } }; struct Proxy : public Interface { Proxy( const std::shared_ptr<IExecutor>& executor, const std::shared_ptr<Interface>& implementation) : executor_(executor) , implementation_(implementation) { } Future<int> op() override { auto lazy = make_lazy_future<int>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); auto callerExecutor = this_thread::get_current_executor(); auto p = implementation_; executor_->post([p, promise, callerExecutor]() mutable { p->op().then([callerExecutor, promise](int value) mutable { callerExecutor->post( [promise, value]() mutable { promise.set_value(std::move(value)); }); }); }); return future; } const std::shared_ptr<IExecutor> executor_; const std::shared_ptr<Interface> implementation_; }; auto implementation = std::make_shared<Implementation>(); auto proxy = std::make_shared<Proxy>(calleeExecutor, implementation); std::promise<int> valuePromise; callerExecutor->post([proxy, &valuePromise]() { proxy->op().then([&valuePromise](int value) { valuePromise.set_value(value); }); }); EXPECT_EQ(42, valuePromise.get_future().get()); } TYPED_TEST(FutureTest, shouldThrowWhenOverwritingValueContinuations) { std::promise<void> exceptionThrown; this->executor_->post([&exceptionThrown]() { auto lazy = make_lazy_future<int>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); future.then([](int) {}); try { future.then([](int) {}); } catch (...) { exceptionThrown.set_exception(std::current_exception()); } }); ASSERT_THROW(exceptionThrown.get_future().get(), std::runtime_error); } TYPED_TEST(FutureTest, shouldThrowWhenOverwritingValueContinuationsEvenWhenResolved) { std::promise<void> exceptionThrown; this->executor_->post([&exceptionThrown]() { auto lazy = make_lazy_future<int>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); future.then([](int) {}); promise.set_value(42); try { future.then([](int) {}); } catch (...) { exceptionThrown.set_exception(std::current_exception()); } }); ASSERT_THROW(exceptionThrown.get_future().get(), std::runtime_error); } TYPED_TEST(FutureTest, shouldThrowWhenOverwritingErrorContinuations) { std::promise<void> exceptionThrown; this->executor_->post([&exceptionThrown]() { auto lazy = make_lazy_future<int>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); future.catch_error([](std::exception_ptr) {}); try { future.catch_error([](std::exception_ptr) {}); } catch (...) { exceptionThrown.set_exception(std::current_exception()); } }); ASSERT_THROW(exceptionThrown.get_future().get(), std::runtime_error); } TYPED_TEST(FutureTest, shouldThrowWhenOverwritingErrorContinuationsEvenWhenRejected) { std::promise<void> exceptionThrown; this->executor_->post([&exceptionThrown]() { auto lazy = make_lazy_future<int>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); future.catch_error([](std::exception_ptr) {}); promise.set_exception("intentional error"); try { future.catch_error([](std::exception_ptr) {}); } catch (...) { exceptionThrown.set_exception(std::current_exception()); } }); ASSERT_THROW(exceptionThrown.get_future().get(), std::runtime_error); } TYPED_TEST(FutureTest, shouldPropagateMoveOnlyValues) { std::promise<std::unique_ptr<int>> propagatedValue; this->executor_->post([&propagatedValue]() { auto contained = new int(42); auto value = std::unique_ptr<int>{ contained }; make_ready_future<std::unique_ptr<int>>(std::move(value)) .then([&propagatedValue](std::unique_ptr<int> v) { propagatedValue.set_value(std::move(v)); }); }); EXPECT_EQ(42, *propagatedValue.get_future().get()); } TYPED_TEST(FutureTest, shouldThrowWhenSettingValueTwice) { std::promise<void> shouldThrow; this->executor_->post([&shouldThrow]() { auto lazy = make_lazy_future<int>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); promise.set_value(5); try { promise.set_value(5); } catch (...) { shouldThrow.set_exception(std::current_exception()); } }); EXPECT_THROW(shouldThrow.get_future().get(), std::runtime_error); } TYPED_TEST(FutureTest, shouldThrowWhenSettingErrorsTwice) { std::promise<void> shouldThrow; this->executor_->post([&shouldThrow]() { auto lazy = make_lazy_future<int>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); std::exception_ptr e; try { throw std::runtime_error("some error"); } catch (...) { e = std::current_exception(); } promise.set_exception(e); try { promise.set_exception(e); } catch (...) { shouldThrow.set_exception(std::current_exception()); } }); EXPECT_THROW(shouldThrow.get_future().get(), std::runtime_error); } TYPED_TEST(FutureTest, shouldThrowWhenSettingErrorAfterValue) { std::promise<void> shouldThrow; this->executor_->post([&shouldThrow]() { auto lazy = make_lazy_future<int>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); std::exception_ptr e; try { throw std::runtime_error("some error"); } catch (...) { e = std::current_exception(); } promise.set_value(5); try { promise.set_exception(e); } catch (...) { shouldThrow.set_exception(std::current_exception()); } }); EXPECT_THROW(shouldThrow.get_future().get(), std::runtime_error); } TYPED_TEST(FutureTest, shouldThrowWhenSettingValueAfterError) { std::promise<void> shouldThrow; this->executor_->post([&shouldThrow]() { auto lazy = make_lazy_future<int>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); std::exception_ptr e; try { throw std::runtime_error("some error"); } catch (...) { e = std::current_exception(); } promise.set_exception(e); try { promise.set_value(5); } catch (...) { shouldThrow.set_exception(std::current_exception()); } }); EXPECT_THROW(shouldThrow.get_future().get(), std::runtime_error); } TYPED_TEST(FutureTest, shouldDeleteTheContinuationWhenTheErrorHandlerHasBeenExecuted) { std::promise<void> result; auto i = std::make_shared<int>(42); EXPECT_EQ(1, i.use_count()); auto lazy = make_lazy_future<void>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); this->executor_->post([&future, &promise, &i, &result]() { future.catch_error([&result](std::exception_ptr ex) mutable { result.set_exception(ex); }) .then([i]() {}); EXPECT_EQ(2, i.use_count()); promise.set_exception("failure"); }); EXPECT_THROW(result.get_future().get(), std::runtime_error); EXPECT_EQ(1, i.use_count()); } TYPED_TEST(FutureTest, shouldDeleteTheErrorHandlerWhenTheContinuationHasBeenExecuted) { std::promise<void> result; auto i = std::make_shared<int>(42); EXPECT_EQ(1, i.use_count()); auto lazy = make_lazy_future<void>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); this->executor_->post([&future, &promise, &i, &result]() { future.catch_error([i](auto) {}).then([&result]() mutable { result.set_value(); }); EXPECT_EQ(2, i.use_count()); promise.set_value(); }); result.get_future().get(); EXPECT_EQ(1, i.use_count()); } TYPED_TEST(FutureTest, shouldDeleteTheContinuationWhenTheChainedErrorHandlerHasBeenExecuted) { std::promise<void> result; auto i = std::make_shared<int>(42); EXPECT_EQ(1, i.use_count()); auto lazy = make_lazy_future<void>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); this->executor_->post([&future, &promise, &i, &result]() { future.then([i]() {}).catch_error( [&result](std::exception_ptr ex) mutable { result.set_exception(ex); }); EXPECT_EQ(2, i.use_count()); promise.set_exception("failure"); }); EXPECT_THROW(result.get_future().get(), std::runtime_error); EXPECT_EQ(1, i.use_count()); } TYPED_TEST(FutureTest, shouldDeleteTheContinuationWhenThereIsNoErrorHandlerButTheFutureIsRejected) { std::promise<void> result; auto i = std::make_shared<int>(42); EXPECT_EQ(1, i.use_count()); auto lazy = make_lazy_future<void>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); this->executor_->post([&future, &promise, &i, &result]() { future.then([i]() {}); EXPECT_EQ(2, i.use_count()); promise.set_exception("failure"); EXPECT_EQ(1, i.use_count()); result.set_value(); }); result.get_future().get(); EXPECT_EQ(1, i.use_count()); } TYPED_TEST(FutureTest, shouldDeleteTheErrorHandlerWhenThereIsNoContinuationButTheFutureIsResolved) { std::promise<void> result; auto i = std::make_shared<int>(42); EXPECT_EQ(1, i.use_count()); auto lazy = make_lazy_future<void>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); this->executor_->post([&future, &promise, &i, &result]() { future.catch_error([i](auto) {}); EXPECT_EQ(2, i.use_count()); promise.set_value(); EXPECT_EQ(1, i.use_count()); result.set_value(); }); result.get_future().get(); } TYPED_TEST(FutureTest, shouldThrowWhenSchedulingContinuationsFromNonExecutorContext) { auto future = make_ready_future<int>(42); EXPECT_THROW(future.then([](int) {}), std::runtime_error); } // Future<T>::then(T -> Future<void>) -> Future<void> TYPED_TEST(FutureTest, shouldSupport_ValueFuture_ValueContinuations_ReturningVoidFutures) { std::promise<void> called; this->executor_->post([&called]() { make_ready_future<int>(42).then([&called](int) { called.set_value(); return make_ready_future(); }); }); EXPECT_NO_THROW(called.get_future().get()); } TYPED_TEST( FutureTest, shouldSupport_ValueFuture_ValueContinuations_ReturningVoidFutures_WithContinuationErrors) { std::promise<void> called; struct test_error : public std::exception { }; this->executor_->post([&called]() { make_ready_future<int>(42) .then([](int) -> Future<void> { throw test_error{}; }) .catch_error([&called](std::exception_ptr e) { called.set_exception(e); }); }); EXPECT_THROW(called.get_future().get(), test_error); } TYPED_TEST( FutureTest, shouldSupport_ValueFuture_ValueContinuations_ReturningVoidFutures_WithExceptionalFutures) { std::promise<void> called; struct test_error : public std::exception { }; this->executor_->post([&called]() { make_ready_future<int>(42) .then([](int) { std::exception_ptr e; try { throw test_error{}; } catch (...) { e = std::current_exception(); } return make_exceptional_future<void>(e); }) .catch_error([&called](std::exception_ptr e) { called.set_exception(e); }); }); EXPECT_THROW(called.get_future().get(), test_error); } // Future<void>::then(void -> Future<void>) -> Future<void> TYPED_TEST(FutureTest, shouldSupport_VoidFuture_ValueContinuations_ReturningVoidFutures) { std::promise<void> called; this->executor_->post([&called]() { make_ready_future().then([&called]() { called.set_value(); return make_ready_future(); }); }); EXPECT_NO_THROW(called.get_future().get()); } TYPED_TEST( FutureTest, shouldSupport_VoidFuture_ValueContinuations_ReturningVoidFutures_WithContinuationErrors) { std::promise<void> called; struct test_error : public std::exception { }; this->executor_->post([&called]() { make_ready_future() .then([]() -> Future<void> { throw test_error{}; }) .catch_error([&called](std::exception_ptr e) { called.set_exception(e); }); }); EXPECT_THROW(called.get_future().get(), test_error); } TYPED_TEST( FutureTest, shouldSupport_VoidFuture_ValueContinuations_ReturningVoidFutures_WithExceptionalFutures) { std::promise<void> called; struct test_error : public std::exception { }; this->executor_->post([&called]() { make_ready_future() .then([]() { std::exception_ptr e; try { throw test_error{}; } catch (...) { e = std::current_exception(); } return make_exceptional_future<void>(e); }) .catch_error([&called](std::exception_ptr e) { called.set_exception(e); }); }); EXPECT_THROW(called.get_future().get(), test_error); } // Future<T>::then(T -> Future<U>) -> Future<U> TYPED_TEST(FutureTest, shouldSupport_ValueFuture_ValueContinuations_ReturningValueFutures) { std::promise<bool> called; this->executor_->post([&called]() { make_ready_future<int>(42) .then([](int) { return make_ready_future(true); }) .then([&called](bool value) { called.set_value(value); }); }); EXPECT_EQ(true, called.get_future().get()); } TYPED_TEST( FutureTest, shouldSupport_ValueFuture_ValueContinuations_ReturningValueFutures_WithContinuationErrors) { std::promise<bool> called; struct test_error : public std::exception { }; this->executor_->post([&called]() { make_ready_future<int>(42) .then([](int) -> Future<bool> { throw test_error{}; }) .catch_error([&called](std::exception_ptr e) { called.set_exception(e); }) .then([&called](bool value) { called.set_value(value); }); }); EXPECT_THROW(called.get_future().get(), test_error); } TYPED_TEST( FutureTest, shouldSupport_ValueFuture_ValueContinuations_ReturningValueFutures_WithExceptionalFutures) { std::promise<bool> called; struct test_error : public std::exception { }; this->executor_->post([&called]() { make_ready_future<int>(42) .then([](int) { std::exception_ptr e; try { throw test_error{}; } catch (...) { e = std::current_exception(); } return make_exceptional_future<bool>(e); }) .catch_error([&called](std::exception_ptr e) { called.set_exception(e); }) .then([&called](bool value) { called.set_value(value); }); }); EXPECT_THROW(called.get_future().get(), test_error); } // Future<void>::then(void -> Future<U>) -> Future<U> TYPED_TEST(FutureTest, shouldSupport_VoidFuture_ValueContinuations_ReturningValueFutures) { std::promise<bool> called; this->executor_->post([&called]() { make_ready_future() .then([]() { return make_ready_future(true); }) .then([&called](bool value) { called.set_value(value); }); }); EXPECT_EQ(true, called.get_future().get()); } TYPED_TEST( FutureTest, shouldSupport_VoidFuture_ValueContinuations_ReturningValueFutures_WithContinuationErrors) { std::promise<bool> called; struct test_error : public std::exception { }; this->executor_->post([&called]() { make_ready_future() .then([]() -> Future<bool> { throw test_error{}; }) .catch_error([&called](std::exception_ptr e) { called.set_exception(e); }) .then([&called](bool value) { called.set_value(value); }); }); EXPECT_THROW(called.get_future().get(), test_error); } TYPED_TEST( FutureTest, shouldSupport_VoidFuture_ValueContinuations_ReturningValueFutures_WithExceptionalFutures) { std::promise<bool> called; struct test_error : public std::exception { }; this->executor_->post([&called]() { make_ready_future() .then([]() { std::exception_ptr e; try { throw test_error{}; } catch (...) { e = std::current_exception(); } return make_exceptional_future<bool>(e); }) .catch_error([&called](std::exception_ptr e) { called.set_exception(e); }) .then([&called](bool value) { called.set_value(value); }); }); EXPECT_THROW(called.get_future().get(), test_error); } // Future<T>::then(T -> void) -> Future<void> TYPED_TEST(FutureTest, shouldSupport_ValueFuture_ValueContinuations_ReturningVoid) { std::promise<void> called; this->executor_->post([&called]() { make_ready_future<int>(42).then([](int) {}).then([&called]() { called.set_value(); }); }); EXPECT_NO_THROW(called.get_future().get()); } TYPED_TEST( FutureTest, shouldSupport_ValueFuture_ValueContinuations_ReturningVoid_WithContinuationErrors) { std::promise<void> called; struct test_error : public std::exception { }; this->executor_->post([&called]() { make_ready_future<int>(42) .then([](int) { throw test_error{}; }) .catch_error([&called](std::exception_ptr e) { called.set_exception(e); }) .then([&called]() { called.set_value(); }); }); EXPECT_THROW(called.get_future().get(), test_error); } TYPED_TEST(FutureTest, shouldSupport_ValueFuture_ConstLValueValueContinuations_ReturningVoid) { std::promise<int> called; const auto lambda = [&called](int v) { called.set_value(v); }; this->executor_->post([&lambda]() { make_ready_future(42).then(lambda); }); EXPECT_EQ(42, called.get_future().get()); } TYPED_TEST(FutureTest, shouldSupport_ValueFuture_NonConstLValueValueContinuations_ReturningVoid) { std::promise<int> called; auto lambda = [&called](int v) mutable { called.set_value(v); }; this->executor_->post([&lambda]() { make_ready_future(42).then(lambda); }); EXPECT_EQ(42, called.get_future().get()); } // Future<void>::then(void -> void) -> Future<void> TYPED_TEST(FutureTest, shouldSupport_VoidFuture_VoidContinuations_ReturningVoid) { std::promise<void> called; this->executor_->post([&called]() { make_ready_future().then([]() {}).then([&called]() { called.set_value(); }); }); EXPECT_NO_THROW(called.get_future().get()); } TYPED_TEST( FutureTest, shouldSupport_VoidFuture_VoidContinuations_ReturningVoid_WithContinuationErrors) { std::promise<void> called; struct test_error : public std::exception { }; this->executor_->post([&called]() { make_ready_future() .then([]() -> Future<void> { throw test_error{}; }) .catch_error([&called](std::exception_ptr e) { called.set_exception(e); }) .then([&called]() { called.set_value(); }); }); EXPECT_THROW(called.get_future().get(), test_error); } TYPED_TEST(FutureTest, shouldSupport_VoidFuture_ConstLValueVoidContinuations_ReturningVoid) { std::promise<void> called; const auto lambda = [&called]() { called.set_value(); }; this->executor_->post([&lambda]() { make_ready_future().then(lambda); }); EXPECT_NO_THROW(called.get_future().get()); } TYPED_TEST(FutureTest, shouldSupport_VoidFuture_NonConstLValueVoidContinuations_ReturningVoid) { std::promise<void> called; auto lambda = [&called]() mutable { called.set_value(); }; this->executor_->post([&lambda]() { make_ready_future().then(lambda); }); EXPECT_NO_THROW(called.get_future().get()); } // Future<T>::then(T -> U) -> Future<U> TYPED_TEST(FutureTest, shouldSupport_ValueFuture_ValueContinuations_ReturningValues) { std::promise<bool> called; this->executor_->post([&called]() { make_ready_future<int>(42).then([](int) { return true; }).then([&called](bool value) { called.set_value(value); }); }); EXPECT_EQ(true, called.get_future().get()); } TYPED_TEST( FutureTest, shouldSupport_ValueFuture_ValueContinuations_ReturningValues_WithContinuationErrors) { std::promise<bool> called; struct test_error : public std::exception { }; this->executor_->post([&called]() { make_ready_future<int>(42) .then([](int) -> Future<bool> { throw test_error{}; }) .catch_error([&called](std::exception_ptr e) { called.set_exception(e); }) .then([&called](bool value) { called.set_value(value); }); }); EXPECT_THROW(called.get_future().get(), test_error); } // Future<void>::then(void -> U) -> Future<U> TYPED_TEST(FutureTest, shouldSupport_VoidFuture_ValueContinuations_ReturningValues) { std::promise<bool> called; this->executor_->post([&called]() { make_ready_future().then([]() { return true; }).then([&called](bool value) { called.set_value(value); }); }); EXPECT_EQ(true, called.get_future().get()); } TYPED_TEST( FutureTest, shouldSupport_VoidFuture_ValueContinuations_ReturningValues_WithContinuationErrors) { std::promise<bool> called; struct test_error : public std::exception { }; this->executor_->post([&called]() { make_ready_future() .then([]() -> Future<bool> { throw test_error{}; }) .catch_error([&called](std::exception_ptr e) { called.set_exception(e); }) .then([&called](bool value) { called.set_value(value); }); }); EXPECT_THROW(called.get_future().get(), test_error); } TYPED_TEST(FutureTest, shouldSupportResolvingPromisesWithLValues) { std::promise<int> called; auto value = 5; this->executor_->post([&called, &value]() { auto lazy = make_lazy_future<int>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); future.then([&called](int v) { called.set_value(v); }); promise.set_value(value); }); EXPECT_EQ(called.get_future().get(), value); } TYPED_TEST(FutureTest, shouldSupportLValuesForMakeReadyFuture) { std::promise<int> called; auto value = 5; this->executor_->post([&called, &value]() { auto future = make_ready_future<int>(value); future.then([&called](int v) { called.set_value(v); }); }); EXPECT_EQ(called.get_future().get(), value); } TYPED_TEST(FutureTest, thenShouldHoldExecutorReference) { std::promise<void> thenCalled; auto lazy = make_lazy_future<void>(); auto future = std::get<0>(lazy); auto promise = std::get<1>(lazy); this->executor_->post([&thenCalled, &future]() { future.then([]() {}); thenCalled.set_value(); }); thenCalled.get_future().wait(); // there is no guarantee here that the posted lambda has been executed completely, // so wait for a small amount of time, // we can't use termination_awaiter here cause in the successful case it would block // (future should still keep a reference, stored by future.then()) std::this_thread::sleep_for(std::chrono::milliseconds(50)); this->factory_.reset(); this->executor_.reset(); try { promise.set_value(); // this is going to crash if the executor isn't held by the future // (then()) } catch (const std::runtime_error&) { // this is going to throw because the executor is already // stopped, TODO: check if this is correct behavior } } /// FutureThrowingExecutorTest provides test cases that ensure futures behave correctly in case /// underlying executors encounter runtime errors that prevent them to execute tasks that futures /// schedule on them. template <typename E> class FutureThrowingExecutorTestBase : public Test { public: FutureThrowingExecutorTestBase(std::tuple<asyncly::Future<void>, asyncly::Promise<void>> lazy) : promise_(std::get<1>(lazy)) , future_(std::get<0>(lazy)) , throwingExecutor_(asyncly::detail::ThrowingExecutor<E>::create()) , currentExecutorGuard_(throwingExecutor_) { } FutureThrowingExecutorTestBase() : FutureThrowingExecutorTestBase(make_lazy_future<void>()) { } asyncly::Promise<void> promise_; asyncly::Future<void> future_; const std::shared_ptr<asyncly::detail::ThrowingExecutor<E>> throwingExecutor_; const asyncly::test::CurrentExecutorGuard currentExecutorGuard_; }; class FutureThrowingExecutorRuntimeErrorTest : public FutureThrowingExecutorTestBase<std::runtime_error> { }; TEST_F(FutureThrowingExecutorRuntimeErrorTest, throws_on_late_then) { promise_.set_value(); EXPECT_ANY_THROW(future_.then([]() { ADD_FAILURE(); })); } TEST_F(FutureThrowingExecutorRuntimeErrorTest, throws_on_late_set_value) { future_.then([]() { ADD_FAILURE(); }); EXPECT_ANY_THROW(promise_.set_value()); } TEST_F(FutureThrowingExecutorRuntimeErrorTest, throws_on_late_catch_error) { promise_.set_exception("intentional error"); EXPECT_ANY_THROW(future_.catch_error([](auto) { ADD_FAILURE(); })); } TEST_F(FutureThrowingExecutorRuntimeErrorTest, throws_on_late_set_exception) { future_.catch_error([](auto) { ADD_FAILURE(); }); EXPECT_ANY_THROW(promise_.set_exception("intentional error")); } class FutureThrowingExecutorExecutorStoppedExceptionTest : public FutureThrowingExecutorTestBase<ExecutorStoppedException> { }; TEST_F(FutureThrowingExecutorExecutorStoppedExceptionTest, throws_on_late_then) { promise_.set_value(); EXPECT_ANY_THROW(future_.then([]() { ADD_FAILURE(); })); } TEST_F( FutureThrowingExecutorExecutorStoppedExceptionTest, catches_executor_post_exception_on_late_set_value) { future_.then([]() { ADD_FAILURE(); }); promise_.set_value(); } TEST_F(FutureThrowingExecutorExecutorStoppedExceptionTest, throws_on_late_catch_error) { promise_.set_exception("intentional error"); EXPECT_ANY_THROW(future_.catch_error([](auto) { ADD_FAILURE(); })); } TEST_F( FutureThrowingExecutorExecutorStoppedExceptionTest, catches_executor_post_exception_on_late_set_exception) { future_.catch_error([](auto) { ADD_FAILURE(); }); promise_.set_exception("intentional error"); } }
30.698803
100
0.631067
erikzenker
982537b9da42cfe4184a27d5b1f3deb91abdcd1e
12,950
cpp
C++
MainWindow.cpp
azonenberg/sump-monitor
74d44823990f4ad84fca32e8ddf47b96f5e5ee5c
[ "BSD-3-Clause" ]
null
null
null
MainWindow.cpp
azonenberg/sump-monitor
74d44823990f4ad84fca32e8ddf47b96f5e5ee5c
[ "BSD-3-Clause" ]
null
null
null
MainWindow.cpp
azonenberg/sump-monitor
74d44823990f4ad84fca32e8ddf47b96f5e5ee5c
[ "BSD-3-Clause" ]
null
null
null
/*********************************************************************************************************************** * * * SUMP MONITOR v0.1 * * * * Copyright (c) 2020 Andrew D. Zonenberg * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * * following conditions are met: * * * * * Redistributions of source code must retain the above copyright notice, this list of conditions, and the * * following disclaimer. * * * * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * * following disclaimer in the documentation and/or other materials provided with the distribution. * * * * * Neither the name of the author nor the names of any contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * * THE AUTHORS BE HELD 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. * * * ***********************************************************************************************************************/ /** @file @author Andrew D. Zonenberg @brief Implementation of main application window class */ #include "sumpmon.h" #include "MainWindow.h" using namespace std; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Construction / destruction /** @brief Initializes the main window */ MainWindow::MainWindow() : m_depthGraph(500) , m_volumeGraph(500) , m_flowGraph(500) , m_alarming(false) { set_title("Sump Monitor"); //Initial setup set_reallocate_redraws(true); //Add widgets CreateWidgets(); //Run the HMI in fullscreen mode fullscreen(); //Set the update timer sigc::slot<bool> slot = sigc::bind(sigc::mem_fun(*this, &MainWindow::OnTimer), 1); sigc::connection conn = Glib::signal_timeout().connect(slot, 1000); } /** @brief Application cleanup */ MainWindow::~MainWindow() { } /** @brief Helper function for creating widgets and setting up signal handlers */ void MainWindow::CreateWidgets() { m_tabs.override_font(Pango::FontDescription("sans bold 20")); string font = "sans bold 14"; //Set up window hierarchy add(m_tabs); m_tabs.append_page(m_summaryTab, "Summary"); m_summaryTab.pack_start(m_depthBox, Gtk::PACK_SHRINK); m_depthBox.pack_start(m_depthCaptionLabel, Gtk::PACK_SHRINK); m_depthCaptionLabel.override_font(Pango::FontDescription("sans bold 20")); m_depthCaptionLabel.set_label("Depth: "); m_depthCaptionLabel.set_size_request(125, 1); m_depthBox.pack_start(m_depthLabel, Gtk::PACK_SHRINK); m_depthLabel.override_font(Pango::FontDescription("sans bold 20")); m_summaryTab.pack_start(m_volumeBox, Gtk::PACK_SHRINK); m_volumeBox.pack_start(m_volumeCaptionLabel, Gtk::PACK_SHRINK); m_volumeCaptionLabel.override_font(Pango::FontDescription("sans bold 20")); m_volumeCaptionLabel.set_label("Volume: "); m_volumeCaptionLabel.set_size_request(125, 1); m_volumeBox.pack_start(m_volumeLabel, Gtk::PACK_SHRINK); m_volumeLabel.override_font(Pango::FontDescription("sans bold 20")); m_summaryTab.pack_start(m_flowBox, Gtk::PACK_SHRINK); m_flowBox.pack_start(m_flowCaptionLabel, Gtk::PACK_SHRINK); m_flowCaptionLabel.override_font(Pango::FontDescription("sans bold 20")); m_flowCaptionLabel.set_label("Flow: "); m_flowCaptionLabel.set_size_request(125, 1); m_flowBox.pack_start(m_flowLabel, Gtk::PACK_SHRINK); m_flowLabel.override_font(Pango::FontDescription("sans bold 20")); m_summaryTab.pack_start(m_silenceAlarmButton, Gtk::PACK_SHRINK); m_silenceAlarmButton.set_label("Silence alarm"); m_silenceAlarmButton.signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::SilenceAlarm)); m_summaryTab.pack_start(m_trendFrame, Gtk::PACK_EXPAND_WIDGET); m_trendFrame.set_label("Weekly Flow Trend"); m_trendFrame.add(m_trendGraph); m_trendGraph.m_units = "L/hr"; m_trendGraph.m_minScale = 0; m_trendGraph.m_maxScale = 50; m_trendGraph.m_scaleBump = 5; m_trendGraph.m_maxRedline = 45; m_trendGraph.m_series.push_back(&m_trendData); m_trendGraph.m_seriesName = "flow"; m_trendGraph.m_timeScale = 0.001; m_trendGraph.m_timeTick = 86400; m_trendGraph.m_lineWidth = 3; m_trendGraph.m_drawLegend = false; m_trendData.m_color = Gdk::Color("#0000ff"); m_trendGraph.m_font = Pango::FontDescription(font); m_tabs.append_page(m_depthTab, "Depth"); m_depthTab.add(m_depthGraph); m_depthGraph.m_units = "mm"; m_depthGraph.m_minScale = 100; m_depthGraph.m_maxScale = 225; m_depthGraph.m_scaleBump = 25; m_depthGraph.m_maxRedline = 200; m_depthGraph.m_series.push_back(&m_depthData); m_depthGraph.m_seriesName = "depth"; m_depthGraph.m_timeScale = 0.15; m_depthGraph.m_timeTick = 600; m_depthGraph.m_lineWidth = 3; m_depthGraph.m_drawLegend = false; m_depthData.m_color = Gdk::Color("#0000ff"); m_depthGraph.m_font = Pango::FontDescription(font); m_tabs.append_page(m_volumeTab, "Volume"); m_volumeTab.add(m_volumeGraph); m_volumeGraph.m_units = "L"; m_volumeGraph.m_minScale = 14; m_volumeGraph.m_maxScale = 30; m_volumeGraph.m_scaleBump = 2; m_volumeGraph.m_maxRedline = 28; m_volumeGraph.m_series.push_back(&m_volumeData); m_volumeGraph.m_seriesName = "volume"; m_volumeGraph.m_timeScale = 0.15; m_volumeGraph.m_timeTick = 600; m_volumeGraph.m_lineWidth = 3; m_volumeGraph.m_drawLegend = false; m_volumeData.m_color = Gdk::Color("#0000ff"); m_volumeGraph.m_font = Pango::FontDescription(font); m_tabs.append_page(m_inflowTab, "Flow"); m_inflowTab.add(m_flowGraph); m_flowGraph.m_units = "L/hr"; m_flowGraph.m_minScale = 0; m_flowGraph.m_maxScale = 50; m_flowGraph.m_scaleBump = 5; m_flowGraph.m_maxRedline = 45; m_flowGraph.m_series.push_back(&m_flowData); m_flowGraph.m_seriesName = "flow"; m_flowGraph.m_timeScale = 0.075; m_flowGraph.m_timeTick = 1200; m_flowGraph.m_lineWidth = 3; m_flowGraph.m_drawLegend = false; m_flowData.m_color = Gdk::Color("#0000ff"); m_flowGraph.m_font = Pango::FontDescription(font); m_tabs.append_page(m_dutyTab, "Duty %"); //Done adding widgets show_all(); } //////////////////////////////////////////////////////////////////////////////////////////////////// // Message handlers bool MainWindow::OnTimer(int /*timer*/) { //Before we do anything else, check if any of the floor sensors are leaking and ring the alarm. if(g_leakReading > 10) { if(!m_alarming) AlarmOn(); } //Clear alarms if no trouble conditions else if(m_alarming) AlarmOff(); double t = g_timeOfReading; double depth = g_depth; double volume = DepthToVolume(depth); //If we get called before the first measurement shows up, do nothing. //(Negative depth is physically impossible) if(depth < 0) return true; auto dseries = m_depthData.GetSeries("depth"); auto vseries = m_volumeData.GetSeries("volume"); auto fseries = m_flowData.GetSeries("flow"); //Flow is calculated in liters per hour. //Use a large Gaussian window to get a more accurate estimate. const size_t window = 127; const size_t mid = (window-1)/2; const size_t delta = 120; const size_t dwindow = window + delta; double sigma = 30; double coeffs[window]; double frac = 1 / (sqrt(2 * M_PI)*sigma); double isq = 1 / (2*sigma*sigma); double sum = 0; for(size_t i=0; i<window; i++) { double dx = fabs(i - mid); coeffs[i] = frac * exp(-dx*dx*isq); sum += coeffs[i]; } for(size_t i=0; i<window; i++) //normalize kernel coeffs[i] /= sum; double flow = 0; if(vseries->size() > dwindow) { double samples[dwindow]; double times[dwindow]; auto it = vseries->end(); it --; for(size_t i=0; i<dwindow && it != vseries->begin(); i ++) { samples[i] = it->value; times[i] = it->time; it --; } double center1 = times[mid]; double center2 = times[mid + delta]; //Smooth the volumetric data with a Gaussian kernel double gauss1 = 0; double gauss2 = 0; for(size_t i=0; i<window; i++) { gauss1 += samples[i] * coeffs[i]; gauss2 += samples[i+delta] * coeffs[i]; } double dt = center1 - center2; //printf("dt = %.3f\n", dt); double dvol = gauss1 - gauss2; //liters flow = (dvol * 3600) / dt; printf("rates: %.3f %.3f / %.3f L, %.3f L/hr, dt %f\n", gauss1, gauss2, dvol, flow, dt); } //TODO: determine if the pump is on or not dseries->push_back(GraphPoint(t, depth)); vseries->push_back(GraphPoint(t, volume)); fseries->push_back(GraphPoint(t, flow)); //Format text char tmp[128]; snprintf(tmp, sizeof(tmp), "%.1f mm", depth); m_depthLabel.set_label(tmp); snprintf(tmp, sizeof(tmp), "%.1f L", volume); m_volumeLabel.set_label(tmp); snprintf(tmp, sizeof(tmp), "%.1f L/hr", flow); m_flowLabel.set_label(tmp); //If the flow rate is positive (pump not running, water leaking in) add the current flow rate to the history if(flow > 0) { if(m_flowSamples.empty()) printf("Pump stopped\n"); m_flowSamples.push_back(flow); } //Pump is running. //Pump must have just started if we have samples in the buffer. else if(!m_flowSamples.empty() && (flow < -1) ) { printf("Pump started\n"); //Figure out total memory depth. //Ignore 20 sec at start and end of buffer due to interference from the pump flow size_t margin = 20; double sum = 0; double count = 0; for(size_t i=margin; i+margin < m_flowSamples.size(); i++) { sum += m_flowSamples[i]; count ++; } double avg; if(count == 0) avg = 0; else avg = sum / count; m_flowSamples.clear(); printf("Average flow during this pump cycle: %f\n", avg); //Write current flow to a file we can read from munin FILE* fp = fopen("avgflow.txt", "w"); fprintf(fp, "%f", avg); fclose(fp); auto tseries = m_trendData.GetSeries("flow"); tseries->push_back(GraphPoint(t, avg)); } //No, pump has been running for a while. No action needed. else { } //Clean out old stuff size_t max_points = 10000; while(dseries->size() > max_points) dseries->erase(dseries->begin()); while(vseries->size() > max_points) vseries->erase(vseries->begin()); while(fseries->size() > max_points) fseries->erase(fseries->begin()); return true; } void MainWindow::AlarmOn() { m_alarming = true; system("python3 /home/azonenberg/alarm-on.py"); } void MainWindow::AlarmOff() { m_alarming = false; system("python3 /home/azonenberg/alarm-off.py"); } void MainWindow::SilenceAlarm() { system("python3 /home/azonenberg/alarm-off.py"); }
36.685552
120
0.59529
azonenberg
9825da1c31e6dde9b247fba908733786293c6894
657
cpp
C++
Engine/Src/SFEngine/Asset/Importer/SFAssetImporterTexture.cpp
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
1
2020-06-20T07:35:25.000Z
2020-06-20T07:35:25.000Z
Engine/Src/SFEngine/Asset/Importer/SFAssetImporterTexture.cpp
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
null
null
null
Engine/Src/SFEngine/Asset/Importer/SFAssetImporterTexture.cpp
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // CopyRight (c) 2018 Kyungkun Ko // // Author : KyungKun Ko // // Description : Asset Importer // //////////////////////////////////////////////////////////////////////////////// #include "SFEnginePCH.h" #include "ResultCode/SFResultCodeSystem.h" #include "Asset/Importer//SFAssetImporterTexture.h" #include "Resource/SFTexture.h" namespace SF { AssetImporterTexture::AssetImporterTexture(IHeap& heap, const StringCrc64& name) : AssetImporter(heap, name) { } AssetImporterTexture::~AssetImporterTexture() { } }
17.289474
82
0.499239
blue3k
9831de890e9deaa18ea939c33f4de2368059108e
13,427
cpp
C++
source/modules/neuralNetwork/layer/pooling/pooling.cpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
43
2018-07-26T07:20:42.000Z
2022-03-02T10:23:12.000Z
source/modules/neuralNetwork/layer/pooling/pooling.cpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
212
2018-09-21T10:44:07.000Z
2022-03-22T14:33:05.000Z
source/modules/neuralNetwork/layer/pooling/pooling.cpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
16
2018-07-25T15:00:36.000Z
2022-03-22T14:19:46.000Z
#include "modules/neuralNetwork/layer/pooling/pooling.hpp" #include "modules/neuralNetwork/neuralNetwork.hpp" #ifdef _KORALI_USE_CUDNN #include "auxiliar/cudaUtils.hpp" #endif #ifdef _KORALI_USE_ONEDNN #include "auxiliar/dnnUtils.hpp" using namespace dnnl; #endif #include <Eigen/Dense> using namespace Eigen; namespace korali { namespace neuralNetwork { namespace layer { ; void Pooling::initialize() { // Checking Layer size if (_outputChannels == 0) KORALI_LOG_ERROR("Node count for layer (%lu) should be larger than zero.\n", _index); // Checking position if (_index == 0) KORALI_LOG_ERROR("Pooling layers cannot be the starting layer of the NN\n"); if (_index == _nn->_layers.size() - 1) KORALI_LOG_ERROR("Pooling layers cannot be the last layer of the NN\n"); // Precalculating values for the pooling operation N = _batchSize; IH = _imageHeight; IW = _imageWidth; KH = _kernelHeight; KW = _kernelWidth; SV = _verticalStride; SH = _horizontalStride; PT = _paddingTop; PL = _paddingLeft; PB = _paddingBottom; PR = _paddingRight; // Check for non zeros if (IH <= 0) KORALI_LOG_ERROR("Image height must be larger than zero for pooling layer.\n"); if (IW <= 0) KORALI_LOG_ERROR("Image width must be larger than zero for pooling layer.\n"); if (KH <= 0) KORALI_LOG_ERROR("Kernel height must be larger than zero for pooling layer.\n"); if (KW <= 0) KORALI_LOG_ERROR("Kernel width must be larger than zero for pooling layer.\n"); if (SV <= 0) KORALI_LOG_ERROR("Vertical stride must be larger than zero for pooling layer.\n"); if (SH <= 0) KORALI_LOG_ERROR("Horizontal stride must be larger than zero for pooling layer.\n"); // Several sanity checks if (KH > IH) KORALI_LOG_ERROR("Kernel height cannot be larger than input image height.\n"); if (KW > IW) KORALI_LOG_ERROR("Kernel height cannot be larger than input image height.\n"); if (PR + PL > IW) KORALI_LOG_ERROR("L+R Paddings cannot exceed the width of the input image.\n"); if (PT + PB > IH) KORALI_LOG_ERROR("T+B Paddings cannot exceed the height of the input image.\n"); // Check whether the output channels of the previous layer is divided by the height and width if (_prevLayer->_outputChannels % (IH * IW) > 0) KORALI_LOG_ERROR("Previous layer contains a number of channels (%lu) not divisible by the pooling 2D HxW setup (%lux%lu).\n", _prevLayer->_outputChannels, IH, IW); IC = _prevLayer->_outputChannels / (IH * IW); // Deriving output height and width OH = std::floor((IH - (KH - (PR + PL))) / SH) + 1; OW = std::floor((IW - (KW - (PT + PB))) / SV) + 1; // Check whether the output channels of the previous layer is divided by the height and width if (_outputChannels % (OH * OW) > 0) KORALI_LOG_ERROR("Pooling layer contains a number of output channels (%lu) not divisible by the output image size (%lux%lu) given kernel (%lux%lu) size and padding/stride configuration.\n", _outputChannels, OH, OW, KH, KW); OC = _outputChannels / (OH * OW); } void Pooling::createForwardPipeline() { // Calling base layer function Layer::createForwardPipeline(); if (_nn->_engine == "Korali") KORALI_LOG_ERROR("Pooling Layers still not supported in Korali's NN backend. Use OneDNN.\n"); if (_nn->_engine == "CuDNN") KORALI_LOG_ERROR("Pooling Layers still not supported in CuDNNbackend. Use OneDNN.\n"); #ifdef _KORALI_USE_ONEDNN if (_nn->_engine == "OneDNN") { // Creating memory descriptor mappings for input memory _srcMemDesc = memory::desc({N, IC, IH, IW}, memory::data_type::f32, memory::format_tag::nchw); _dstMemDesc = memory::desc({N, OC, OH, OW}, memory::data_type::f32, memory::format_tag::nchw); // Creating padding dims memory::dims ST = {SV, SH}; // Horizontal Vertical memory::dims PTL = {PT, PL}; // Top Left memory::dims PBR = {PB, PR}; // Bottom Right // Creating work memory memory::dims kernelDims = {KH, KW}; // Determining algorithm dnnl::algorithm algorithmType; if (_function == "Max") algorithmType = dnnl::algorithm::pooling_max; if (_function == "Inclusive Average") algorithmType = dnnl::algorithm::pooling_avg_include_padding; if (_function == "Exclusive Average") algorithmType = dnnl::algorithm::pooling_avg_exclude_padding; // We create the pooling operation auto pooling_d = pooling_forward::desc(_propKind, algorithmType, _srcMemDesc, _dstMemDesc, ST, kernelDims, PTL, PBR); // Create inner product primitive descriptor. dnnl::primitive_attr poolingPrimitiveAttributes; _forwardPoolingPrimitiveDesc = pooling_forward::primitive_desc(pooling_d, poolingPrimitiveAttributes, _nn->_dnnlEngine); // Create pooling workspace memory _workspaceMem.resize(_nn->_timestepCount); for (size_t t = 0; t < _nn->_timestepCount; t++) _workspaceMem[t] = memory(_forwardPoolingPrimitiveDesc.workspace_desc(), _nn->_dnnlEngine); // Create the weights+bias primitive. _forwardPoolingPrimitive = pooling_forward(_forwardPoolingPrimitiveDesc); } #endif } void Pooling::createBackwardPipeline() { // Initializing memory objects and primitives for BACKWARD propagation // Calling base layer function Layer::createBackwardPipeline(); #ifdef _KORALI_USE_ONEDNN if (_nn->_engine == "OneDNN") { // Creating memory descriptor mappings for input memory _srcMemDesc = memory::desc({N, IC, IH, IW}, memory::data_type::f32, memory::format_tag::nchw); _dstMemDesc = memory::desc({N, OC, OH, OW}, memory::data_type::f32, memory::format_tag::nchw); // Creating padding dims memory::dims ST = {SV, SH}; // Horizontal Vertical memory::dims PTL = {PT, PL}; // Top Left memory::dims PBR = {PB, PR}; // Bottom Right // Creating work memory memory::dims kernelDims = {KH, KW}; // Determining algorithm dnnl::algorithm algorithmType; if (_function == "Max") algorithmType = dnnl::algorithm::pooling_max; if (_function == "Inclusive Average") algorithmType = dnnl::algorithm::pooling_avg_include_padding; if (_function == "Exclusive Average") algorithmType = dnnl::algorithm::pooling_avg_exclude_padding; auto backwardDataDesc = pooling_backward::desc( algorithmType, _srcMemDesc, _dstMemDesc, ST, kernelDims, PTL, PBR); // Create the primitive. auto backwardDataPrimitiveDesc = pooling_backward::primitive_desc(backwardDataDesc, _nn->_dnnlEngine, _forwardPoolingPrimitiveDesc); _backwardDataPrimitive = pooling_backward(backwardDataPrimitiveDesc); } #endif } void Pooling::forwardData(const size_t t) { #ifdef _KORALI_USE_ONEDNN if (_nn->_engine == "OneDNN") { // Arguments to the inner product operation std::unordered_map<int, dnnl::memory> forwardPoolingArgs; forwardPoolingArgs[DNNL_ARG_SRC] = _prevLayer->_outputMem[t]; forwardPoolingArgs[DNNL_ARG_DST] = _outputMem[t]; forwardPoolingArgs[DNNL_ARG_WORKSPACE] = _workspaceMem[t]; _forwardPoolingPrimitive.execute(_nn->_dnnlStream, forwardPoolingArgs); } #endif } void Pooling::backwardData(const size_t t) { if (_nn->_mode == "Inference") KORALI_LOG_ERROR("Requesting Layer backward data propagation but NN was configured for inference only.\n"); #ifdef _KORALI_USE_ONEDNN if (_nn->_engine == "OneDNN") { _backwardDataArgs[DNNL_ARG_DIFF_DST] = _outputGradientMem[t]; // Input _backwardDataArgs[DNNL_ARG_DIFF_SRC] = _prevLayer->_outputGradientMem[t]; // Output _backwardDataArgs[DNNL_ARG_WORKSPACE] = _workspaceMem[t]; _backwardDataPrimitive.execute(_nn->_dnnlStream, _backwardDataArgs); } #endif } void Pooling::setConfiguration(knlohmann::json& js) { if (isDefined(js, "Results")) eraseValue(js, "Results"); if (isDefined(js, "Function")) { try { _function = js["Function"].get<std::string>(); } catch (const std::exception& e) { KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Function']\n%s", e.what()); } { bool validOption = false; if (_function == "Max") validOption = true; if (_function == "Inclusive Average") validOption = true; if (_function == "Exclusive Average") validOption = true; if (validOption == false) KORALI_LOG_ERROR(" + Unrecognized value (%s) provided for mandatory setting: ['Function'] required by pooling.\n", _function.c_str()); } eraseValue(js, "Function"); } else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Function'] required by pooling.\n"); if (isDefined(js, "Image Height")) { try { _imageHeight = js["Image Height"].get<ssize_t>(); } catch (const std::exception& e) { KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Image Height']\n%s", e.what()); } eraseValue(js, "Image Height"); } else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Image Height'] required by pooling.\n"); if (isDefined(js, "Image Width")) { try { _imageWidth = js["Image Width"].get<ssize_t>(); } catch (const std::exception& e) { KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Image Width']\n%s", e.what()); } eraseValue(js, "Image Width"); } else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Image Width'] required by pooling.\n"); if (isDefined(js, "Kernel Height")) { try { _kernelHeight = js["Kernel Height"].get<ssize_t>(); } catch (const std::exception& e) { KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Kernel Height']\n%s", e.what()); } eraseValue(js, "Kernel Height"); } else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Kernel Height'] required by pooling.\n"); if (isDefined(js, "Kernel Width")) { try { _kernelWidth = js["Kernel Width"].get<ssize_t>(); } catch (const std::exception& e) { KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Kernel Width']\n%s", e.what()); } eraseValue(js, "Kernel Width"); } else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Kernel Width'] required by pooling.\n"); if (isDefined(js, "Vertical Stride")) { try { _verticalStride = js["Vertical Stride"].get<ssize_t>(); } catch (const std::exception& e) { KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Vertical Stride']\n%s", e.what()); } eraseValue(js, "Vertical Stride"); } else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Vertical Stride'] required by pooling.\n"); if (isDefined(js, "Horizontal Stride")) { try { _horizontalStride = js["Horizontal Stride"].get<ssize_t>(); } catch (const std::exception& e) { KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Horizontal Stride']\n%s", e.what()); } eraseValue(js, "Horizontal Stride"); } else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Horizontal Stride'] required by pooling.\n"); if (isDefined(js, "Padding Left")) { try { _paddingLeft = js["Padding Left"].get<ssize_t>(); } catch (const std::exception& e) { KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Padding Left']\n%s", e.what()); } eraseValue(js, "Padding Left"); } else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Padding Left'] required by pooling.\n"); if (isDefined(js, "Padding Right")) { try { _paddingRight = js["Padding Right"].get<ssize_t>(); } catch (const std::exception& e) { KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Padding Right']\n%s", e.what()); } eraseValue(js, "Padding Right"); } else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Padding Right'] required by pooling.\n"); if (isDefined(js, "Padding Top")) { try { _paddingTop = js["Padding Top"].get<ssize_t>(); } catch (const std::exception& e) { KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Padding Top']\n%s", e.what()); } eraseValue(js, "Padding Top"); } else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Padding Top'] required by pooling.\n"); if (isDefined(js, "Padding Bottom")) { try { _paddingBottom = js["Padding Bottom"].get<ssize_t>(); } catch (const std::exception& e) { KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Padding Bottom']\n%s", e.what()); } eraseValue(js, "Padding Bottom"); } else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Padding Bottom'] required by pooling.\n"); Layer::setConfiguration(js); _type = "layer/pooling"; if(isDefined(js, "Type")) eraseValue(js, "Type"); if(isEmpty(js) == false) KORALI_LOG_ERROR(" + Unrecognized settings for Korali module: pooling: \n%s\n", js.dump(2).c_str()); } void Pooling::getConfiguration(knlohmann::json& js) { js["Type"] = _type; js["Function"] = _function; js["Image Height"] = _imageHeight; js["Image Width"] = _imageWidth; js["Kernel Height"] = _kernelHeight; js["Kernel Width"] = _kernelWidth; js["Vertical Stride"] = _verticalStride; js["Horizontal Stride"] = _horizontalStride; js["Padding Left"] = _paddingLeft; js["Padding Right"] = _paddingRight; js["Padding Top"] = _paddingTop; js["Padding Bottom"] = _paddingBottom; Layer::getConfiguration(js); } void Pooling::applyModuleDefaults(knlohmann::json& js) { std::string defaultString = "{}"; knlohmann::json defaultJs = knlohmann::json::parse(defaultString); mergeJson(js, defaultJs); Layer::applyModuleDefaults(js); } void Pooling::applyVariableDefaults() { Layer::applyVariableDefaults(); } ; } //layer } //neuralNetwork } //korali ;
38.253561
262
0.690996
JonathanLehner
9835d0a1c3f347d9f92019864766c823c4093a4b
3,221
cpp
C++
ESRenderEngine/app/src/main/cpp/MapExample/MapFlushVertexApp.cpp
Woohyun-Kim/ESRenderEngine
431dbbbc6529a599441b497f9797eeb223052627
[ "MIT" ]
1
2018-06-06T18:07:20.000Z
2018-06-06T18:07:20.000Z
ESRenderEngine/app/src/main/cpp/MapExample/MapFlushVertexApp.cpp
artrointel/ESRenderEngine
431dbbbc6529a599441b497f9797eeb223052627
[ "MIT" ]
null
null
null
ESRenderEngine/app/src/main/cpp/MapExample/MapFlushVertexApp.cpp
artrointel/ESRenderEngine
431dbbbc6529a599441b497f9797eeb223052627
[ "MIT" ]
null
null
null
// // Created by we.kim on 2017-07-20. // #include "MapFlushVertexApp.h" bool MapFlushVertexApp::init() { if(TriangleVBOApp::init()) { // Generate an additional VBO for map example glGenBuffers(1, &vboMapId); glBindBuffer(GL_ARRAY_BUFFER, vboMapId); glBufferData(GL_ARRAY_BUFFER, Triangle3D::ByteSize, NULL, GL_DYNAMIC_DRAW); if(triangle.attrib) { // options : We will WRITE data to the mapped buffer and // gpu driver can invalidate data of the buffer. // It's okay because we haven't ever updated before this buffer by any valid data. mappedBuf = (GLfloat *)glMapBufferRange(GL_ARRAY_BUFFER, 0, Triangle3D::ByteSize, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); if(mappedBuf == NULL) { ALOGE("MapFlushVertexApp::init glMapBuffer fail"); return false; } memcpy(mappedBuf, triangle.attrib->data, Triangle3D::ByteSize); glUnmapBuffer(GL_ARRAY_BUFFER); // full-memory of 'mappedBuf' Flush operation from GPU side mappedBuf = NULL; } glGenVertexArrays(1, &vaoMapId); glBindVertexArray(vaoMapId); { glBindBuffer(GL_ARRAY_BUFFER, vboMapId); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, Triangle3D::ByteStride, 0); glEnableVertexAttribArray(POS_ATTRIB); ALOGD("Generated VAO ID is %d", vaoMapId); } ALOGD("MapFlushVertexApp Initialized"); return true; } else return false; } MapFlushVertexApp::~MapFlushVertexApp() { glDeleteBuffers(1, &vboMapId); vboMapId = NULL; } void MapFlushVertexApp::render() { // Draw previous triangle on left screen. glBindVertexArray(0); TriangleVBOApp::render(); glBindVertexArray(vaoMapId); { // This time we made a Map with FLUSH option so user can call // explicit Flush operation on some discrete data for updating. mappedBuf = (GLfloat *)glMapBufferRange(GL_ARRAY_BUFFER, 0, Triangle3D::ByteSize, GL_MAP_WRITE_BIT | GL_MAP_FLUSH_EXPLICIT_BIT); if(mappedBuf == NULL) { ALOGE("MapVertexApp::init glMapBuffer fail"); return; } // we only update a 'x' position of vertex 0 triangle.mapAttrib(mappedBuf); triangle.mappedAttrib->vertex[0].pos.x += 0.1f; if(triangle.mappedAttrib->vertex[0].pos.x >= 1.f) triangle.mappedAttrib->vertex[0].pos.x = 0.f; glFlushMappedBufferRange(GL_ARRAY_BUFFER, 0, sizeof(triangle.mappedAttrib->vertex[0].pos.x)); // sizeof Float glUnmapBuffer(GL_ARRAY_BUFFER); // Flush only x data. // data of the others will not be updated even if the data has really updated like this. // because we didn't flushed. // triangle.mappedAttrib->vertex[1].pos.x = -1.f; glDrawArrays(GL_TRIANGLES, 0, 3); } checkGLError("MapFlushVertexApp::render"); }
37.022989
118
0.595157
Woohyun-Kim
983604f7fce37559c7a955132739d5389a33e810
14,811
hpp
C++
include/mgard-x/DataRefactoring/MultiDimension/Correction/LevelwiseProcessingKernel.hpp
JasonRuonanWang/MGARD
70d3399f6169c8a369da9fe9786c45cb6f3bb9f1
[ "Apache-2.0" ]
null
null
null
include/mgard-x/DataRefactoring/MultiDimension/Correction/LevelwiseProcessingKernel.hpp
JasonRuonanWang/MGARD
70d3399f6169c8a369da9fe9786c45cb6f3bb9f1
[ "Apache-2.0" ]
null
null
null
include/mgard-x/DataRefactoring/MultiDimension/Correction/LevelwiseProcessingKernel.hpp
JasonRuonanWang/MGARD
70d3399f6169c8a369da9fe9786c45cb6f3bb9f1
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021, Oak Ridge National Laboratory. * MGARD-X: MultiGrid Adaptive Reduction of Data Portable across GPUs and CPUs * Author: Jieyang Chen ([email protected]) * Date: December 1, 2021 */ #ifndef MGARD_X_LEVELWISE_PROCESSING_KERNEL_TEMPLATE #define MGARD_X_LEVELWISE_PROCESSING_KERNEL_TEMPLATE #include "../../../RuntimeX/RuntimeX.h" namespace mgard_x { template <DIM D, typename T, SIZE R, SIZE C, SIZE F, OPTION OP, typename DeviceType> class LwpkReoFunctor : public Functor<DeviceType> { public: MGARDX_CONT LwpkReoFunctor() {} MGARDX_CONT LwpkReoFunctor(SubArray<1, SIZE, DeviceType> shape, SubArray<D, T, DeviceType> v, SubArray<D, T, DeviceType> work) : shape(shape), v(v), work(work) { Functor<DeviceType>(); } MGARDX_EXEC void Operation1() { threadId = (FunctorBase<DeviceType>::GetThreadIdZ() * (FunctorBase<DeviceType>::GetBlockDimX() * FunctorBase<DeviceType>::GetBlockDimY())) + (FunctorBase<DeviceType>::GetThreadIdY() * FunctorBase<DeviceType>::GetBlockDimX()) + FunctorBase<DeviceType>::GetThreadIdX(); SIZE *sm = (SIZE *)FunctorBase<DeviceType>::GetSharedMemory(); shape_sm = sm; if (threadId < D) { shape_sm[threadId] = *shape(threadId); } } MGARDX_EXEC void Operation2() { SIZE idx[D]; SIZE firstD = div_roundup(shape_sm[0], F); SIZE bidx = FunctorBase<DeviceType>::GetBlockIdX(); idx[0] = (bidx % firstD) * F + FunctorBase<DeviceType>::GetThreadIdX(); // printf("firstD %d idx[0] %d\n", firstD, idx[0]); bidx /= firstD; if (D >= 2) idx[1] = FunctorBase<DeviceType>::GetBlockIdY() * FunctorBase<DeviceType>::GetBlockDimY() + FunctorBase<DeviceType>::GetThreadIdY(); if (D >= 3) idx[2] = FunctorBase<DeviceType>::GetBlockIdZ() * FunctorBase<DeviceType>::GetBlockDimZ() + FunctorBase<DeviceType>::GetThreadIdZ(); for (DIM d = 3; d < D; d++) { idx[d] = bidx % shape_sm[d]; bidx /= shape_sm[d]; } // int z = blockIdx.z * blockDim.z + threadIdx.z; // int y = blockIdx.y * blockDim.y + threadIdx.y; // int x = blockIdx.z * blockDim.z + threadIdx.z; bool in_range = true; for (DIM d = 0; d < D; d++) { if (idx[d] >= shape_sm[d]) in_range = false; } if (in_range) { // printf("%d %d %d %d\n", idx[3], idx[2], idx[1], idx[0]); if (OP == COPY) *work(idx) = *v(idx); if (OP == ADD) *work(idx) += *v(idx); if (OP == SUBTRACT) *work(idx) -= *v(idx); } } MGARDX_EXEC void Operation3() {} MGARDX_EXEC void Operation4() {} MGARDX_EXEC void Operation5() {} MGARDX_CONT size_t shared_memory_size() { size_t size = 0; size = D * sizeof(SIZE); return size; } private: SubArray<1, SIZE, DeviceType> shape; SubArray<D, T, DeviceType> v, work; IDX threadId; SIZE *shape_sm; }; template <DIM D, typename T, OPTION OP, typename DeviceType> class LwpkReo : public AutoTuner<DeviceType> { public: MGARDX_CONT LwpkReo() : AutoTuner<DeviceType>() {} template <SIZE R, SIZE C, SIZE F> MGARDX_CONT Task<LwpkReoFunctor<D, T, R, C, F, OP, DeviceType>> GenTask(SubArray<1, SIZE, DeviceType> shape, SubArray<D, T, DeviceType> v, SubArray<D, T, DeviceType> work, int queue_idx) { using FunctorType = LwpkReoFunctor<D, T, R, C, F, OP, DeviceType>; FunctorType functor(shape, v, work); SIZE total_thread_z = 1; SIZE total_thread_y = 1; SIZE total_thread_x = 1; if (D >= 3) total_thread_z = shape.dataHost()[2]; if (D >= 2) total_thread_y = shape.dataHost()[1]; total_thread_x = shape.dataHost()[0]; SIZE tbx, tby, tbz, gridx, gridy, gridz; size_t sm_size = functor.shared_memory_size(); tbz = R; tby = C; tbx = F; gridz = ceil((float)total_thread_z / tbz); gridy = ceil((float)total_thread_y / tby); gridx = ceil((float)total_thread_x / tbx); for (DIM d = 3; d < D; d++) { gridx *= shape.dataHost()[d]; } // printf("%u %u %u\n", shape.dataHost()[2], shape.dataHost()[1], // shape.dataHost()[0]); PrintSubarray("shape", shape); return Task(functor, gridz, gridy, gridx, tbz, tby, tbx, sm_size, queue_idx, "LwpkReo"); } MGARDX_CONT void Execute(SubArray<1, SIZE, DeviceType> shape, SubArray<D, T, DeviceType> v, SubArray<D, T, DeviceType> work, int queue_idx) { int range_l = std::min(6, (int)std::log2(shape.dataHost()[0]) - 1); int arch = DeviceRuntime<DeviceType>::GetArchitectureGeneration(); int prec = TypeToIdx<T>(); double min_time = std::numeric_limits<double>::max(); int min_config = 0; // int config = 0; int config = AutoTuner<DeviceType>::autoTuningTable.lwpk[prec][range_l]; #define LWPK(CONFIG) \ if (config == CONFIG || AutoTuner<DeviceType>::ProfileKernels) { \ const int R = LWPK_CONFIG[D - 1][CONFIG][0]; \ const int C = LWPK_CONFIG[D - 1][CONFIG][1]; \ const int F = LWPK_CONFIG[D - 1][CONFIG][2]; \ using FunctorType = LwpkReoFunctor<D, T, R, C, F, OP, DeviceType>; \ using TaskType = Task<FunctorType>; \ TaskType task = GenTask<R, C, F>(shape, v, work, queue_idx); \ DeviceAdapter<TaskType, DeviceType> adapter; \ ExecutionReturn ret = adapter.Execute(task); \ if (AutoTuner<DeviceType>::ProfileKernels) { \ if (min_time > ret.execution_time) { \ min_time = ret.execution_time; \ min_config = CONFIG; \ } \ } \ } LWPK(0) LWPK(1) LWPK(2) LWPK(3) LWPK(4) LWPK(5) LWPK(6) #undef LWPK if (AutoTuner<DeviceType>::ProfileKernels) { FillAutoTunerTable<DeviceType>("lwpk", prec, range_l, min_config); } } }; // template <DIM D, typename T, SIZE R, SIZE C, SIZE F, int OP> // __global__ void _lwpk(SIZE *shape, T *dv, SIZE *ldvs, T *dwork, SIZE *ldws) { // size_t threadId = (threadIdx.z * (blockDim.x * blockDim.y)) + // (threadIdx.y * blockDim.x) + threadIdx.x; // SIZE *sm = SharedMemory<SIZE>(); // SIZE *shape_sm = sm; // SIZE *ldvs_sm = shape_sm + D; // SIZE *ldws_sm = ldvs_sm + D; // if (threadId < D) { // shape_sm[threadId] = shape[threadId]; // ldvs_sm[threadId] = ldvs[threadId]; // ldws_sm[threadId] = ldws[threadId]; // } // __syncthreads(); // SIZE idx[D]; // SIZE firstD = div_roundup(shape_sm[0], F); // SIZE bidx = FunctorBase<DeviceType>::GetBlockIdX(); // idx[0] = (bidx % firstD) * F + threadIdx.x; // // printf("firstD %d idx[0] %d\n", firstD, idx[0]); // bidx /= firstD; // if (D >= 2) // idx[1] = blockIdx.y * blockDim.y + threadIdx.y; // if (D >= 3) // idx[2] = blockIdx.z * blockDim.z + threadIdx.z; // for (DIM d = 3; d < D; d++) { // idx[d] = bidx % shape_sm[d]; // bidx /= shape_sm[d]; // } // // int z = blockIdx.z * blockDim.z + threadIdx.z; // // int y = blockIdx.y * blockDim.y + threadIdx.y; // // int x = blockIdx.z * blockDim.z + threadIdx.z; // bool in_range = true; // for (DIM d = 0; d < D; d++) { // if (idx[d] >= shape_sm[d]) // in_range = false; // } // if (in_range) { // // printf("%d %d %d %d\n", idx[3], idx[2], idx[1], idx[0]); // if (OP == COPY) // dwork[get_idx<D>(ldws, idx)] = dv[get_idx<D>(ldvs, idx)]; // if (OP == ADD) // dwork[get_idx<D>(ldws, idx)] += dv[get_idx<D>(ldvs, idx)]; // if (OP == SUBTRACT) // dwork[get_idx<D>(ldws, idx)] -= dv[get_idx<D>(ldvs, idx)]; // } // } // template <DIM D, typename T, SIZE R, SIZE C, SIZE F, int OP> // void lwpk_adaptive_launcher(Handle<D, T> &handle, SIZE *shape_h, SIZE // *shape_d, // T *dv, SIZE *ldvs, T *dwork, SIZE *ldws, // int queue_idx) { // SIZE total_thread_z = shape_h[2]; // SIZE total_thread_y = shape_h[1]; // SIZE total_thread_x = shape_h[0]; // // linearize other dimensions // SIZE tbz = R; // SIZE tby = C; // SIZE tbx = F; // SIZE gridz = ceil((float)total_thread_z / tbz); // SIZE gridy = ceil((float)total_thread_y / tby); // SIZE gridx = ceil((float)total_thread_x / tbx); // for (DIM d = 3; d < D; d++) { // gridx *= shape_h[d]; // } // // printf("exec: %d %d %d %d %d %d\n", tbx, tby, tbz, gridx, gridy, gridz); // dim3 threadsPerBlock(tbx, tby, tbz); // dim3 blockPerGrid(gridx, gridy, gridz); // size_t sm_size = (D * 3) * sizeof(SIZE); // _lwpk<D, T, R, C, F, OP><<<blockPerGrid, threadsPerBlock, sm_size, // *(cudaStream_t *)handle.get(queue_idx)>>>( // shape_d, dv, ldvs, dwork, ldws); // gpuErrchk(cudaGetLastError()); // if (handle.sync_and_check_all_kernels) { // gpuErrchk(cudaDeviceSynchronize()); // } // } // template <DIM D, typename T, int OP> // void lwpk(Handle<D, T> &handle, SIZE *shape_h, SIZE *shape_d, T *dv, SIZE // *ldvs, // T *dwork, SIZE *ldws, int queue_idx) { // #define COPYLEVEL(R, C, F) \ // { \ // lwpk_adaptive_launcher<D, T, R, C, F, OP>(handle, shape_h, shape_d, dv, \ // ldvs, dwork, ldws, queue_idx); // \ // } // if (D >= 3) { // COPYLEVEL(4, 4, 4) // } // if (D == 2) { // COPYLEVEL(1, 4, 4) // } // if (D == 1) { // COPYLEVEL(1, 1, 8) // } // #undef COPYLEVEL // } template <mgard_x::DIM D, typename T, int R, int C, int F, OPTION OP, typename DeviceType> class LevelwiseCalcNDFunctor : public Functor<DeviceType> { public: MGARDX_CONT LevelwiseCalcNDFunctor(SIZE *shape, SubArray<D, T, DeviceType> v, SubArray<D, T, DeviceType> w) : shape(shape), v(v), w(w) { Functor<DeviceType>(); } MGARDX_EXEC void Operation1() { threadId = (FunctorBase<DeviceType>::GetThreadIdZ() * (FunctorBase<DeviceType>::GetBlockDimX() * FunctorBase<DeviceType>::GetBlockDimY())) + (FunctorBase<DeviceType>::GetThreadIdY() * FunctorBase<DeviceType>::GetBlockDimX()) + FunctorBase<DeviceType>::GetThreadIdX(); int8_t *sm_p = (int8_t *)FunctorBase<DeviceType>::GetSharedMemory(); shape_sm = (SIZE *)sm_p; sm_p += D * sizeof(SIZE); if (threadId < D) { shape_sm[threadId] = shape[threadId]; } } MGARDX_EXEC void Operation2() { SIZE firstD = div_roundup(shape_sm[0], F); SIZE bidx = FunctorBase<DeviceType>::GetBlockIdX(); idx[0] = (bidx % firstD) * F + FunctorBase<DeviceType>::GetThreadIdX(); // printf("firstD %d idx[0] %d\n", firstD, idx[0]); bidx /= firstD; if (D >= 2) idx[1] = FunctorBase<DeviceType>::GetBlockIdY() * FunctorBase<DeviceType>::GetBlockDimY() + FunctorBase<DeviceType>::GetThreadIdY(); if (D >= 3) idx[2] = FunctorBase<DeviceType>::GetBlockIdZ() * FunctorBase<DeviceType>::GetBlockDimZ() + FunctorBase<DeviceType>::GetThreadIdZ(); for (DIM d = 3; d < D; d++) { idx[d] = bidx % shape_sm[d]; bidx /= shape_sm[d]; } bool in_range = true; for (DIM d = 0; d < D; d++) { if (idx[d] >= shape_sm[d]) in_range = false; } if (in_range) { // printf("%d %d %d %d\n", idx[3], idx[2], idx[1], idx[0]); if (OP == COPY) *w(idx) = *v(idx); if (OP == ADD) *w(idx) += *v(idx); if (OP == SUBTRACT) *w(idx) -= *v(idx); } } MGARDX_EXEC void Operation3() {} MGARDX_EXEC void Operation4() {} MGARDX_EXEC void Operation5() {} MGARDX_CONT size_t shared_memory_size() { size_t size = 0; size += D * sizeof(SIZE); return size; } private: SIZE *shape; SubArray<D, T, DeviceType> v; SubArray<D, T, DeviceType> w; SIZE *shape_sm; size_t threadId; SIZE idx[D]; }; template <DIM D, typename T, OPTION Direction, typename DeviceType> class LevelwiseCalcNDKernel : public AutoTuner<DeviceType> { public: MGARDX_CONT LevelwiseCalcNDKernel() : AutoTuner<DeviceType>() {} template <SIZE R, SIZE C, SIZE F> MGARDX_CONT Task<LevelwiseCalcNDFunctor<D, T, R, C, F, Direction, DeviceType>> GenTask(SIZE *shape_h, SIZE *shape_d, SubArray<D, T, DeviceType> v, SubArray<D, T, DeviceType> w, int queue_idx) { using FunctorType = LevelwiseCalcNDFunctor<D, T, R, C, F, Direction, DeviceType>; FunctorType functor(shape_d, v, w); SIZE tbx, tby, tbz, gridx, gridy, gridz; size_t sm_size = functor.shared_memory_size(); int total_thread_z = shape_h[2]; int total_thread_y = shape_h[1]; int total_thread_x = shape_h[0]; // linearize other dimensions tbz = R; tby = C; tbx = F; gridz = ceil((float)total_thread_z / tbz); gridy = ceil((float)total_thread_y / tby); gridx = ceil((float)total_thread_x / tbx); for (int d = 3; d < D; d++) { gridx *= shape_h[d]; } return Task(functor, gridz, gridy, gridx, tbz, tby, tbx, sm_size, queue_idx); } MGARDX_CONT void Execute(SIZE *shape_h, SIZE *shape_d, SubArray<D, T, DeviceType> v, SubArray<D, T, DeviceType> w, int queue_idx) { #define KERNEL(R, C, F) \ { \ using FunctorType = \ LevelwiseCalcNDFunctor<D, T, R, C, F, Direction, DeviceType>; \ using TaskType = Task<FunctorType>; \ TaskType task = GenTask<R, C, F>(shape_h, shape_d, v, w, queue_idx); \ DeviceAdapter<TaskType, DeviceType> adapter; \ adapter.Execute(task); \ } if (D >= 3) { KERNEL(4, 4, 16) } if (D == 2) { KERNEL(1, 4, 32) } if (D == 1) { KERNEL(1, 1, 64) } #undef KERNEL } }; } // namespace mgard_x #endif
32.623348
80
0.542165
JasonRuonanWang
9838e28fe961cfe241d63ad265dc4125ab77dbd7
24,415
cpp
C++
src/limits.cpp
neivv/teippi
05c006c2f74ad11285c39d37135aed03d1fb8806
[ "MIT" ]
11
2015-08-25T23:27:00.000Z
2021-05-06T18:53:21.000Z
src/limits.cpp
neivv/teippi
05c006c2f74ad11285c39d37135aed03d1fb8806
[ "MIT" ]
2
2015-08-30T21:22:59.000Z
2016-05-31T17:49:42.000Z
src/limits.cpp
neivv/teippi
05c006c2f74ad11285c39d37135aed03d1fb8806
[ "MIT" ]
5
2015-08-29T22:35:28.000Z
2016-02-26T19:15:24.000Z
#include "limits.h" #include "patch/patchmanager.h" #include "ai.h" #include "bullet.h" #include "bunker.h" #include "commands.h" #include "dialog.h" #include "draw.h" #include "flingy.h" #include "game.h" #include "init.h" #include "image.h" #include "iscript.h" #include "log.h" #include "offsets_hooks.h" #include "offsets.h" #include "order.h" #include "pathing.h" #include "player.h" #include "replay.h" #include "rng.h" #include "save.h" #include "selection.h" #include "sound.h" #include "sprite.h" #include "targeting.h" #include "tech.h" #include "triggers.h" #include "unitsearch.h" #include "warn.h" #include "unit.h" Common::PatchManager *patch_mgr; // Hack from game.cpp extern bool unitframes_in_progress; void DamageUnit_Hook(int damage, Unit *target, Unit *attacker, int attacking_player, int show_attacker) { // Can't do UnitWasHit here, so warn if (attacker != nullptr) Warning("DamageUnit hooked"); vector<Unit *> killed_units; DamageUnit(damage, target, &killed_units); for (Unit *unit : killed_units) unit->Kill(nullptr); } void AddMultipleOverlaySprites(Sprite *sprite, uint16_t base, int overlay_type, int count, int sprite_id, int flip) { sprite->AddMultipleOverlaySprites(overlay_type, count - base + 1, SpriteType(sprite_id), base, flip); } void SendUnloadCommand(const Unit *unit) { uint8_t buf[5]; buf[0] = commands::Unload; *(uint32_t *)(buf + 1) = unit->lookup_id; bw::SendCommand(buf, 5); } Unit ** FindUnitsRect(const Rect16 *rect) { int tmp; Rect16 r = *rect; // See unitsearch.h r.right += 1; r.bottom += 1; if (r.right < r.left) r.left = 0; if (r.bottom < r.top) r.top = 0; r.right = std::min(r.right, *bw::map_width); r.bottom = std::min(r.bottom, *bw::map_height); Unit **ret = unit_search->FindUnitsRect(r, &tmp); return ret; } Unit ** CheckMovementCollision(Unit *unit, int x, int y) { if (x >= 0x8000) x |= 0xffff << 16; if (y >= 0x8000) y |= 0xffff << 16; return unit_search->CheckMovementCollision(unit, x, y); } Unit **FindUnitBordersRect(const Rect16 *rect) { Rect16 r = *rect; if (r.right < r.left) r.left = 0; if (r.bottom < r.top) r.top = 0; return unit_search->FindUnitBordersRect(&r); } Unit *FindNearestUnit(Rect16 *area, Unit *a, uint16_t b, uint16_t c, int d, int e, int f, int g, int (__fastcall *h)(const Unit *, void *), void *i) { if (area->left > area->right) area->left = 0; if (area->top > area->bottom) area->top = 0; return unit_search->FindNearestUnit(a, Point(b, c), h, i, *area); } void CancelZergBuilding(Unit *unit) { //Warning("Calling Unit::Kill with nullptr from CancelZergBuilding (Extractor)"); // This *should* not matter, as human cancels are at least done from ProcessCommands unit->CancelZergBuilding(nullptr); } Order *DeleteOrder_Hook(Order *order, Unit *unit) { unit->DeleteOrder(order); // Bw assumes that it returns a order, but with this implementation // it would be use-after-free, so just return nullptr and hope // that any uses get caught with it. return nullptr; } void KillSingleUnit(Unit *unit) { if (unitframes_in_progress) Warning("Hooked Unit::Kill while unit frames are progressed (unit %x)", unit->unit_id); unit->Kill(nullptr); } Unit **FindUnitsPoint(uint16_t x, uint16_t y) { Rect16 area(x, y, x + 1, y + 1); return unit_search->FindUnitsRect(Rect16(x, y, x + 1, y + 1)); } int IsTileBlockedBy(Unit **units, Unit *builder, int x_tile, int y_tile, int dont_ignore_reacting, int also_invisible) { int xpos = x_tile * 32; int ypos = y_tile * 32; for (Unit *unit = *units++; unit; unit = *units++) { if (unit == builder) continue; if (unit->flags & (UnitStatus::Building | UnitStatus::Air)) continue; if (unit->Type() == UnitId::DarkSwarm || unit->Type() == UnitId::DisruptionWeb) continue; if (!dont_ignore_reacting && unit->flags & UnitStatus::Reacts) continue; bool invisible = false; if (builder && unit->IsInvisibleTo(builder)) { if (!also_invisible) continue; else invisible = true; } if (unit->sprite->IsHidden()) continue; Rect16 crect = unit->GetCollisionRect(); if (crect.left < xpos + 32 && crect.right > xpos) { if (crect.top < ypos + 32 && crect.bottom > ypos) { if (invisible) return 0; else return 4; } } } return 0; } // Horribly misnamed int DoesBuildingBlock(Unit *builder, int x_tile, int y_tile) { if (!builder || ~builder->flags & UnitStatus::Building || builder->Type() == UnitId::NydusCanal) return true; if (builder->sprite->IsHidden()) return true; Rect16 crect = builder->GetCollisionRect(); if (crect.left >= (x_tile + 1) * 32 || crect.right <= x_tile * 32) return true; if (crect.top >= (y_tile + 1) * 32 || crect.bottom <= y_tile * 32) return true; return false; } class SimpleIscriptContext : public Iscript::Context { public: constexpr SimpleIscriptContext(Rng *rng) : Iscript::Context(rng, false) { } virtual Iscript::CmdResult HandleCommand(Image *img, Iscript::Script *script, const Iscript::Command &cmd) override { auto result = img->HandleIscriptCommand(this, script, cmd); if (result == Iscript::CmdResult::NotHandled) { Warning("Could not handle iscript command %s for image %s from SetIscriptAnimation hook", cmd.DebugStr().c_str(), img->DebugStr().c_str()); } return result; } }; void SetIscriptAnimation(Image *img, uint8_t anim) { if (*bw::active_iscript_unit != nullptr) (*bw::active_iscript_unit)->SetIscriptAnimationForImage(img, anim); else { // This is unable to handle any unit-specific commands SimpleIscriptContext ctx(MainRng()); img->SetIscriptAnimation(&ctx, anim); } } class MovementIscriptContext : public Iscript::Context { public: constexpr MovementIscriptContext(Unit *unit, uint32_t *out_speed, Rng *rng) : Iscript::Context(rng, false), unit(unit), out_speed(out_speed) { } Unit * const unit; uint32_t *out_speed; virtual Iscript::CmdResult HandleCommand(Image *img, Iscript::Script *script, const Iscript::Command &cmd) override { if (cmd.opcode == Iscript::Opcode::Move) { auto speed = bw::CalculateSpeedChange(unit, cmd.val * 256); *out_speed = speed; } auto result = img->ConstIscriptCommand(this, script, cmd); if (result == Iscript::CmdResult::NotHandled) return Iscript::CmdResult::Handled; return result; } }; static void ProgressIscriptFrame_Hook(Image *image, Iscript::Script *script, int test_run, uint32_t *out_speed) { // Shouldn't be hooked from elsewhere Assert(*bw::active_iscript_unit != nullptr); if (test_run) { Assert(out_speed != nullptr); MovementIscriptContext ctx(*bw::active_iscript_unit, out_speed, MainRng()); script->ProgressFrame(&ctx, image); } else { // What to do? Could try determining if we are using unit, bullet, sprite or what, // but this shouldn't be called anyways Warning("ProgressIscriptFrame hooked"); } } int ForEachLoadedUnit(Unit *transport, int (__fastcall *Func)(Unit *unit, void *param), void *param) { for (Unit *unit = transport->first_loaded; unit; unit = unit->next_loaded) { if ((*Func)(unit, param)) return 1; } return 0; } void AddLoadedUnitsToCompletedUnitLbScore(Unit *transport) { for (Unit *unit = transport->first_loaded; unit; unit = unit->next_loaded) { bw::AddToCompletedUnitLbScore(unit); } } void TriggerPortraitFinished_Hook(Control *ctrl, int timer_id) { bw::DeleteTimer(ctrl, timer_id); *bw::trigger_portrait_active = 0; // Not including the code which clears waits in singleplayer, as it causes replays to desync } FILE *fopen_hook(const char *a, const char *b) { return fopen(a, b); } void fclose_hook(FILE *a) { fclose(a); } int fread_hook(void *a, int b, int c, FILE *d) { return fread(a, b, c, d); } int fwrite_hook(void *a, int b, int c, FILE *d) { return fwrite(a, b, c, d); } int fgetc_hook(FILE *a) { return fgetc(a); } int fseek_hook(FILE *a, int b, int c) { return fseek(a, b, c); } int setvbuf_hook(FILE *a, char *b, int c, int d) { return setvbuf(a, b, c, d); } void CreateSimplePath_Hook(Unit *unit, uint32_t waypoint_xy, uint32_t end_xy) { CreateSimplePath(unit, Point(waypoint_xy & 0xffff, waypoint_xy >> 16), Point(end_xy & 0xffff, end_xy >> 16)); } static void ProgressMove_Hook(Flingy *flingy) { FlingyMoveResults unused; flingy->ProgressMove(&unused); } static int IsDrawnPixel(GrpFrameHeader *frame, int x, int y) { if (x < 0 || x >= frame->w) return 0; if (y < 0 || y >= frame->h) return 0; return frame->GetPixel(x, y) != 0; } static bool __fastcall DrawGrp_Hook(int x, int y, GrpFrameHeader * frame_header, Rect32 * rect, void *unused) { if (frame_header->IsDecoded()) { DrawNormal_NonFlipped(x, y, frame_header, rect, unused); return true; } else return false; } static bool __fastcall DrawGrp_Flipped_Hook(int x, int y, GrpFrameHeader * frame_header, Rect32 * rect, void *unused) { if (frame_header->IsDecoded()) { DrawNormal_Flipped(x, y, frame_header, rect, unused); return true; } else return false; } static void MakeDetected_Hook(Sprite *sprite) { if (sprite->flags & 0x40) bw::RemoveCloakDrawfuncs(sprite); else { for (Image *img : sprite->first_overlay) img->MakeDetected(); } } void PatchDraw(Common::PatchContext *patch) { patch->Hook(bw::SDrawLockSurface, SDrawLockSurface_Hook); patch->Hook(bw::SDrawUnlockSurface, SDrawUnlockSurface_Hook); patch->Hook(bw::DrawScreen, DrawScreen); } void RemoveLimits(Common::PatchContext *patch) { delete unit_search; unit_search = new MainUnitSearch; Ai::RemoveLimits(patch); if (UseConsole) { patch->Hook(bw::GenerateFog, GenerateFog); } patch->Hook(bw::ProgressObjects, ProgressObjects); patch->Hook(bw::GameFunc, ProgressFrames); patch->Hook(bw::CreateOrder, [](uint8_t order, uint32_t pos, Unit *target, uint16_t fow) { return new Order(OrderType(order), Point(pos & 0xffff, pos >> 16), target, UnitType(fow)); }); patch->Hook(bw::DeleteOrder, DeleteOrder_Hook); patch->Hook(bw::DeleteSpecificOrder, [](Unit *unit, uint8_t order) { return unit->DeleteSpecificOrder(OrderType(order)); }); patch->Hook(bw::GetEmptyImage, []{ return new Image; }); patch->Hook(bw::DeleteImage, &Image::SingleDelete); patch->Hook(bw::CreateSprite, Sprite::AllocateWithBasicIscript_Hook); patch->Hook(bw::DeleteSprite, [](Sprite *sprite) { sprite->Remove(); delete sprite; }); patch->Hook(bw::ProgressSpriteFrame, [](Sprite *sprite) { // Shouldn't be hooked from elsewhere Assert(*bw::active_iscript_unit != nullptr); (*bw::active_iscript_unit)->ProgressIscript("ProgressSpriteFrame hook", nullptr); }); patch->Hook(bw::CreateLoneSprite, [](uint16_t sprite_id, uint16_t x, uint16_t y, uint8_t player) { return lone_sprites->AllocateLone(SpriteType(sprite_id), Point(x, y), player); }); patch->Hook(bw::CreateFowSprite, [](uint16_t unit_id, Sprite *base) { return lone_sprites->AllocateFow(base, UnitType(unit_id)); }); patch->Hook(bw::InitLoneSprites, InitCursorMarker); patch->Hook(bw::DrawCursorMarker, DrawCursorMarker); patch->Hook(bw::ShowRallyTarget, ShowRallyTarget); patch->Hook(bw::ShowCursorMarker, ShowCursorMarker); patch->Hook(bw::SetSpriteDirection, &Sprite::SetDirection32); patch->Hook(bw::FindBlockingFowResource, FindBlockingFowResource); patch->Hook(bw::DrawAllMinimapUnits, DrawMinimapUnits); patch->Hook(bw::CreateBunkerShootOverlay, CreateBunkerShootOverlay); patch->Hook(bw::AllocateUnit, &Unit::AllocateAndInit); patch->CallHook(bw::InitUnitSystem_Hook, []{ Unit::DeleteAll(); // Hack to do it here but oh well. score->Initialize(); }); patch->Hook(bw::InitSpriteSystem, Sprite::InitSpriteSystem); patch->Hook(bw::CreateBullet, [](Unit *parent, int x, int y, uint8_t player, uint8_t direction, uint8_t weapon_id) { return bullet_system->AllocateBullet(parent, player, direction, WeaponType(weapon_id), Point(x, y)); }); patch->Hook(bw::GameEnd, GameEnd); patch->Hook(bw::AddToPositionSearch, [](Unit *unit) { unit_search->Add(unit); } ); patch->Hook(bw::FindUnitPosition, [](int) { return 0; }); patch->Hook(bw::FindUnitsRect, FindUnitsRect); patch->Hook(bw::FindNearbyUnits, [](Unit *u, int x, int y) { return unit_search->FindCollidingUnits(u, x, y); }); patch->Hook(bw::DoUnitsCollide, [](const Unit *a, const Unit *b) { return unit_search->DoUnitsCollide(a, b); }); patch->Hook(bw::CheckMovementCollision, CheckMovementCollision); patch->Hook(bw::FindUnitBordersRect, FindUnitBordersRect); patch->CallHook(bw::ClearPositionSearch, []{ unit_search->Clear(); }); patch->Hook(bw::ChangeUnitPosition, [](Unit *unit, int x_diff, int y_diff) { unit_search->ChangeUnitPosition(unit, x_diff, y_diff); }); patch->Hook(bw::FindNearestUnit, FindNearestUnit); patch->Hook(bw::GetNearbyBlockingUnits, [](PathingData *pd) { unit_search->GetNearbyBlockingUnits(pd); }); patch->Hook(bw::RemoveFromPosSearch, [](Unit *unit) { unit_search->Remove(unit); }); patch->Hook(bw::FindUnitsPoint, FindUnitsPoint); patch->Hook(bw::GetDodgingDirection, [](const Unit *self, const Unit *other) { return unit_search->GetDodgingDirection(self, other); }); patch->Hook(bw::DoesBlockArea, [](const Unit *unit, const CollisionArea *area) -> int { return unit_search->DoesBlockArea(unit, area); }); patch->Hook(bw::IsTileBlockedBy, IsTileBlockedBy); patch->Hook(bw::DoesBuildingBlock, DoesBuildingBlock); patch->Hook(bw::UnitToIndex, [](Unit *val) { return (uint32_t)val; }); patch->Hook(bw::IndexToUnit, [](uint32_t val) { return (Unit *)val; }); patch->Hook(bw::MakeDrawnSpriteList, [] {}); patch->Hook(bw::PrepareDrawSprites, Sprite::CreateDrawSpriteList); patch->CallHook(bw::FullRedraw, Sprite::CreateDrawSpriteListFullRedraw); patch->Hook(bw::DrawSprites, Sprite::DrawSprites); // Disabled as I can't be bothered to figure it out. patch->Hook(bw::VisionSync, [](void *, int) { return 1; }); patch->Hook(bw::RemoveUnitFromBulletTargets, RemoveFromBulletTargets); patch->Hook(bw::DamageUnit, DamageUnit_Hook); patch->Hook(bw::FindUnitInLocation_Check, FindUnitInLocation_Check); patch->Hook(bw::ChangeInvincibility, ChangeInvincibility); patch->Hook(bw::CanLoadUnit, [](const Unit *a, const Unit *b) -> int { return a->CanLoadUnit(b); }); patch->Hook(bw::LoadUnit, &Unit::LoadUnit); patch->Hook(bw::HasLoadedUnits, [](const Unit *unit) -> int { return unit->HasLoadedUnits(); }); patch->Hook(bw::UnloadUnit, [](Unit *unit) -> int { return unit->related->UnloadUnit(unit); }); patch->Hook(bw::SendUnloadCommand, SendUnloadCommand); patch->Hook(bw::GetFirstLoadedUnit, [](Unit *unit) { return unit->first_loaded; }); patch->Hook(bw::ForEachLoadedUnit, ForEachLoadedUnit); patch->Hook(bw::AddLoadedUnitsToCompletedUnitLbScore, AddLoadedUnitsToCompletedUnitLbScore); patch->Hook(bw::GetUsedSpace, &Unit::GetUsedSpace); patch->Hook(bw::IsCarryingFlag, [](const Unit *unit) -> int { return unit->IsCarryingFlag(); }); patch->Hook(bw::DrawStatusScreen_LoadedUnits, DrawStatusScreen_LoadedUnits); patch->Hook(bw::TransportStatus_UpdateDrawnValues, TransportStatus_UpdateDrawnValues); patch->Hook(bw::TransportStatus_DoesNeedRedraw, TransportStatus_DoesNeedRedraw); patch->Hook(bw::StatusScreen_DrawKills, StatusScreen_DrawKills); patch->Hook(bw::AddMultipleOverlaySprites, AddMultipleOverlaySprites); patch->Hook(bw::KillSingleUnit, KillSingleUnit); patch->Hook(bw::Unit_Die, [] { Warning("Hooked Unit::Die, not doing anything"); }); patch->Hook(bw::CancelZergBuilding, CancelZergBuilding); patch->Hook(bw::SetIscriptAnimation, SetIscriptAnimation); patch->Hook(bw::ProgressIscriptFrame, ProgressIscriptFrame_Hook); patch->Hook(bw::Order_AttackMove_ReactToAttack, [](Unit *unit, int order) { return unit->Order_AttackMove_ReactToAttack(OrderType(order)); }); patch->Hook(bw::Order_AttackMove_TryPickTarget, [](Unit *unit, int order) { unit->Order_AttackMove_TryPickTarget(OrderType(order)); }); // Won't be called when loading save though. patch->CallHook(bw::PathingInited, [] { unit_search->Init(); }); patch->Hook(bw::ProgressUnstackMovement, &Unit::ProgressUnstackMovement); patch->Hook(bw::MovementState13, &Unit::MovementState13); patch->Hook(bw::MovementState17, &Unit::MovementState17); patch->Hook(bw::MovementState20, &Unit::MovementState20); patch->Hook(bw::MovementState1c, &Unit::MovementState1c); patch->Hook(bw::MovementState_FollowPath, &Unit::MovementState_FollowPath); patch->Hook(bw::MovementState_Flyer, [](Unit *) { return 0; }); patch->Hook(bw::Trig_KillUnitGeneric, [](Unit *unit, KillUnitArgs *args) { return Trig_KillUnitGeneric(unit, args, args->check_height, false); }); patch->Hook(bw::TriggerPortraitFinished, TriggerPortraitFinished_Hook); bw::trigger_actions[0x7] = TrigAction_Transmission; bw::trigger_actions[0xa] = TrigAction_CenterView; patch->Hook(bw::ChangeMovementTargetToUnit, [](Unit *unit, Unit *target) -> int { return unit->ChangeMovementTargetToUnit(target); }); patch->Hook(bw::ChangeMovementTarget, [](Unit *unit, uint16_t x, uint16_t y) -> int { return unit->ChangeMovementTarget(Point(x, y)); }); patch->JumpHook(bw::Sc_fclose, fclose_hook); patch->JumpHook(bw::Sc_fopen, fopen_hook); patch->JumpHook(bw::Sc_fwrite, fwrite_hook); patch->JumpHook(bw::Sc_fread, fread_hook); patch->JumpHook(bw::Sc_fgetc, fgetc_hook); patch->JumpHook(bw::Sc_fseek, fseek_hook); patch->JumpHook(bw::Sc_setvbuf, setvbuf_hook); patch->Hook(bw::LoadGameObjects, LoadGameObjects); patch->Hook(bw::AllocatePath, AllocatePath); patch->Hook(bw::DeletePath, &Unit::DeletePath); patch->Hook(bw::DeletePath2, &Unit::DeletePath); patch->Hook(bw::CreateSimplePath, CreateSimplePath_Hook); patch->Hook(bw::InitPathArray, [] {}); patch->Hook(bw::StatusScreenButton, StatusScreenButton); patch->Hook(bw::LoadReplayMapDirEntry, LoadReplayMapDirEntry); patch->Hook(bw::LoadReplayData, LoadReplayData); patch->Hook(bw::DoNextQueuedOrder, &Unit::DoNextQueuedOrder); patch->Hook(bw::ProcessLobbyCommands, ProcessLobbyCommands); patch->Hook(bw::BriefingOk, BriefingOk); patch->Hook(bw::ProgressFlingyTurning, [](Flingy *f) -> int { return f->ProgressTurning(); }); patch->Hook(bw::SetMovementDirectionToTarget, &Flingy::SetMovementDirectionToTarget); patch->Hook(bw::ProgressMove, ProgressMove_Hook); patch->Hook(bw::LoadGrp, [](int image_id, uint32_t *grps, Tbl *tbl, GrpSprite **loaded_grps, void **overlapped, void **out_file) { return LoadGrp(ImageType(image_id), grps, tbl, loaded_grps, overlapped, out_file); }); patch->Hook(bw::IsDrawnPixel, IsDrawnPixel); patch->Hook(bw::LoadBlendPalettes, LoadBlendPalettes); patch->Hook(bw::DrawImage_Detected, [](int x, int y, GrpFrameHeader *frame_header, Rect32 *rect, uint8_t *blend_table) { DrawBlended_NonFlipped(x, y, frame_header, rect, blend_table); }); patch->Hook(bw::DrawImage_Detected_Flipped, [](int x, int y, GrpFrameHeader *frame_header, Rect32 *rect, uint8_t *blend_table) { DrawBlended_Flipped(x, y, frame_header, rect, blend_table); }); patch->Hook(bw::DrawUncloakedPart, [](int x, int y, GrpFrameHeader *frame_header, Rect32 *rect, int state) { DrawUncloakedPart_NonFlipped(x, y, frame_header, rect, state & 0xff); }); patch->Hook(bw::DrawUncloakedPart_Flipped, [](int x, int y, GrpFrameHeader *frame_header, Rect32 *rect, int state) { DrawUncloakedPart_Flipped(x, y, frame_header, rect, state & 0xff); }); patch->Hook(bw::DrawImage_Cloaked, DrawCloaked_NonFlipped); patch->Hook(bw::DrawImage_Cloaked_Flipped, DrawCloaked_Flipped); bw::image_renderfuncs[Image::Normal].nonflipped = &DrawNormal_NonFlipped; bw::image_renderfuncs[Image::Normal].flipped = &DrawNormal_Flipped; bw::image_renderfuncs[Image::NormalSpecial].nonflipped = &DrawNormal_NonFlipped; bw::image_renderfuncs[Image::NormalSpecial].flipped = &DrawNormal_Flipped; bw::image_renderfuncs[Image::Remap].nonflipped = &DrawBlended_NonFlipped; bw::image_renderfuncs[Image::Remap].flipped = &DrawBlended_Flipped; bw::image_renderfuncs[Image::Shadow].nonflipped = &DrawShadow_NonFlipped; bw::image_renderfuncs[Image::Shadow].flipped = &DrawShadow_Flipped; bw::image_renderfuncs[Image::UseWarpTexture].nonflipped = &DrawWarpTexture_NonFlipped; bw::image_renderfuncs[Image::UseWarpTexture].flipped = &DrawWarpTexture_Flipped; patch->Patch(bw::DrawGrp, (void *)&DrawGrp_Hook, 12, PATCH_OPTIONALHOOK | PATCH_SAFECALLHOOK); patch->Patch(bw::DrawGrp_Flipped, (void *)&DrawGrp_Flipped_Hook, 12, PATCH_OPTIONALHOOK | PATCH_SAFECALLHOOK); patch->Hook(bw::FindUnitAtPoint, FindUnitAtPoint); patch->Hook(bw::MakeJoinedGameCommand, [](int flags, int x4, int proto_ver, int save_uniq_player, int save_player, uint32_t save_hash, int create) { MakeJoinedGameCommand(flags, x4, save_player, save_uniq_player, save_hash, create != 0); }); patch->Hook(bw::Command_GameData, Command_GameData); patch->Hook(bw::InitGame, InitGame); patch->Hook(bw::InitStartingRacesAndTypes, InitStartingRacesAndTypes); patch->Hook(bw::NeutralizePlayer, [](uint8_t player) { Neutralize(player); }); patch->Hook(bw::MakeDetected, MakeDetected_Hook); patch->Hook(bw::AddDamageOverlay, &Sprite::AddDamageOverlay); patch->Hook(bw::GameScreenRClickEvent, GameScreenRClickEvent); patch->Hook(bw::GameScreenLClickEvent_Targeting, GameScreenLClickEvent_Targeting); patch->Hook(bw::DoTargetedCommand, [](uint16_t x, uint16_t y, Unit *target, uint16_t fow_unit) { DoTargetedCommand(x, y, target, UnitType(fow_unit)); }); patch->Hook(bw::SendChangeSelectionCommand, SendChangeSelectionCommand); patch->Hook(bw::CenterOnSelectionGroup, CenterOnSelectionGroup); patch->Hook(bw::SelectHotkeyGroup, SelectHotkeyGroup); patch->Hook(bw::Command_SaveHotkeyGroup, [](uint8_t group, int create) { Command_SaveHotkeyGroup(group, create == 0); }); patch->Hook(bw::Command_SelectHotkeyGroup, Command_LoadHotkeyGroup); patch->Hook(bw::TrySelectRecentHotkeyGroup, TrySelectRecentHotkeyGroup); patch->Hook(bw::ProcessCommands, ProcessCommands); patch->Hook(bw::ReplayCommands_Nothing, [](const void *) {}); patch->Hook(bw::UpdateBuildingPlacementState, [](Unit *a, int b, int c, int d, uint16_t e, int f, int g, int h, int i) { return UpdateBuildingPlacementState(a, b, c, d, UnitType(e), f, g, h, i); }); patch->Hook(bw::PlaySelectionSound, PlaySelectionSound); patch->Hook(bw::InitResourceAreas, InitResourceAreas); patch->Hook(bw::Ai_RepairSomething, &Unit::Ai_RepairSomething); }
36.992424
118
0.665452
neivv
983c1b878efed132e65028ff5e1119bce5e830f9
3,608
cpp
C++
hphp/compiler/statement/class_constant.cpp
kkopachev/hhvm
a9f242ec029c37b1e9d1715b13661e66293d87ab
[ "PHP-3.01", "Zend-2.0" ]
2
2019-09-01T19:40:10.000Z
2019-10-18T13:30:30.000Z
hphp/compiler/statement/class_constant.cpp
alisha/hhvm
523dc33b444bd5b59695eff2b64056629b0ed523
[ "PHP-3.01", "Zend-2.0" ]
1
2018-12-16T15:39:15.000Z
2018-12-16T15:39:16.000Z
hphp/compiler/statement/class_constant.cpp
alisha/hhvm
523dc33b444bd5b59695eff2b64056629b0ed523
[ "PHP-3.01", "Zend-2.0" ]
1
2020-12-30T13:22:47.000Z
2020-12-30T13:22:47.000Z
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/compiler/statement/class_constant.h" #include "hphp/compiler/analysis/analysis_result.h" #include "hphp/compiler/expression/expression_list.h" #include "hphp/compiler/expression/constant_expression.h" #include "hphp/compiler/analysis/class_scope.h" #include "hphp/compiler/expression/assignment_expression.h" #include "hphp/compiler/expression/class_constant_expression.h" #include "hphp/compiler/expression/scalar_expression.h" #include "hphp/compiler/option.h" #include "hphp/compiler/type_annotation.h" using namespace HPHP; /////////////////////////////////////////////////////////////////////////////// // constructors/destructors ClassConstant::ClassConstant (STATEMENT_CONSTRUCTOR_PARAMETERS, std::string typeConstraint, ExpressionListPtr exp, bool abstract, bool typeconst, TypeAnnotationPtr typeAnnot) : Statement(STATEMENT_CONSTRUCTOR_PARAMETER_VALUES(ClassConstant)), m_typeConstraint(typeConstraint), m_exp(exp), m_abstract(abstract), m_typeconst(typeconst) { // for now only store TypeAnnotation info for type constants if (typeconst && typeAnnot) { m_typeStructure = Array(typeAnnot->getScalarArrayRep()); assertx(m_typeStructure.isDictOrDArray()); } } StatementPtr ClassConstant::clone() { ClassConstantPtr stmt(new ClassConstant(*this)); stmt->m_exp = Clone(m_exp); return stmt; } /////////////////////////////////////////////////////////////////////////////// // parser functions void ClassConstant::onParseRecur(AnalysisResultConstRawPtr /*ar*/, FileScopeRawPtr fs, ClassScopePtr scope) { if (scope->isTrait()) { parseTimeFatal(fs, "Traits cannot have constants"); } } /////////////////////////////////////////////////////////////////////////////// // static analysis functions ConstructPtr ClassConstant::getNthKid(int n) const { switch (n) { case 0: return m_exp; default: assert(false); break; } return ConstructPtr(); } int ClassConstant::getKidCount() const { return 1; } void ClassConstant::setNthKid(int n, ConstructPtr cp) { switch (n) { case 0: m_exp = dynamic_pointer_cast<ExpressionList>(cp); break; default: assert(false); break; } } /////////////////////////////////////////////////////////////////////////////// // code generation functions void ClassConstant::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) { if (isAbstract()) { cg_printf("abstract "); } cg_printf("const "); if (isTypeconst()) { cg_printf("type "); } m_exp->outputPHP(cg, ar); cg_printf(";\n"); }
33.719626
79
0.561253
kkopachev
983d4a9a9f304a7d065a213220ce7e29bd7c02fc
1,147
cpp
C++
csapex_vision_features/src/register_plugin.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
2
2016-09-02T15:33:22.000Z
2019-05-06T22:09:33.000Z
csapex_vision_features/src/register_plugin.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
1
2021-02-14T19:53:30.000Z
2021-02-14T19:53:30.000Z
csapex_vision_features/src/register_plugin.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
6
2016-10-12T00:55:23.000Z
2021-02-10T17:49:25.000Z
/// HEADER #include "register_plugin.h" /// COMPONENT #include <csapex/factory/generic_node_factory.hpp> #include <csapex/factory/node_factory_impl.h> #include <csapex/msg/generic_value_message.hpp> #include <csapex_vision_features/descriptor_message.h> #include <csapex_vision_features/keypoint_message.h> /// PROJECT #include <csapex/factory/message_factory.h> #include <csapex/model/tag.h> #include <csapex_opencv/yaml_io.hpp> /// SYSTEM #include <csapex/utility/register_apex_plugin.h> CSAPEX_REGISTER_CLASS(csapex::RegisterVisionFeaturePlugin, csapex::CorePlugin) using namespace csapex; RegisterVisionFeaturePlugin::RegisterVisionFeaturePlugin() { } void rotateKeypoint(const connection_types::GenericValueMessage<cv::KeyPoint>& input, connection_types::GenericValueMessage<cv::KeyPoint>& output) { output = input; } void RegisterVisionFeaturePlugin::init(CsApexCore& core) { Tag::createIfNotExists("Features"); auto c = GenericNodeFactory::createConstructorFromFunction(rotateKeypoint, "rotateKeypoint"); c->setDescription("Test function for rotating a keypoint"); core.getNodeFactory()->registerNodeType(c); }
28.675
146
0.79599
AdrianZw
983f46aeeba033a9d84c6d7faeb1e26484552933
7,369
cpp
C++
QTDialogs/SceneEditorTab/SceneEditorTab.cpp
msolids/musen
67d9a70d03d771ccda649c21b78d165684e31171
[ "BSD-3-Clause" ]
19
2020-09-28T07:22:50.000Z
2022-03-07T09:52:20.000Z
QTDialogs/SceneEditorTab/SceneEditorTab.cpp
LasCondes/musen
18961807928285ff802e050050f4c627dd7bec1e
[ "BSD-3-Clause" ]
5
2020-12-26T18:18:27.000Z
2022-02-23T22:56:43.000Z
QTDialogs/SceneEditorTab/SceneEditorTab.cpp
LasCondes/musen
18961807928285ff802e050050f4c627dd7bec1e
[ "BSD-3-Clause" ]
11
2020-11-02T11:32:03.000Z
2022-01-27T08:22:04.000Z
/* Copyright (c) 2013-2020, MUSEN Development Team. All rights reserved. This file is part of MUSEN framework http://msolids.net/musen. See LICENSE file for license and warranty information. */ #include "SceneEditorTab.h" #include <QMessageBox> CSceneEditorTab::CSceneEditorTab(QWidget *parent /*= 0*/) : CMusenDialog(parent) { ui.setupUi(this); QVector<QWidget*> labels; labels.push_back(ui.setCenterOfMass); labels.push_back(ui.labelRotation); labels.push_back(ui.labelAngle); labels.push_back(ui.labelOffset); labels.push_back(ui.labelVelocity); int maxWidth = (*std::max_element(labels.begin(), labels.end(), [](const QWidget* l, const QWidget* r) { return (l->width() < r->width()); }))->width(); for (QWidget* w : labels) w->setFixedWidth(maxWidth); m_bAllowUndoFunction = false; connect(ui.rotateSystem, &QPushButton::clicked, this, &CSceneEditorTab::RotateSystem); connect(ui.undoRotation, &QPushButton::clicked, this, &CSceneEditorTab::UndoRotation); connect(ui.setCenterOfMass, &QPushButton::clicked, this, &CSceneEditorTab::SetCenterOfMass); connect(ui.moveSystem, &QPushButton::clicked, this, &CSceneEditorTab::MoveSystem); connect(ui.setVelocity, &QPushButton::clicked, this, &CSceneEditorTab::SetVelocity); connect(ui.groupBoxPBC, &QGroupBox::toggled, this, &CSceneEditorTab::SetPBC); connect(ui.checkBoxPBCX, &QCheckBox::stateChanged, this, &CSceneEditorTab::SetPBC); connect(ui.checkBoxPBCY, &QCheckBox::stateChanged, this, &CSceneEditorTab::SetPBC); connect(ui.checkBoxPBCZ, &QCheckBox::stateChanged, this, &CSceneEditorTab::SetPBC); connect(ui.lineEditPBCMinX, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC); connect(ui.lineEditPBCMinY, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC); connect(ui.lineEditPBCMinZ, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC); connect(ui.lineEditPBCMaxX, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC); connect(ui.lineEditPBCMaxY, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC); connect(ui.lineEditPBCMaxZ, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC); connect(ui.lineEditVelocityX, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC); connect(ui.lineEditVelocityY, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC); connect(ui.lineEditVelocityZ, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC); connect(ui.checkBoxAnisotropy, &QCheckBox::stateChanged, this, &CSceneEditorTab::SetAnisotropy); connect(ui.checkBoxContactRadius, &QCheckBox::stateChanged, this, &CSceneEditorTab::SetContactRadius); } void CSceneEditorTab::setVisible( bool _bVisible ) { if (!_bVisible) m_bAllowUndoFunction = false; CMusenDialog::setVisible(_bVisible); } void CSceneEditorTab::UpdateWholeView() { ui.undoRotation->setEnabled(m_bAllowUndoFunction); ShowConvLabel(ui.labelCenterX, "X", EUnitType::LENGTH); ShowConvLabel(ui.labelCenterY, "Y", EUnitType::LENGTH); ShowConvLabel(ui.labelCenterZ, "Z", EUnitType::LENGTH); ShowConvLabel(ui.labelOffsetX, "X", EUnitType::LENGTH); ShowConvLabel(ui.labelOffsetY, "Y", EUnitType::LENGTH); ShowConvLabel(ui.labelOffsetZ, "Z", EUnitType::LENGTH); ShowConvLabel(ui.labelVelocityX, "Vx", EUnitType::VELOCITY); ShowConvLabel(ui.labelVelocityY, "Vy", EUnitType::VELOCITY); ShowConvLabel(ui.labelVelocityZ, "Vz", EUnitType::VELOCITY); ShowConvLabel(ui.labelPBCMin, "Min", EUnitType::LENGTH); ShowConvLabel(ui.labelPBCMax, "Max", EUnitType::LENGTH); ShowConvLabel(ui.labelPBCVel, "Velocity", EUnitType::VELOCITY); UpdatePBC(); ui.checkBoxAnisotropy->setChecked(m_pSystemStructure->IsAnisotropyEnabled()); ui.checkBoxContactRadius->setChecked(m_pSystemStructure->IsContactRadiusEnabled()); } void CSceneEditorTab::SetCenterOfMass() { ShowConvValue(ui.lineEditCenterX, ui.lineEditCenterY, ui.lineEditCenterZ, m_pSystemStructure->GetCenterOfMass(0), EUnitType::LENGTH); } void CSceneEditorTab::RotateSystem() { m_RotationCenter = GetConvValue(ui.lineEditCenterX, ui.lineEditCenterY, ui.lineEditCenterZ, EUnitType::LENGTH); m_RotationAngle = GetConvValue(ui.lineEditAngleX, ui.lineEditAngleY, ui.lineEditAngleZ, EUnitType::NONE ) * PI / 180; m_pSystemStructure->ClearAllStatesFrom(0); m_pSystemStructure->RotateSystem(0, m_RotationCenter, m_RotationAngle); m_bAllowUndoFunction = true; UpdateWholeView(); emit UpdateOpenGLView(); } void CSceneEditorTab::MoveSystem() { m_pSystemStructure->ClearAllStatesFrom(0); m_pSystemStructure->MoveSystem(0, GetConvValue(ui.lineEditOffsetX, ui.lineEditOffsetY, ui.lineEditOffsetZ, EUnitType::LENGTH)); UpdateWholeView(); emit UpdateOpenGLView(); } void CSceneEditorTab::SetVelocity() { m_pSystemStructure->ClearAllStatesFrom(0); m_pSystemStructure->SetSystemVelocity(0, GetConvValue(ui.lineEditVelocityX, ui.lineEditVelocityY, ui.lineEditVelocityZ, EUnitType::VELOCITY)); UpdateWholeView(); emit UpdateOpenGLView(); } void CSceneEditorTab::UndoRotation() { m_pSystemStructure->RotateSystem(0, m_RotationCenter, m_RotationAngle * (-1)); UpdateWholeView(); emit UpdateOpenGLView(); } void CSceneEditorTab::SetPBC() { if (m_bAvoidSignal) return; if (m_pSystemStructure->GetNumberOfSpecificObjects(SOLID_BOND) != 0) QMessageBox::information(this, ("Bonds over PBC"), ("Modification of PBC will influence existing solid bonds!"), QMessageBox::Ok); SPBC pbcNew; pbcNew.bEnabled = ui.groupBoxPBC->isChecked(); pbcNew.bX = ui.checkBoxPBCX->isChecked(); pbcNew.bY = ui.checkBoxPBCY->isChecked(); pbcNew.bZ = ui.checkBoxPBCZ->isChecked(); pbcNew.SetDomain(GetConvValue(ui.lineEditPBCMinX, ui.lineEditPBCMinY, ui.lineEditPBCMinZ, EUnitType::LENGTH), GetConvValue(ui.lineEditPBCMaxX, ui.lineEditPBCMaxY, ui.lineEditPBCMaxZ, EUnitType::LENGTH)); pbcNew.vVel = GetConvValue(ui.lineEditVelX, ui.lineEditVelY, ui.lineEditVelZ, EUnitType::VELOCITY); m_pSystemStructure->SetPBC(pbcNew); UpdateWholeView(); emit UpdateOpenGLView(); } void CSceneEditorTab::UpdatePBC() { m_bAvoidSignal = true; const SPBC& pbc = m_pSystemStructure->GetPBC(); ui.groupBoxPBC->setChecked(pbc.bEnabled); ShowConvValue( ui.lineEditPBCMinX, ui.lineEditPBCMinY, ui.lineEditPBCMinZ, pbc.initDomain.coordBeg, EUnitType::LENGTH); ShowConvValue( ui.lineEditPBCMaxX, ui.lineEditPBCMaxY, ui.lineEditPBCMaxZ, pbc.initDomain.coordEnd, EUnitType::LENGTH); ShowConvValue( ui.lineEditVelX, ui.lineEditVelY, ui.lineEditVelZ, pbc.vVel, EUnitType::VELOCITY); ui.checkBoxPBCX->setChecked(pbc.bX); ui.lineEditPBCMinX->setEnabled(pbc.bX && pbc.bEnabled); ui.lineEditPBCMaxX->setEnabled(pbc.bX && pbc.bEnabled); ui.lineEditVelX->setEnabled(pbc.bX && pbc.bEnabled); ui.checkBoxPBCY->setChecked(pbc.bY); ui.lineEditPBCMinY->setEnabled(pbc.bY && pbc.bEnabled); ui.lineEditPBCMaxY->setEnabled(pbc.bY && pbc.bEnabled); ui.lineEditVelY->setEnabled(pbc.bY && pbc.bEnabled); ui.checkBoxPBCZ->setChecked(pbc.bZ); ui.lineEditPBCMinZ->setEnabled(pbc.bZ && pbc.bEnabled); ui.lineEditPBCMaxZ->setEnabled(pbc.bZ && pbc.bEnabled); ui.lineEditVelZ->setEnabled(pbc.bZ && pbc.bEnabled); m_bAvoidSignal = false; } void CSceneEditorTab::SetAnisotropy() { m_pSystemStructure->EnableAnisotropy(ui.checkBoxAnisotropy->isChecked()); } void CSceneEditorTab::SetContactRadius() { m_pSystemStructure->EnableContactRadius(ui.checkBoxContactRadius->isChecked()); emit ContactRadiusEnabled(); }
41.398876
204
0.780703
msolids
9846bd5882d147f78ebdab29031e533a267552fb
567
hpp
C++
include/Pomdog/Async/ImmediateScheduler.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
include/Pomdog/Async/ImmediateScheduler.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
include/Pomdog/Async/ImmediateScheduler.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #ifndef POMDOG_IMMEDIATESCHEDULER_6ABB0F4A_HPP #define POMDOG_IMMEDIATESCHEDULER_6ABB0F4A_HPP #include "Pomdog/Async/Scheduler.hpp" namespace Pomdog { namespace Concurrency { class POMDOG_EXPORT ImmediateScheduler final : public Scheduler { public: void Schedule( std::function<void()> && task, const Duration& delayTime) override; }; } // namespace Concurrency } // namespace Pomdog #endif // POMDOG_IMMEDIATESCHEDULER_6ABB0F4A_HPP
24.652174
70
0.767196
bis83