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
c41d7aab2e06c08b50d323d766b88a3ea35d1d02
2,206
cpp
C++
src/main.cpp
qualibit/rtspmjpegclient
9bf7f4cfa0223fc573d41727f6d9f29e3254f297
[ "Apache-2.0" ]
4
2017-01-17T21:32:01.000Z
2018-10-23T13:53:54.000Z
src/main.cpp
qualibit/rtspmjpegclient
9bf7f4cfa0223fc573d41727f6d9f29e3254f297
[ "Apache-2.0" ]
null
null
null
src/main.cpp
qualibit/rtspmjpegclient
9bf7f4cfa0223fc573d41727f6d9f29e3254f297
[ "Apache-2.0" ]
3
2016-08-08T10:15:48.000Z
2022-01-24T23:49:53.000Z
/* * Copyright 2016 Qualibit S.r.l. * * 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 <fstream> #include <string> #include <chrono> #include <thread> #include "rtspmjpegclient_interface.hpp" #define TEST_ADDRESS "rtsp://192.168.1.54/live/mjpeg" #define TEST_FRAME_NUM 10 #define TEST_FRAME_PER_LOOP 2 int main() { rtspmjpegclient_start_log("", ""); rtspmjpegclient_start(0, TEST_ADDRESS, 1); int nframe = 0; RTSPMJPEGClientData *data = new RTSPMJPEGClientData; while (nframe < TEST_FRAME_NUM) { rtspmjpegclient_log_state(0); data->state = rtspmjpegclient_get_state(0); if (data->state != RTSPMJPEGCLIENT_STATE_LOOPING) { if (data->state < RTSPMJPEGCLIENT_STATE_INITIALIZING) rtspmjpegclient_start(0, TEST_ADDRESS, 1); std::this_thread::sleep_for(std::chrono::seconds(1)); continue; } if (rtspmjpegclient_wait(0) != 0) continue; rtspmjpegclient_get_data(0, TEST_FRAME_PER_LOOP, 0, data); rtspmjpegclient_resume(0); for (int i = 0; i < data->framesRead; i++) { std::string name = "test"; name += std::to_string(static_cast<long long>(nframe)); name += ".jpg"; std::ofstream(name, std::ios::binary).write((char * ) &data->frameQueue[i * RTSPMJPEGCLIENT_FRAME_BUFFER_SIZE], data->frameSizes[i]); nframe++; } std::this_thread::sleep_for(std::chrono::seconds(2)); } rtspmjpegclient_stop(0); delete data; rtspmjpegclient_stop_log(); return 0; }
27.575
146
0.631006
qualibit
c41dcc28c49ee68785c31c5f2555636781bc4a1f
761
hpp
C++
core/database/driver/postgresql/DatabaseClientStorageDriver.hpp
PlatformerTeam/mad
8768e3127a0659f1d831dcb6c96ba2bb71c30795
[ "MIT" ]
2
2022-02-21T08:23:02.000Z
2022-03-17T10:01:40.000Z
core/database/driver/postgresql/DatabaseClientStorageDriver.hpp
PlatformerTeam/mad
8768e3127a0659f1d831dcb6c96ba2bb71c30795
[ "MIT" ]
43
2022-02-21T13:07:08.000Z
2022-03-22T11:02:16.000Z
core/database/driver/postgresql/DatabaseClientStorageDriver.hpp
PlatformerTeam/mad
8768e3127a0659f1d831dcb6c96ba2bb71c30795
[ "MIT" ]
null
null
null
#ifndef MAD_DATABASECLIENTSTORAGEDRIVER_H #define MAD_DATABASECLIENTSTORAGEDRIVER_H #include <database/database/Database.hpp> #include <database/driver/ClientStorageDriver.hpp> #include <memory> namespace mad::core { class DatabaseClientStorageDriver : public ClientStorageDriver { public: explicit DatabaseClientStorageDriver(std::shared_ptr<Database> database); bool log_in(const std::string &username) const override; bool sign_up(const std::string &username) override; std::size_t get_progress() const override; void update_progress() override; private: std::shared_ptr<Database> m_database; mutable std::string m_username; }; } #endif//MAD_DATABASECLIENTSTORAGEDRIVER_H
22.382353
81
0.735874
PlatformerTeam
c41f8a54cceda8db9841d384ad84a63c76144dbd
823
cpp
C++
src/xr_3da/xrGame/object_property_evaluator_state.cpp
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:19.000Z
2022-03-26T17:00:19.000Z
src/xr_3da/xrGame/object_property_evaluator_state.cpp
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
null
null
null
src/xr_3da/xrGame/object_property_evaluator_state.cpp
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:21.000Z
2022-03-26T17:00:21.000Z
//////////////////////////////////////////////////////////////////////////// // Module : object_property_evaluator_state.cpp // Created : 13.03.2004 // Modified : 13.03.2004 // Author : Dmitriy Iassenev // Description : Object state property evaluator //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "object_property_evaluator_state.h" #include "weapon.h" CObjectPropertyEvaluatorState::CObjectPropertyEvaluatorState (CWeapon *item, CAI_Stalker *owner, u32 state, bool equality) : inherited (item,owner), m_state (state), m_equality (equality) { } CObjectPropertyEvaluatorState::_value_type CObjectPropertyEvaluatorState::evaluate () { VERIFY (m_item); return (_value_type((m_item->STATE == m_state) == m_equality)); }
32.92
125
0.589307
ixray-team
c421ce1aaf686b93c1d71ff6ebbf47695c2f34df
34,793
cpp
C++
src/navier_stokes/INSStaggeredPPMConvectiveOperator.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
2
2017-12-06T06:16:36.000Z
2021-03-13T12:28:08.000Z
src/navier_stokes/INSStaggeredPPMConvectiveOperator.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
null
null
null
src/navier_stokes/INSStaggeredPPMConvectiveOperator.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
null
null
null
// Filename: INSStaggeredPPMConvectiveOperator.cpp // Created on 08 May 2008 by Boyce Griffith // // Copyright (c) 2002-2013, Boyce Griffith // 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 New York University nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. /////////////////////////////// INCLUDES ///////////////////////////////////// #include <stddef.h> #include <ostream> #include "Box.h" #include "CartesianPatchGeometry.h" #include "FaceData.h" #include "IBAMR_config.h" #include "INSStaggeredPPMConvectiveOperator.h" #include "Index.h" #include "IntVector.h" #include "Patch.h" #include "PatchLevel.h" #include "SAMRAIVectorReal.h" #include "SAMRAI_config.h" #include "SideData.h" #include "SideGeometry.h" #include "Variable.h" #include "VariableContext.h" #include "VariableDatabase.h" #include "blitz/tinyvec2.h" #include "ibamr/ibamr_utilities.h" #include "ibamr/namespaces.h" // IWYU pragma: keep #include "tbox/Timer.h" #include "tbox/TimerManager.h" #include "tbox/Utilities.h" namespace SAMRAI { namespace solv { template <int DIM> class RobinBcCoefStrategy; } // namespace solv } // namespace SAMRAI // FORTRAN ROUTINES #if (NDIM == 2) #define ADVECT_DERIVATIVE_FC FC_FUNC_(advect_derivative2d, ADVECT_DERIVATIVE2D) #define CONVECT_DERIVATIVE_FC FC_FUNC_(convect_derivative2d, CONVECT_DERIVATIVE2D) #define GODUNOV_EXTRAPOLATE_FC FC_FUNC_(godunov_extrapolate2d, GODUNOV_EXTRAPOLATE2D) #define NAVIER_STOKES_INTERP_COMPS_FC FC_FUNC_(navier_stokes_interp_comps2d, NAVIER_STOKES_INTERP_COMPS2D) #define NAVIER_STOKES_RESET_ADV_VELOCITY_FC FC_FUNC_(navier_stokes_reset_adv_velocity2d, NAVIER_STOKES_RESET_ADV_VELOCITY2D) #define SKEW_SYM_DERIVATIVE_FC FC_FUNC_(skew_sym_derivative2d, SKEW_SYM_DERIVATIVE2D) #endif #if (NDIM == 3) #define ADVECT_DERIVATIVE_FC FC_FUNC_(advect_derivative3d, ADVECT_DERIVATIVE3D) #define CONVECT_DERIVATIVE_FC FC_FUNC_(convect_derivative3d, CONVECT_DERIVATIVE3D) #define GODUNOV_EXTRAPOLATE_FC FC_FUNC_(godunov_extrapolate3d, GODUNOV_EXTRAPOLATE3D) #define NAVIER_STOKES_INTERP_COMPS_FC FC_FUNC_(navier_stokes_interp_comps3d, NAVIER_STOKES_INTERP_COMPS3D) #define NAVIER_STOKES_RESET_ADV_VELOCITY_FC FC_FUNC_(navier_stokes_reset_adv_velocity3d, NAVIER_STOKES_RESET_ADV_VELOCITY3D) #define SKEW_SYM_DERIVATIVE_FC FC_FUNC_(skew_sym_derivative3d, SKEW_SYM_DERIVATIVE3D) #endif extern "C" { void ADVECT_DERIVATIVE_FC( const double*, #if (NDIM == 2) const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const double* , const double* , const double* , const double* , const int& , const int& , #endif #if (NDIM == 3) const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const double* , const double* , const double* , const double* , const double* , const double* , const int& , const int& , const int& , #endif double* ); void CONVECT_DERIVATIVE_FC( const double*, #if (NDIM == 2) const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const double* , const double* , const double* , const double* , const int& , const int& , #endif #if (NDIM == 3) const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const double* , const double* , const double* , const double* , const double* , const double* , const int& , const int& , const int& , #endif double* ); void GODUNOV_EXTRAPOLATE_FC( #if (NDIM == 2) const int& , const int& , const int& , const int& , const int& , const int& , const double* , double* , double* , double* , double* , const int& , const int& , const int& , const int& , const double* , const double* , double* , double* #endif #if (NDIM == 3) const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const double* , double* , double* , double* , double* , double* , const int& , const int& , const int& , const int& , const int& , const int& , const double* , const double* , const double* , double* , double* , double* #endif ); void NAVIER_STOKES_INTERP_COMPS_FC( #if (NDIM == 2) const int& , const int& , const int& , const int& , const int& , const int& , const double* , const double* , const int& , const int& , const int& , const int& , const int& , const int& , double* , double* , const int& , const int& , const int& , const int& , const int& , const int& , double* , double* #endif #if (NDIM == 3) const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const double* , const double* , const double* , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , double* , double* , double* , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , double* , double* , double* , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , double* , double* , double* #endif ); void NAVIER_STOKES_RESET_ADV_VELOCITY_FC( #if (NDIM == 2) const int& , const int& , const int& , const int& , const int& , const int& , double* , double* , const int& , const int& , const double* , const double* , const int& , const int& , const int& , const int& , const int& , const int& , double* , double* , const int& , const int& , const double* , const double* #endif #if (NDIM == 3) const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , double* , double* , double* , const int& , const int& , const int& , const double* , const double* , const double* , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , double* , double* , double* , const int& , const int& , const int& , const double* , const double* , const double* , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , double* , double* , double* , const int& , const int& , const int& , const double* , const double* , const double* #endif ); void SKEW_SYM_DERIVATIVE_FC( const double*, #if (NDIM == 2) const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const double* , const double* , const double* , const double* , const int& , const int& , #endif #if (NDIM == 3) const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const int& , const double* , const double* , const double* , const double* , const double* , const double* , const int& , const int& , const int& , #endif double* ); } /////////////////////////////// NAMESPACE //////////////////////////////////// namespace IBAMR { /////////////////////////////// STATIC /////////////////////////////////////// namespace { // NOTE: The number of ghost cells required by the Godunov advection scheme // depends on the order of the reconstruction. These values were chosen to work // with xsPPM7 (the modified piecewise parabolic method of Rider, Greenough, and // Kamm). static const int GADVECTG = 4; // Timers. static Timer* t_apply_convective_operator; static Timer* t_apply; static Timer* t_initialize_operator_state; static Timer* t_deallocate_operator_state; } /////////////////////////////// PUBLIC /////////////////////////////////////// INSStaggeredPPMConvectiveOperator::INSStaggeredPPMConvectiveOperator( const std::string& object_name, Pointer<Database> input_db, const ConvectiveDifferencingType difference_form, const std::vector<RobinBcCoefStrategy<NDIM>*>& bc_coefs) : ConvectiveOperator(object_name, difference_form), d_bc_coefs(bc_coefs), d_bdry_extrap_type("CONSTANT"), d_hierarchy(NULL), d_coarsest_ln(-1), d_finest_ln(-1), d_U_var(NULL), d_U_scratch_idx(-1) { if (d_difference_form != ADVECTIVE && d_difference_form != CONSERVATIVE && d_difference_form != SKEW_SYMMETRIC) { TBOX_ERROR("INSStaggeredPPMConvectiveOperator::INSStaggeredPPMConvectiveOperator():\n" << " unsupported differencing form: " << enum_to_string<ConvectiveDifferencingType>(d_difference_form) << " \n" << " valid choices are: ADVECTIVE, CONSERVATIVE, SKEW_SYMMETRIC\n"); } if (input_db) { if (input_db->keyExists("bdry_extrap_type")) d_bdry_extrap_type = input_db->getString("bdry_extrap_type"); } VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase(); Pointer<VariableContext> context = var_db->getContext("INSStaggeredPPMConvectiveOperator::CONTEXT"); const std::string U_var_name = "INSStaggeredPPMConvectiveOperator::U"; d_U_var = var_db->getVariable(U_var_name); if (d_U_var) { d_U_scratch_idx = var_db->mapVariableAndContextToIndex(d_U_var, context); } else { d_U_var = new SideVariable<NDIM,double>(U_var_name); d_U_scratch_idx = var_db->registerVariableAndContext(d_U_var, context, IntVector<NDIM>(GADVECTG)); } #ifdef DEBUG_CHECK_ASSERTIONS TBOX_ASSERT(d_U_scratch_idx >= 0); #endif // Setup Timers. IBAMR_DO_ONCE( t_apply_convective_operator = TimerManager::getManager()->getTimer("IBAMR::INSStaggeredPPMConvectiveOperator::applyConvectiveOperator()"); t_apply = TimerManager::getManager()->getTimer("IBAMR::INSStaggeredPPMConvectiveOperator::apply()"); t_initialize_operator_state = TimerManager::getManager()->getTimer("IBAMR::INSStaggeredPPMConvectiveOperator::initializeOperatorState()"); t_deallocate_operator_state = TimerManager::getManager()->getTimer("IBAMR::INSStaggeredPPMConvectiveOperator::deallocateOperatorState()"); ); return; }// INSStaggeredPPMConvectiveOperator INSStaggeredPPMConvectiveOperator::~INSStaggeredPPMConvectiveOperator() { deallocateOperatorState(); return; }// ~INSStaggeredPPMConvectiveOperator void INSStaggeredPPMConvectiveOperator::applyConvectiveOperator( const int U_idx, const int N_idx) { IBAMR_TIMER_START(t_apply_convective_operator); #ifdef DEBUG_CHECK_ASSERTIONS if (!d_is_initialized) { TBOX_ERROR("INSStaggeredPPMConvectiveOperator::applyConvectiveOperator():\n" << " operator must be initialized prior to call to applyConvectiveOperator\n"); } TBOX_ASSERT(U_idx == d_u_idx); #endif // Fill ghost cell values for all components. static const bool homogeneous_bc = false; typedef HierarchyGhostCellInterpolation::InterpolationTransactionComponent InterpolationTransactionComponent; std::vector<InterpolationTransactionComponent> transaction_comps(1); transaction_comps[0] = InterpolationTransactionComponent(d_U_scratch_idx, U_idx, "CONSERVATIVE_LINEAR_REFINE", false, "CONSERVATIVE_COARSEN", d_bdry_extrap_type, false, d_bc_coefs); d_hier_bdry_fill->resetTransactionComponents(transaction_comps); d_hier_bdry_fill->setHomogeneousBc(homogeneous_bc); StaggeredStokesPhysicalBoundaryHelper::setupBcCoefObjects(d_bc_coefs, NULL, d_U_scratch_idx, -1, homogeneous_bc); d_hier_bdry_fill->fillData(d_solution_time); StaggeredStokesPhysicalBoundaryHelper::resetBcCoefObjects(d_bc_coefs, NULL); d_bc_helper->enforceDivergenceFreeConditionAtBoundary(d_U_scratch_idx); d_hier_bdry_fill->resetTransactionComponents(d_transaction_comps); // Compute the convective derivative. for (int ln = d_coarsest_ln; ln <= d_finest_ln; ++ln) { Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln); for (PatchLevel<NDIM>::Iterator p(level); p; p++) { Pointer<Patch<NDIM> > patch = level->getPatch(p()); const Pointer<CartesianPatchGeometry<NDIM> > patch_geom = patch->getPatchGeometry(); const double* const dx = patch_geom->getDx(); const Box<NDIM>& patch_box = patch->getBox(); const IntVector<NDIM>& patch_lower = patch_box.lower(); const IntVector<NDIM>& patch_upper = patch_box.upper(); Pointer<SideData<NDIM,double> > N_data = patch->getPatchData(N_idx); Pointer<SideData<NDIM,double> > U_data = patch->getPatchData(d_U_scratch_idx); const IntVector<NDIM> ghosts = IntVector<NDIM>(1); blitz::TinyVector<Box<NDIM>,NDIM> side_boxes; blitz::TinyVector<Pointer<FaceData<NDIM,double> >,NDIM> U_adv_data; blitz::TinyVector<Pointer<FaceData<NDIM,double> >,NDIM> U_half_data; for (unsigned int axis = 0; axis < NDIM; ++axis) { side_boxes [axis] = SideGeometry<NDIM>::toSideBox(patch_box,axis); U_adv_data [axis] = new FaceData<NDIM,double>(side_boxes[axis],1,ghosts); U_half_data[axis] = new FaceData<NDIM,double>(side_boxes[axis],1,ghosts); } #if (NDIM == 2) NAVIER_STOKES_INTERP_COMPS_FC( patch_lower(0), patch_upper(0), patch_lower(1), patch_upper(1), U_data->getGhostCellWidth()(0), U_data->getGhostCellWidth()(1), U_data->getPointer(0), U_data->getPointer(1), side_boxes[0].lower(0), side_boxes[0].upper(0), side_boxes[0].lower(1), side_boxes[0].upper(1), U_adv_data[0]->getGhostCellWidth()(0), U_adv_data[0]->getGhostCellWidth()(1), U_adv_data[0]->getPointer(0), U_adv_data[0]->getPointer(1), side_boxes[1].lower(0), side_boxes[1].upper(0), side_boxes[1].lower(1), side_boxes[1].upper(1), U_adv_data[1]->getGhostCellWidth()(0), U_adv_data[1]->getGhostCellWidth()(1), U_adv_data[1]->getPointer(0), U_adv_data[1]->getPointer(1)); #endif #if (NDIM == 3) NAVIER_STOKES_INTERP_COMPS_FC( patch_lower(0), patch_upper(0), patch_lower(1), patch_upper(1), patch_lower(2), patch_upper(2), U_data->getGhostCellWidth()(0), U_data->getGhostCellWidth()(1), U_data->getGhostCellWidth()(2), U_data->getPointer(0), U_data->getPointer(1), U_data->getPointer(2), side_boxes[0].lower(0), side_boxes[0].upper(0), side_boxes[0].lower(1), side_boxes[0].upper(1), side_boxes[0].lower(2), side_boxes[0].upper(2), U_adv_data[0]->getGhostCellWidth()(0), U_adv_data[0]->getGhostCellWidth()(1), U_adv_data[0]->getGhostCellWidth()(2), U_adv_data[0]->getPointer(0), U_adv_data[0]->getPointer(1), U_adv_data[0]->getPointer(2), side_boxes[1].lower(0), side_boxes[1].upper(0), side_boxes[1].lower(1), side_boxes[1].upper(1), side_boxes[1].lower(2), side_boxes[1].upper(2), U_adv_data[1]->getGhostCellWidth()(0), U_adv_data[1]->getGhostCellWidth()(1), U_adv_data[1]->getGhostCellWidth()(2), U_adv_data[1]->getPointer(0), U_adv_data[1]->getPointer(1), U_adv_data[1]->getPointer(2), side_boxes[2].lower(0), side_boxes[2].upper(0), side_boxes[2].lower(1), side_boxes[2].upper(1), side_boxes[2].lower(2), side_boxes[2].upper(2), U_adv_data[2]->getGhostCellWidth()(0), U_adv_data[2]->getGhostCellWidth()(1), U_adv_data[2]->getGhostCellWidth()(2), U_adv_data[2]->getPointer(0), U_adv_data[2]->getPointer(1), U_adv_data[2]->getPointer(2)); #endif for (unsigned int axis = 0; axis < NDIM; ++axis) { Pointer<SideData<NDIM,double> > dU_data = new SideData<NDIM,double>(U_data->getBox(), U_data->getDepth(), U_data->getGhostCellWidth()); Pointer<SideData<NDIM,double> > U_L_data = new SideData<NDIM,double>(U_data->getBox(), U_data->getDepth(), U_data->getGhostCellWidth()); Pointer<SideData<NDIM,double> > U_R_data = new SideData<NDIM,double>(U_data->getBox(), U_data->getDepth(), U_data->getGhostCellWidth()); Pointer<SideData<NDIM,double> > U_scratch1_data = new SideData<NDIM,double>(U_data->getBox(), U_data->getDepth(), U_data->getGhostCellWidth()); #if (NDIM == 3) Pointer<SideData<NDIM,double> > U_scratch2_data = new SideData<NDIM,double>(U_data->getBox(), U_data->getDepth(), U_data->getGhostCellWidth()); #endif #if (NDIM == 2) GODUNOV_EXTRAPOLATE_FC( side_boxes[axis].lower(0), side_boxes[axis].upper(0), side_boxes[axis].lower(1), side_boxes[axis].upper(1), U_data->getGhostCellWidth()(0), U_data->getGhostCellWidth()(1), U_data ->getPointer(axis), U_scratch1_data->getPointer(axis), dU_data ->getPointer(axis), U_L_data ->getPointer(axis), U_R_data->getPointer(axis), U_adv_data [axis]->getGhostCellWidth()(0), U_adv_data [axis]->getGhostCellWidth()(1), U_half_data[axis]->getGhostCellWidth()(0), U_half_data[axis]->getGhostCellWidth()(1), U_adv_data [axis]->getPointer(0), U_adv_data [axis]->getPointer(1), U_half_data[axis]->getPointer(0), U_half_data[axis]->getPointer(1)); #endif #if (NDIM == 3) GODUNOV_EXTRAPOLATE_FC( side_boxes[axis].lower(0), side_boxes[axis].upper(0), side_boxes[axis].lower(1), side_boxes[axis].upper(1), side_boxes[axis].lower(2), side_boxes[axis].upper(2), U_data->getGhostCellWidth()(0), U_data->getGhostCellWidth()(1), U_data->getGhostCellWidth()(2), U_data ->getPointer(axis), U_scratch1_data->getPointer(axis), U_scratch2_data->getPointer(axis), dU_data ->getPointer(axis), U_L_data ->getPointer(axis), U_R_data ->getPointer(axis), U_adv_data [axis]->getGhostCellWidth()(0), U_adv_data [axis]->getGhostCellWidth()(1), U_adv_data [axis]->getGhostCellWidth()(2), U_half_data[axis]->getGhostCellWidth()(0), U_half_data[axis]->getGhostCellWidth()(1), U_half_data[axis]->getGhostCellWidth()(2), U_adv_data [axis]->getPointer(0), U_adv_data [axis]->getPointer(1), U_adv_data [axis]->getPointer(2), U_half_data[axis]->getPointer(0), U_half_data[axis]->getPointer(1), U_half_data[axis]->getPointer(2)); #endif } #if (NDIM == 2) NAVIER_STOKES_RESET_ADV_VELOCITY_FC( side_boxes[0].lower(0), side_boxes[0].upper(0), side_boxes[0].lower(1), side_boxes[0].upper(1), U_adv_data [0]->getGhostCellWidth()(0), U_adv_data [0]->getGhostCellWidth()(1), U_adv_data [0]->getPointer(0), U_adv_data [0]->getPointer(1), U_half_data[0]->getGhostCellWidth()(0), U_half_data[0]->getGhostCellWidth()(1), U_half_data[0]->getPointer(0), U_half_data[0]->getPointer(1), side_boxes[1].lower(0), side_boxes[1].upper(0), side_boxes[1].lower(1), side_boxes[1].upper(1), U_adv_data [1]->getGhostCellWidth()(0), U_adv_data [1]->getGhostCellWidth()(1), U_adv_data [1]->getPointer(0), U_adv_data [1]->getPointer(1), U_half_data[1]->getGhostCellWidth()(0), U_half_data[1]->getGhostCellWidth()(1), U_half_data[1]->getPointer(0), U_half_data[1]->getPointer(1)); #endif #if (NDIM == 3) NAVIER_STOKES_RESET_ADV_VELOCITY_FC( side_boxes[0].lower(0), side_boxes[0].upper(0), side_boxes[0].lower(1), side_boxes[0].upper(1), side_boxes[0].lower(2), side_boxes[0].upper(2), U_adv_data [0]->getGhostCellWidth()(0), U_adv_data [0]->getGhostCellWidth()(1), U_adv_data [0]->getGhostCellWidth()(2), U_adv_data [0]->getPointer(0), U_adv_data [0]->getPointer(1), U_adv_data [0]->getPointer(2), U_half_data[0]->getGhostCellWidth()(0), U_half_data[0]->getGhostCellWidth()(1), U_half_data[0]->getGhostCellWidth()(2), U_half_data[0]->getPointer(0), U_half_data[0]->getPointer(1), U_half_data[0]->getPointer(2), side_boxes[1].lower(0), side_boxes[1].upper(0), side_boxes[1].lower(1), side_boxes[1].upper(1), side_boxes[1].lower(2), side_boxes[1].upper(2), U_adv_data [1]->getGhostCellWidth()(0), U_adv_data [1]->getGhostCellWidth()(1), U_adv_data [1]->getGhostCellWidth()(2), U_adv_data [1]->getPointer(0), U_adv_data [1]->getPointer(1), U_adv_data [1]->getPointer(2), U_half_data[1]->getGhostCellWidth()(0), U_half_data[1]->getGhostCellWidth()(1), U_half_data[1]->getGhostCellWidth()(2), U_half_data[1]->getPointer(0), U_half_data[1]->getPointer(1), U_half_data[1]->getPointer(2), side_boxes[2].lower(0), side_boxes[2].upper(0), side_boxes[2].lower(1), side_boxes[2].upper(1), side_boxes[2].lower(2), side_boxes[2].upper(2), U_adv_data [2]->getGhostCellWidth()(0), U_adv_data [2]->getGhostCellWidth()(1), U_adv_data [2]->getGhostCellWidth()(2), U_adv_data [2]->getPointer(0), U_adv_data [2]->getPointer(1), U_adv_data [2]->getPointer(2), U_half_data[2]->getGhostCellWidth()(0), U_half_data[2]->getGhostCellWidth()(1), U_half_data[2]->getGhostCellWidth()(2), U_half_data[2]->getPointer(0), U_half_data[2]->getPointer(1), U_half_data[2]->getPointer(2)); #endif for (unsigned int axis = 0; axis < NDIM; ++axis) { switch (d_difference_form) { case CONSERVATIVE: #if (NDIM == 2) CONVECT_DERIVATIVE_FC( dx, side_boxes[axis].lower(0), side_boxes[axis].upper(0), side_boxes[axis].lower(1), side_boxes[axis].upper(1), U_adv_data [axis]->getGhostCellWidth()(0), U_adv_data [axis]->getGhostCellWidth()(1), U_half_data[axis]->getGhostCellWidth()(0), U_half_data[axis]->getGhostCellWidth()(1), U_adv_data [axis]->getPointer(0), U_adv_data [axis]->getPointer(1), U_half_data[axis]->getPointer(0), U_half_data[axis]->getPointer(1), N_data->getGhostCellWidth()(0), N_data->getGhostCellWidth()(1), N_data->getPointer(axis)); #endif #if (NDIM == 3) CONVECT_DERIVATIVE_FC( dx, side_boxes[axis].lower(0), side_boxes[axis].upper(0), side_boxes[axis].lower(1), side_boxes[axis].upper(1), side_boxes[axis].lower(2), side_boxes[axis].upper(2), U_adv_data [axis]->getGhostCellWidth()(0), U_adv_data [axis]->getGhostCellWidth()(1), U_adv_data [axis]->getGhostCellWidth()(2), U_half_data[axis]->getGhostCellWidth()(0), U_half_data[axis]->getGhostCellWidth()(1), U_half_data[axis]->getGhostCellWidth()(2), U_adv_data [axis]->getPointer(0), U_adv_data [axis]->getPointer(1), U_adv_data [axis]->getPointer(2), U_half_data[axis]->getPointer(0), U_half_data[axis]->getPointer(1), U_half_data[axis]->getPointer(2), N_data->getGhostCellWidth()(0), N_data->getGhostCellWidth()(1), N_data->getGhostCellWidth()(2), N_data->getPointer(axis)); #endif break; case ADVECTIVE: #if (NDIM == 2) ADVECT_DERIVATIVE_FC( dx, side_boxes[axis].lower(0), side_boxes[axis].upper(0), side_boxes[axis].lower(1), side_boxes[axis].upper(1), U_adv_data [axis]->getGhostCellWidth()(0), U_adv_data [axis]->getGhostCellWidth()(1), U_half_data[axis]->getGhostCellWidth()(0), U_half_data[axis]->getGhostCellWidth()(1), U_adv_data [axis]->getPointer(0), U_adv_data [axis]->getPointer(1), U_half_data[axis]->getPointer(0), U_half_data[axis]->getPointer(1), N_data->getGhostCellWidth()(0), N_data->getGhostCellWidth()(1), N_data->getPointer(axis)); #endif #if (NDIM == 3) ADVECT_DERIVATIVE_FC( dx, side_boxes[axis].lower(0), side_boxes[axis].upper(0), side_boxes[axis].lower(1), side_boxes[axis].upper(1), side_boxes[axis].lower(2), side_boxes[axis].upper(2), U_adv_data [axis]->getGhostCellWidth()(0), U_adv_data [axis]->getGhostCellWidth()(1), U_adv_data [axis]->getGhostCellWidth()(2), U_half_data[axis]->getGhostCellWidth()(0), U_half_data[axis]->getGhostCellWidth()(1), U_half_data[axis]->getGhostCellWidth()(2), U_adv_data [axis]->getPointer(0), U_adv_data [axis]->getPointer(1), U_adv_data [axis]->getPointer(2), U_half_data[axis]->getPointer(0), U_half_data[axis]->getPointer(1), U_half_data[axis]->getPointer(2), N_data->getGhostCellWidth()(0), N_data->getGhostCellWidth()(1), N_data->getGhostCellWidth()(2), N_data->getPointer(axis)); #endif break; case SKEW_SYMMETRIC: #if (NDIM == 2) SKEW_SYM_DERIVATIVE_FC( dx, side_boxes[axis].lower(0), side_boxes[axis].upper(0), side_boxes[axis].lower(1), side_boxes[axis].upper(1), U_adv_data [axis]->getGhostCellWidth()(0), U_adv_data [axis]->getGhostCellWidth()(1), U_half_data[axis]->getGhostCellWidth()(0), U_half_data[axis]->getGhostCellWidth()(1), U_adv_data [axis]->getPointer(0), U_adv_data [axis]->getPointer(1), U_half_data[axis]->getPointer(0), U_half_data[axis]->getPointer(1), N_data->getGhostCellWidth()(0), N_data->getGhostCellWidth()(1), N_data->getPointer(axis)); #endif #if (NDIM == 3) SKEW_SYM_DERIVATIVE_FC( dx, side_boxes[axis].lower(0), side_boxes[axis].upper(0), side_boxes[axis].lower(1), side_boxes[axis].upper(1), side_boxes[axis].lower(2), side_boxes[axis].upper(2), U_adv_data [axis]->getGhostCellWidth()(0), U_adv_data [axis]->getGhostCellWidth()(1), U_adv_data [axis]->getGhostCellWidth()(2), U_half_data[axis]->getGhostCellWidth()(0), U_half_data[axis]->getGhostCellWidth()(1), U_half_data[axis]->getGhostCellWidth()(2), U_adv_data [axis]->getPointer(0), U_adv_data [axis]->getPointer(1), U_adv_data [axis]->getPointer(2), U_half_data[axis]->getPointer(0), U_half_data[axis]->getPointer(1), U_half_data[axis]->getPointer(2), N_data->getGhostCellWidth()(0), N_data->getGhostCellWidth()(1), N_data->getGhostCellWidth()(2), N_data->getPointer(axis)); #endif break; default: TBOX_ERROR("INSStaggeredPPMConvectiveOperator::applyConvectiveOperator():\n" << " unsupported differencing form: " << enum_to_string<ConvectiveDifferencingType>(d_difference_form) << " \n" << " valid choices are: ADVECTIVE, CONSERVATIVE, SKEW_SYMMETRIC\n"); } } } } IBAMR_TIMER_STOP(t_apply_convective_operator); return; }// applyConvectiveOperator void INSStaggeredPPMConvectiveOperator::initializeOperatorState( const SAMRAIVectorReal<NDIM,double>& in, const SAMRAIVectorReal<NDIM,double>& out) { IBAMR_TIMER_START(t_initialize_operator_state); if (d_is_initialized) deallocateOperatorState(); // Get the hierarchy configuration. d_hierarchy = in.getPatchHierarchy(); d_coarsest_ln = in.getCoarsestLevelNumber(); d_finest_ln = in.getFinestLevelNumber(); #ifdef DEBUG_CHECK_ASSERTIONS TBOX_ASSERT(d_hierarchy == out.getPatchHierarchy()); TBOX_ASSERT(d_coarsest_ln == out.getCoarsestLevelNumber()); TBOX_ASSERT(d_finest_ln == out.getFinestLevelNumber()); #else NULL_USE(out); #endif // Setup the interpolation transaction information. typedef HierarchyGhostCellInterpolation::InterpolationTransactionComponent InterpolationTransactionComponent; d_transaction_comps.resize(1); d_transaction_comps[0] = InterpolationTransactionComponent(d_U_scratch_idx, in.getComponentDescriptorIndex(0), "CONSERVATIVE_LINEAR_REFINE", false, "CONSERVATIVE_COARSEN", d_bdry_extrap_type, false, d_bc_coefs); // Initialize the interpolation operators. d_hier_bdry_fill = new HierarchyGhostCellInterpolation(); d_hier_bdry_fill->initializeOperatorState(d_transaction_comps, d_hierarchy); // Initialize the BC helper. d_bc_helper = new StaggeredStokesPhysicalBoundaryHelper(); d_bc_helper->cacheBcCoefData(d_bc_coefs, d_solution_time, d_hierarchy); // Allocate scratch data. for (int ln = d_coarsest_ln; ln <= d_finest_ln; ++ln) { Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln); if (!level->checkAllocated(d_U_scratch_idx)) { level->allocatePatchData(d_U_scratch_idx); } } d_is_initialized = true; IBAMR_TIMER_STOP(t_initialize_operator_state); return; }// initializeOperatorState void INSStaggeredPPMConvectiveOperator::deallocateOperatorState() { if (!d_is_initialized) return; IBAMR_TIMER_START(t_deallocate_operator_state); // Deallocate scratch data. for (int ln = d_coarsest_ln; ln <= d_finest_ln; ++ln) { Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln); if (level->checkAllocated(d_U_scratch_idx)) { level->deallocatePatchData(d_U_scratch_idx); } } // Deallocate the communications operators and BC helpers. d_hier_bdry_fill.setNull(); d_bc_helper.setNull(); d_is_initialized = false; IBAMR_TIMER_STOP(t_deallocate_operator_state); return; }// deallocateOperatorState /////////////////////////////// PROTECTED //////////////////////////////////// /////////////////////////////// PRIVATE ////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// }// namespace IBAMR //////////////////////////////////////////////////////////////////////////////
51.166176
215
0.596528
MSV-Project
c424eb398a132292d30dc8d022db6250f5def7f5
2,610
hxx
C++
include/kry/NKPF.hxx
rcgoodfellow/kry
29b0616d92c514b015eab4a93ad2c2c04d412190
[ "BSD-2-Clause" ]
null
null
null
include/kry/NKPF.hxx
rcgoodfellow/kry
29b0616d92c514b015eab4a93ad2c2c04d412190
[ "BSD-2-Clause" ]
null
null
null
include/kry/NKPF.hxx
rcgoodfellow/kry
29b0616d92c514b015eab4a93ad2c2c04d412190
[ "BSD-2-Clause" ]
null
null
null
/****************************************************************************** * libKrylov * ========= * NKPF.hxx * * This file contains definitions pertaining to Newton-Krylov power flow * * 21 August 2014 * ~ ry * ***************************************************************************/ #ifndef KRY_NKPF_HXX #define KRY_NKPF_HXX #include "kry/Math.hxx" #include <iostream> #include <fstream> #include <sstream> namespace kry { class NKPF; struct jidx; struct jidx { jidx(int j0, int j1); int j0{-1}, j1{-1}; }; struct JacobiMap { size_t j0_sz{0}, j1_sz{0}; std::vector<jidx> map; size_t size(); }; class NKPF { public: NKPF(SparseMatrix Y, SparseMatrix YA, JacobiMap jmap, size_t n, Vector initial, Vector ps); size_t N, n; //system size, projected size Matrix Q, //Subspace Projector H; //Hessenburg Reduction Vector ve, //voltage estimate dve, //voltage delta estimate ps, //scheduled power pc, //calculated power dp, //power delta dv0, //voltage delta initial guess dr0, //initial residual of the Jacobean system qdp, //projected power delta qdv, //projected voltage delta Jdv; //Jacobi approximation double dr0_norm; SparseMatrix Y, //admittance matrix magnitudes YA, //admittance matrix angles J; //Jacobi JacobiMap jmap; //map bus indices onto Jacobi indices //the power flow equations double p(size_t), q(size_t); /* power gradient functions -----------------------------------------------------*/ //real-power gradient double jdp(size_t), jdp_va(size_t), jdp_v(size_t), dp_dva(size_t, size_t), dp_dv(size_t, size_t); //reactive-power gradient double jdq(size_t), jdq_va(size_t), jdq_v(size_t), dq_dva(size_t, size_t), dq_dv(size_t, size_t); /*---------------------------------------------------*/ //accessors for voltage magnitude and angle double v(size_t), va(size_t); //accessors for voltage delta magnitude and angle double dv(size_t), dva(size_t); //conductance and susceptance per bus double g(size_t), b(size_t); void compute_pc(); void compute_dp(); void compute_dve(); void compute_Jdv(); void build_Jacobi(); void j11(); void j22(); void j21(); void j12(); NKPF & operator()(); void update_ve(); std::string show_state(); }; } #endif
21.932773
79
0.53295
rcgoodfellow
c425a4871b41fa9e0f298c677ff122bef96b4f2a
2,038
hpp
C++
src/mainwindow.hpp
Leonardo2718/tffm
a0d96331af5d7e9710fd115e050c9c46bbe536ea
[ "MIT" ]
null
null
null
src/mainwindow.hpp
Leonardo2718/tffm
a0d96331af5d7e9710fd115e050c9c46bbe536ea
[ "MIT" ]
null
null
null
src/mainwindow.hpp
Leonardo2718/tffm
a0d96331af5d7e9710fd115e050c9c46bbe536ea
[ "MIT" ]
null
null
null
/* Project: tffm Author: Leonardo Banderali Description: tffm is a simple, keyboard-centric file manager intended for use with tiling window managers such as Xmonad. License: MIT License Copyright (c) 2016 Leonardo Banderali Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef MAINWINDOW_HPP #define MAINWINDOW_HPP #include <memory> #include <QMainWindow> #include <QVBoxLayout> #include <QListView> #include <QString> #include "filemanager.hpp" #include "inputline.hpp" #include "keybindingtable.hpp" namespace tffm { class MainWindow; } class tffm::MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget* parent = nullptr); signals: private: tffm::KeyBindingTable _keyBindings; std::unique_ptr<QWidget> _centralWidget; std::unique_ptr<QVBoxLayout> _mainLayout; std::unique_ptr<FileManager> _fileManager; std::unique_ptr<InputLine> _inputLine; }; #endif // MAINWINDOW_HPP
30.41791
82
0.740432
Leonardo2718
c42c84124be57a284d9291df2f555b55d5a6c701
531
cc
C++
hackerrank/algorithms/warmup/mini-max-sum.cc
andrewcpacifico/programming
bbbd16d41d34ea7316e207b8a82ae76377d80420
[ "Apache-2.0" ]
null
null
null
hackerrank/algorithms/warmup/mini-max-sum.cc
andrewcpacifico/programming
bbbd16d41d34ea7316e207b8a82ae76377d80420
[ "Apache-2.0" ]
null
null
null
hackerrank/algorithms/warmup/mini-max-sum.cc
andrewcpacifico/programming
bbbd16d41d34ea7316e207b8a82ae76377d80420
[ "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2015 - Andrew C. Pacifico - All Rights Reserved. * @author Andrew C. Pacifico <andrewcpacifico@gmail.com> */ #include <stdio.h> int main(int argc, char *argv[]) { long long v[5], i, sum = 0, min, max; for (i = 0; i < 5; i++) { scanf("%lld", &v[i]); sum += v[i]; } min = max = sum - v[0]; for (i = 1; i < 5; i++) { if (sum - v[i] < min) min = sum - v[i]; if (sum - v[i] > max) max = sum - v[i]; } printf("%lld %lld", min, max); return 0; }
20.423077
65
0.468927
andrewcpacifico
c42d40ecfdefeedf5dd42741837f8072a5e0f749
307
hpp
C++
zen/hash_map.hpp
ZenLibraries/ZenLibraries
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
[ "Apache-2.0" ]
null
null
null
zen/hash_map.hpp
ZenLibraries/ZenLibraries
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
[ "Apache-2.0" ]
2
2020-02-06T17:01:39.000Z
2020-02-12T17:50:14.000Z
zen/hash_map.hpp
ZenLibraries/ZenLibraries
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
[ "Apache-2.0" ]
null
null
null
#ifndef ZEN_HASH_MAP_HPP #define ZEN_HASH_MAP_HPP #include <stddef.h> #include "zen/allocator.hpp" ZEN_NAMESPACE_START template< typename T, typename SizeT = size_t, typename AllocatorT = DefaultAllocator<T> > class HashMap { public: }; ZEN_NAMESPACE_END #endif // of #ifndef ZEN_HASH_MAP_HPP
12.791667
43
0.762215
ZenLibraries
c42d75928f352e1e11884d4961afb5350f5d1c76
1,539
tpp
C++
queue/queue.tpp
gefjon/data_structures
9bf9f35272e168ffc7ffb30fa44e87761773b845
[ "MIT" ]
null
null
null
queue/queue.tpp
gefjon/data_structures
9bf9f35272e168ffc7ffb30fa44e87761773b845
[ "MIT" ]
null
null
null
queue/queue.tpp
gefjon/data_structures
9bf9f35272e168ffc7ffb30fa44e87761773b845
[ "MIT" ]
null
null
null
namespace Queue { template< class T > bool Queue< T >::head_is_defined() { return (this->head_) ? true : false; } template< class T > bool Queue< T >::tail_is_defined() { return (this->tail_) ? true : false; } template< class T > void Queue< T >::assert_defined() { assert(this->head_is_defined()); assert(this->tail_is_defined()); } template< class T > Queue< T >::Queue() {}; template< class T > Queue< T >::Queue(const Queue< T >& other) = default; template< class T > Queue< T >::~Queue() = default; template< class T > void Queue< T >::Enqueue(T to_enqueue) { auto node = std::make_shared< LinkedList::Node< T > >(std::move(to_enqueue)); if (this->length_ == 0) { this->head_ = node; this->tail_ = node; } else { this->assert_defined(); this->tail_->next_ = node; this->tail_ = node; } this->length_ += 1; } template< class T > T Queue< T >::Dequeue() { if (this->length_ == 0) { throw new UnderflowException(); } this->assert_defined(); this->length_ -= 1; auto new_head = this->head_->Cdr(); T to_return = std::move(this->head_->Car()); this->head_ = new_head; return to_return; } template< class T > T& Queue< T >::Peek() { if (this->length_ == 0) { throw new UnderflowException(); } this->assert_defined(); return this->head_->Car(); } template< class T > unsigned int Queue< T >::Length() { return this->length_; } }
21.082192
81
0.566602
gefjon
c42e8ce16db9537241f8671f542ec8e84911d132
11,884
cpp
C++
VST3 SDK/base/source/frect.cpp
jagilley/MrsWatson
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
[ "BSD-2-Clause" ]
2
2019-06-14T10:20:30.000Z
2020-02-19T17:53:42.000Z
VST3 SDK/base/source/frect.cpp
jagilley/MrsWatson
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
[ "BSD-2-Clause" ]
null
null
null
VST3 SDK/base/source/frect.cpp
jagilley/MrsWatson
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
[ "BSD-2-Clause" ]
1
2021-03-16T13:02:17.000Z
2021-03-16T13:02:17.000Z
//------------------------------------------------------------------------ // Project : SDK Base // Version : 1.0 // // Category : Helpers // Filename : base/source/frect.cpp // Created by : Steinberg, 1995 // Description : // //----------------------------------------------------------------------------- // LICENSE // (c) 2016, Steinberg Media Technologies GmbH, All Rights Reserved //----------------------------------------------------------------------------- // This Software Development Kit may not be distributed in parts or its entirety // without prior written agreement by Steinberg Media Technologies GmbH. // This SDK must not be used to re-engineer or manipulate any technology used // in any Steinberg or Third-party application or software module, // unless permitted by law. // Neither the name of the Steinberg Media Technologies nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SDK IS PROVIDED BY STEINBERG MEDIA TECHNOLOGIES GMBH "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 STEINBERG MEDIA TECHNOLOGIES GMBH 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 "base/source/frect.h" #include "pluginterfaces/gui/iplugview.h" // ViewRect #include "pluginterfaces/base/futils.h" namespace Steinberg { //------------------------------------------------------------------------------ // Rect //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ Rect::Rect (const ViewRect& vr) : left (vr.left), top (vr.top), right (vr.right), bottom (vr.bottom) {} //------------------------------------------------------------------------------ Rect& Rect::moveTo (const Point& where) { UCoord vDiff = where.v - top; UCoord hDiff = where.h - left; top += vDiff; bottom += vDiff; left += hDiff; right += hDiff; return *this; } //------------------------------------------------------------------------------ bool Rect::pointInside (const Point& where) const { return where.h >= left && where.h < right && where.v >= top && where.v < bottom; } //------------------------------------------------------------------------------ Rect& Rect::inset (UCoord delta) { top += delta; left += delta; bottom -= delta; right -= delta; return *this; } //------------------------------------------------------------------------------ Rect& Rect::inset (UCoord deltaH, UCoord deltaV) { top += deltaV; left += deltaH; bottom -= deltaV; right -= deltaH; return *this; } //------------------------------------------------------------------------------ Rect& Rect::inset (UCoord deltaL, UCoord deltaT, UCoord deltaR, UCoord deltaB) { top += deltaT; left += deltaL; bottom -= deltaB; right -= deltaR; return *this; } //------------------------------------------------------------------------------ bool Rect::slideInside (const Rect& rect) { UCoord w = getWidth(); UCoord h = getHeight(); // basic rejection conditions if ( ( w > rect.getWidth() ) || ( h > rect.getHeight() ) ) return false; if ( left < rect.left ) { left = rect.left; right = left + w; } else if ( right > rect.right ) { right = rect.right; left = right - w; } if ( top < rect.top ) { top = rect.top; bottom = top + h; } else if ( bottom > rect.bottom ) { bottom = rect.bottom; top = bottom - h; } return true; } //------------------------------------------------------------------------------ bool Rect::join (const Rect& rect) { if (isEmpty ()) { if (rect.isEmpty ()) return false; *this = rect; return true; } else if (rect.isEmpty ()) return false; return joinEvenIfEmpty (rect); } //------------------------------------------------------------------------ bool Rect::joinEvenIfEmpty (const Rect& rect) { if (rect.top < top) top = rect.top; if (rect.left < left) left = rect.left; if (rect.right > right) right = rect.right; if (rect.bottom > bottom) bottom = rect.bottom; return ! (right <= left) && ! (bottom <= top); } //------------------------------------------------------------------------------ Rect& Rect::center (const Rect& rect) { centerH (rect); return centerV (rect); } //------------------------------------------------------------------------------ Rect& Rect::centerH (const Rect& rect) { UCoord width = getWidth (); left = rect.left + ((rect.getWidth () - getWidth ()) / 2); right = left + width; return *this; } //------------------------------------------------------------------------------ Rect& Rect::centerV (const Rect& rect) { UCoord height = getHeight (); top = rect.top + ((rect.getHeight () - getHeight ()) / 2); bottom = top + height; return *this; } //------------------------------------------------------------------------------ bool Rect::isEmpty () const { if (right <= left) return true; if (bottom <= top) return true; return false; } //------------------------------------------------------------------------------ bool Rect::rectInside (const Rect& rect) const { return rect.left >= left && rect.top >= top && rect.right <= right && rect.bottom <= bottom; } //------------------------------------------------------------------------------ bool Rect::rectIntersect (const Rect& rect ) const { UCoord x1, y1, x2, y2; x1 = left > rect.left ? left : rect.left; x2 = right < rect.right ? right : rect.right; y1 = top > rect.top ? top : rect.top; y2 = bottom < rect.bottom ? bottom : rect.bottom; // return (x1 < x2 && y1 < y2); // Right-Bottom Excluded return (x1 <= x2 && y1 <= y2); // Included } //------------------------------------------------------------------------------ bool Rect::rectIntersect (const Rect& rect, Rect& result) const { UCoord x1, y1, x2, y2; result.left = x1 = left > rect.left ? left : rect.left; result.right = x2 = right < rect.right ? right : rect.right; result.top = y1 = top > rect.top ? top : rect.top; result.bottom = y2 = bottom < rect.bottom ? bottom : rect.bottom; if ((x1 <= x2 && y1 <= y2) ) // Right-Bottom Included // Right-Bottom Excluded == (x1 < x2 && y1 < y2) return true; result ( 0, 0, 0, 0 ); return false; } //------------------------------------------------------------------------------ bool Rect::overlapHorizontal (const Rect& rect) const { return (Max (left, rect.left) <= Min (right, rect.right)); } //------------------------------------------------------------------------------ bool Rect::overlapVertical (const Rect& rect) const { return (Max (top, rect.top) <= Min (bottom, rect.bottom)); } //------------------------------------------------------------------------------ UCoord Rect::getOverlapHorizontal (const Rect& r2) const { return Max<UCoord> (0, Min (right, r2.right) - Max (left, r2.left)); } //------------------------------------------------------------------------------ UCoord Rect::getOverlapVertical (const Rect& r2) const { return Max<UCoord> (0, Min (bottom, r2.bottom) - Max (top, r2.top)); } //------------------------------------------------------------------------------ bool Rect::subtract (const Rect& rect) { if (rect.rectInside (*this)) { set (0,0,0,0); return false; } Rect r (*this); r.bound (rect); if (!r.isEmpty ()) { if (r.getWidth () >= getWidth ()) { if (r.top > top) bottom = r.top; else if (r.bottom < bottom) top = r.bottom; } if (r.getHeight () >= getHeight ()) { if (r.left > left) right = r.left; else if (r.right < right) left = r.right; } } return isEmpty () == false; } //------------------------------------------------------------------------------ Point& Rect::constrain (Point& p) const { if (p.h < left) p.h = left; if (p.h > right) p.h = right; if (p.v < top) p.v = top; if (p.v > bottom) p.v = bottom; return p; } //------------------------------------------------------------------------------ bool Rect::lineInside (const Point& p1, const Point& p2) const { return pointInside (p1) && pointInside (p2); } //------------------------------------------------------------------------------ bool Rect::lineIntersect (const Point& _p1, const Point& _p2) const { Point p1 (_p1); Point p2 (_p2); return boundLine (p1,p2); } //------------------------------------------------------------------------ // clipping of line //------------------------------------------------------------------------ // Liang-Barsky algorithm //------------------------------------------------------------------------------ static inline bool boundLineClipTest (double p, double q, double *u1, double *u2) { double r; bool retval = true; if (p < 0.0) { r = q / p; if (r > *u2) retval = false; else if (r > *u1) *u1 = r; } else if (p > 0.0) { r = q / p; if (r < * u1) retval = false; else if (r < *u2) *u2 = r; } else if (q < 0.0) { retval = false; } return retval; } //------------------------------------------------------------------------------ bool Rect::boundLine (Point& p1, Point& p2) const { if (pointInside (p1) && pointInside (p2)) return true; double u1 = 0.0; double u2 = 1.0; double dx = p2.h - p1.h; double dy; if (boundLineClipTest (-dx, p1.h - left, &u1, &u2)) { if (boundLineClipTest (dx, right - p1.h, &u1, &u2)) { dy = p2.v - p1.v; if (boundLineClipTest (-dy, p1.v - top, &u1, &u2)) { if (boundLineClipTest (dy, bottom - p1.v, &u1, &u2)) { if (u2 < 1.0) { p2.h = p1.h + (UCoord)(u2 * dx); p2.v = p1.v + (UCoord)(u2 * dy); } if (u1 > 0.0) { p1.h += (UCoord)(u1 * dx); p1.v += (UCoord)(u1 * dy); } return true; } } } } return false; } //------------------------------------------------------------------------------ ViewRect& Rect::toViewRect (ViewRect& vr) const { vr.left = left; vr.top = top; vr.right = right; vr.bottom = bottom; return vr; } //------------------------------------------------------------------------------ void Rect::fromViewRect (const ViewRect& vr) { left = vr.left; top = vr.top; right = vr.right; bottom = vr.bottom; } //------------------------------------------------------------------------------ Rect& Rect::operator = (const ViewRect& vr) { fromViewRect (vr); return *this; } //------------------------------------------------------------------------------ Rect::operator ViewRect () const { return ViewRect (left, top, right, bottom); } //------------------------------------------------------------------------ Point& Rect::toPoint (Direction dir, Point& p) const { switch (dir) { case kSouthWest: return p = getBottomLeft (); case kWest: return p = getLeftCenter (); case kNorthWest: return p = getTopLeft (); case kNorth: return p = getTopCenter (); case kNorthEast: return p = getTopRight (); case kEast: return p = getRightCenter (); case kSouthEast: return p = getBottomRight (); case kSouth: return p = getBottomCenter (); case kNoDirection: return p = getCenter (); } return p; } } // namespace Steinberg
26.408889
107
0.460114
jagilley
c430c5eab260ab5743bf2c493423163886d36cc8
11,543
cpp
C++
src/parser.cpp
amSangi/SimpleInterpreter
cbfcfccbe7740f3853e6d108264eb228843932c5
[ "MIT" ]
null
null
null
src/parser.cpp
amSangi/SimpleInterpreter
cbfcfccbe7740f3853e6d108264eb228843932c5
[ "MIT" ]
null
null
null
src/parser.cpp
amSangi/SimpleInterpreter
cbfcfccbe7740f3853e6d108264eb228843932c5
[ "MIT" ]
null
null
null
#include <sstream> #include <iostream> #include "parser.h" using std::make_shared; using std::shared_ptr; using std::vector; using std::string; Parser::Parser(const string& filename) : lexer_(filename), current_token_(InvalidToken), next_token_(InvalidToken) { current_token_ = lexer_.GetNext(); next_token_ = lexer_.GetNext(); } shared_ptr<Program> Parser::Parse() { auto program = make_shared<Program>(); if (lexer_.FailedToOpen()) { RecordError("Failed to open the file"); return program; } // Parse function declarations while (lexer_.HasNext() && next_token_.GetType() != MainKeyword) { program->AddFuncDecl(ConsumeFunctionDecl()); } program->SetMain(ConsumeMain()); Expect(EndOfFileToken); return program; } const vector<string> &Parser::GetErrors() const { return errors_; } /*********** Functions ***********/ shared_ptr<FunctionDecl> Parser::ConsumeMain() { auto main = make_shared<FunctionDecl>(); Expect(NumberKeyword); main->SetReturnType(make_shared<NumType>()); Expect(MainKeyword); main->SetId(make_shared<Identifier>("main")); Expect(OpenParanToken); Expect(CloseParanToken); Expect(OpenBraceToken); // Parse statements while (lexer_.HasNext() && current_token_.GetType() != CloseBraceToken && current_token_.GetType() != EndOfFileToken) { main->AddStm(ConsumeStatement()); } Expect(CloseBraceToken); return main; } shared_ptr<FunctionDecl> Parser::ConsumeFunctionDecl() { auto fun_decl = make_shared<FunctionDecl>(); auto type = ConsumeStaticType(); fun_decl->SetReturnType(type); fun_decl->SetId(ConsumeIdentifier()); Expect(OpenParanToken); // Parse formal arguments while (lexer_.HasNext() && (current_token_.GetType() == BoolKeyword || current_token_.GetType() == VoidKeyword || current_token_.GetType() == NumberKeyword)) { fun_decl->AddFormal(ConsumeFunctionParam()); if (current_token_.GetType() == CommaToken) { NextToken(); } } Expect(CloseParanToken); Expect(OpenBraceToken); // Parse statements while (lexer_.HasNext() && current_token_.GetType() != CloseBraceToken) { fun_decl->AddStm(ConsumeStatement()); } Expect(CloseBraceToken); return fun_decl; } shared_ptr<FunctionParam> Parser::ConsumeFunctionParam() { auto param = make_shared<FunctionParam>(); param->SetType(ConsumeStaticType()); param->SetName(ConsumeIdentifier()); return param; } /*********** Statements ***********/ shared_ptr<Statement> Parser::ConsumeStatement() { shared_ptr<Statement> stm; switch (current_token_.GetType()) { case OpenBraceToken: stm = ConsumeBlock(); break; case IfKeyword: stm = ConsumeIf(); break; case WhileKeyword: stm = ConsumeWhile(); break; case NumberKeyword: stm = ConsumeVarDecl(); Expect(SemiColonToken); break; case BoolKeyword: stm = ConsumeVarDecl(); Expect(SemiColonToken); break; case ReturnKeyword: stm = ConsumeReturnStm(); Expect(SemiColonToken); break; case IdentifierToken: stm = ConsumeAssignment(); Expect(SemiColonToken); break; default: NextToken(); return nullptr; } return stm; } shared_ptr<Block> Parser::ConsumeBlock() { auto block = make_shared<Block>(); Expect(OpenBraceToken); while (lexer_.HasNext() && current_token_.GetType() != CloseBraceToken) { block->AddStatement(ConsumeStatement()); } Expect(CloseBraceToken); return block; } shared_ptr<ReturnStm> Parser::ConsumeReturnStm() { auto return_stm = make_shared<ReturnStm>(); Expect(ReturnKeyword); if (current_token_.GetType() != SemiColonToken) { return_stm->SetExpression(ConsumeExpression()); } return return_stm; } shared_ptr<IfThenElse> Parser::ConsumeIf() { auto if_then_else = make_shared<IfThenElse>(); Expect(IfKeyword); Expect(OpenParanToken); if_then_else->SetPredicate(ConsumeExpression()); Expect(CloseParanToken); // Parse then block if_then_else->SetThen(ConsumeBlock()); // Parse else block - if one exists if (Accept(ElseKeyword)) { if_then_else->SetElse(ConsumeBlock()); } return if_then_else; } shared_ptr<While> Parser::ConsumeWhile() { auto while_node = make_shared<While>(); Expect(WhileKeyword); Expect(OpenParanToken); // Parse predicate while_node->SetPredicate(ConsumeExpression()); Expect(CloseParanToken); while_node->SetBlock(ConsumeBlock()); return while_node; } shared_ptr<VarDecl> Parser::ConsumeVarDecl() { auto var_decl = make_shared<VarDecl>(); var_decl->SetType(ConsumeStaticType()); var_decl->SetId(ConsumeIdentifier()); return var_decl; } shared_ptr<Assignment> Parser::ConsumeAssignment() { auto assign = make_shared<Assignment>(); auto id = ConsumeIdentifier(); Expect(EqualToken); auto exp = ConsumeExpression(); assign->SetLValue(id); assign->SetRValue(exp); return assign; } /*********** Expressions ***********/ shared_ptr<Expression> Parser::ConsumeExpression() { return ConsumeAndOrExpression(); } shared_ptr<Expression> Parser::ConsumeAndOrExpression() { auto and_or = make_shared<BinaryOp>(); auto left_exp = ConsumeComparison(); bool is_and = current_token_.GetType() == DoubleAmpersandToken; bool is_or = current_token_.GetType() == DoubleBarToken; if (!is_and && !is_or) return left_exp; and_or->SetOperator(AND); if (is_or) and_or->SetOperator(OR); NextToken(); // && || and_or->SetLeft(left_exp); and_or->SetRight(ConsumeExpression()); and_or->SetType(make_shared<BoolType>()); return and_or; } shared_ptr<Expression> Parser::ConsumeComparison() { auto comp = make_shared<BinaryOp>(); auto left_exp = ConsumeConditional(); switch (current_token_.GetType()) { case GreaterThanToken: comp->SetOperator(GT); break; case GreaterThanEqualToken: comp->SetOperator(GTE); break; case EqualEqualToken: comp->SetOperator(EQ); break; case LessThanToken: comp->SetOperator(LT); break; case LessThanEqualToken: comp->SetOperator(LTE); break; default: return left_exp; } NextToken(); // > >= == < <= comp->SetLeft(left_exp); comp->SetRight(ConsumeExpression()); comp->SetType(make_shared<BoolType>()); return comp; } shared_ptr<Expression> Parser::ConsumeConditional() { auto conditional = make_shared<Conditional>(); auto predicate = ConsumeAddSub(); if (!Accept(QuestionToken)) return predicate; auto tval = ConsumeExpression(); Expect(ColonToken); conditional->SetPredicate(predicate); conditional->SetTrueValue(tval); conditional->SetFalseValue(ConsumeExpression()); return conditional; } shared_ptr<Expression> Parser::ConsumeAddSub() { auto add_sub = make_shared<BinaryOp>(); auto left_exp = ConsumeMultDiv(); bool is_add = current_token_.GetType() == PlusToken; bool is_sub = current_token_.GetType() == MinusToken; if (!is_add && !is_sub) return left_exp; add_sub->SetOperator(PLUS); if (is_sub) add_sub->SetOperator(MINUS); NextToken(); // + - add_sub->SetLeft(left_exp); add_sub->SetRight(ConsumeExpression()); add_sub->SetType(make_shared<NumType>()); return add_sub; } shared_ptr<Expression> Parser::ConsumeMultDiv() { auto exp = make_shared<BinaryOp>(); auto left_exp = ConsumePrimaryExpression(); bool is_mul = current_token_.GetType() == AsteriskToken; bool is_div = current_token_.GetType() == ForwardSlashToken; bool is_mod = current_token_.GetType() == ModToken; if (!is_mul && !is_div && !is_mod) return left_exp; exp->SetOperator(MULTIPLY); if (is_div) exp->SetOperator(DIVIDE); if (is_mod) exp->SetOperator(MODULO); NextToken(); // * / exp->SetLeft(left_exp); exp->SetRight(ConsumeConditional()); exp->SetType(make_shared<NumType>()); return exp; } shared_ptr<Expression> Parser::ConsumePrimaryExpression() { shared_ptr<Expression> exp; switch (current_token_.GetType()) { case IdentifierToken: { if (next_token_.GetType() == OpenParanToken) exp = ConsumeFunctionCall(); else exp = ConsumeIdentifier(); break; } case NumericLiteral: { exp = make_shared<NumLiteral>(std::stod(current_token_.GetValue())); exp->SetType(make_shared<NumType>()); NextToken(); break; } case TrueKeyword: { // true exp = make_shared<BooleanLiteral>(true); exp->SetType(make_shared<BoolType>()); NextToken(); break; } case FalseKeyword: { // false exp = make_shared<BooleanLiteral>(false); exp->SetType(make_shared<BoolType>()); NextToken(); break; } case ExclamationToken: { // ! exp = ConsumeUnaryOp(); break; } case OpenParanToken: { // ( NextToken(); exp = ConsumeExpression(); Expect(CloseParanToken); break; } case MinusToken: { // Handle negatives (e.g. -3, -some_variable) NextToken(); auto mult = make_shared<BinaryOp>(); auto negative_one = make_shared<NumLiteral>(-1); negative_one->SetType(make_shared<NumType>()); mult->SetLeft(negative_one); mult->SetOperator(MULTIPLY); mult->SetRight(ConsumePrimaryExpression()); mult->SetType(make_shared<NumType>()); exp = mult; break; } default: return nullptr; } return exp; } shared_ptr<Expression> Parser::ConsumeUnaryOp() { Expect(ExclamationToken); auto unary_op = make_shared<UnaryOp>(); unary_op->SetOp(NOT); unary_op->SetExpression(ConsumeExpression()); unary_op->SetType(make_shared<BoolType>()); return unary_op; } shared_ptr<FunctionCall> Parser::ConsumeFunctionCall() { auto call = make_shared<FunctionCall>(); call->SetId(ConsumeIdentifier()); Expect(OpenParanToken); while (lexer_.HasNext() && current_token_.GetType() != CloseParanToken) { call->AddArgument(ConsumeExpression()); if (current_token_.GetType() == CommaToken) { NextToken(); } } Expect(CloseParanToken); return call; } shared_ptr<Identifier> Parser::ConsumeIdentifier() { if (current_token_.GetType() != IdentifierToken) return nullptr; auto id = make_shared<Identifier>(current_token_.GetValue()); NextToken(); return id; } shared_ptr<StaticType> Parser::ConsumeStaticType() { shared_ptr<StaticType> type; switch (current_token_.GetType()) { case BoolKeyword: type = make_shared<BoolType>(); break; case NumberKeyword: type = make_shared<NumType>(); break; case VoidKeyword: type = make_shared<VoidType>(); break; default: RecordError("Type: Expected num, bool, or void"); return nullptr; } NextToken(); return type; } /*********** Helpers ***********/ void Parser::NextToken() { current_token_ = next_token_; next_token_ = lexer_.GetNext(); } bool Parser::Expect(TokenType token) { if (Accept(token)) { return true; } // Attempt to recover NextToken(); // Record error std::stringstream ss; ss << "Invalid token at line: " << lexer_.GetCurrentLine() << " column: " << lexer_.GetCurrentColumn(); RecordError(ss.str()); return false; } bool Parser::Accept(TokenType token) { if (current_token_.GetType() == token) { NextToken(); return true; } return false; } void Parser::RecordError(const std::string message) { errors_.emplace_back(message); }
23.461382
105
0.672702
amSangi
c43b3b29f4c2b9aead625896309afd4afe00f551
6,795
cpp
C++
PlayerEntityInteraction.cpp
IvarJonsson/Project-Unknown
4675b41bbb5e90135c7bf3aded2c2e262b50f351
[ "BSL-1.0" ]
null
null
null
PlayerEntityInteraction.cpp
IvarJonsson/Project-Unknown
4675b41bbb5e90135c7bf3aded2c2e262b50f351
[ "BSL-1.0" ]
null
null
null
PlayerEntityInteraction.cpp
IvarJonsson/Project-Unknown
4675b41bbb5e90135c7bf3aded2c2e262b50f351
[ "BSL-1.0" ]
null
null
null
// Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved. #include "StdAfx.h" #include "Player.h" #include "PlayerEntityInteraction.h" #include "IInteractor.h" #include "GameActions.h" #include "UI/HUD/HUDEventWrapper.h" #include "UI/HUD/HUDEventDispatcher.h" #include "PlayerPlugin_Interaction.h" #include "EntityUtility/EntityScriptCalls.h" #include "Throw.h" namespace { void CallEntityScriptMethod(EntityId entityId, const char* methodName, CPlayer* pPlayerArgument, int slotArgument) { IEntity* pEntity = gEnv->pEntitySystem->GetEntity(entityId); if (!pEntity) return; IScriptTable* pEntityTable = pEntity->GetScriptTable(); IScriptTable* playerScript = pPlayerArgument->GetEntity()->GetScriptTable(); EntityScripts::CallScriptFunction( pEntity, pEntityTable, methodName, playerScript, slotArgument); } bool PlayerCanInteract(CPlayer* pPlayer) { const SPlayerStats* pPlayerStats = static_cast<const SPlayerStats*>(pPlayer->GetActorStats()); CRY_ASSERT(pPlayerStats); // During Stealth kill. if (pPlayer->GetStealthKill().IsBusy()) return false; // Whilst throwing things. Causes issues. if(IItem* pItem = pPlayer->GetCurrentItem()) { if(IWeapon* pWeapon = pItem->GetIWeapon()) { if(const CThrow* pThrow = crygti_cast<CThrow*>(static_cast<CFireMode*>(pWeapon->GetFireMode(pWeapon->GetCurrentFireMode())))) { if(pThrow->IsFiring()) { return false; } } } } // On a ledge or sliding. if (pPlayer->IsOnLedge() || pPlayer->IsSliding()) return false; if (!pPlayer->IsInteractiveActionDone()) return false; // Must be alive. return pPlayer->GetHealth() > 0 && pPlayer->GetSpectatorMode() == 0; } bool PlayerCanStopUseHeavyWeapon(CPlayer* pPlayer) { if (!pPlayer->HasHeavyWeaponEquipped()) return false; return pPlayer->GetCurrentInteractionInfo().interactionType != eInteraction_Use; } } CPlayerEntityInteraction::CPlayerEntityInteraction() : m_useHoldFiredAlready(false) , m_usePressFiredForUse(true) , m_usePressFiredForPickup(false) , m_useButtonPressed(false) , m_autoPickupDeactivatedTime(0.f) { } void CPlayerEntityInteraction::UseEntityUnderPlayer(CPlayer* pPlayer) { if (PlayerCanInteract(pPlayer)) { IInteractor* pInteractor = pPlayer->GetInteractor(); const EntityId entityId = pInteractor->GetOverEntityId(); if(IEntity* pLinkedEnt = pPlayer->GetLinkedEntity()) { if(pLinkedEnt->GetId()==entityId) { // Can't use an entity you are already linked to. return; } } const int frameId = gEnv->pRenderer->GetFrameID(); if (m_lastUsedEntity.CanInteractThisFrame( frameId )) { CallEntityScriptMethod( entityId, "OnUsed", pPlayer, pInteractor->GetOverSlotIdx()); m_lastUsedEntity.Update( frameId ); } } } void CPlayerEntityInteraction::ItemPickUpMechanic(CPlayer* pPlayer, const ActionId& actionId, int activationMode) { const CGameActions& actions = g_pGame->Actions(); if (actionId == actions.preUse) { if (activationMode == eAAM_OnPress) { // Interactor HUD needs to know when to start tracking a Use press // preUse is used instead of Use as adding an onPress to Use will need too many changes to its handling. preUse is the input as Use. SHUDEventWrapper::OnInteractionUseHoldTrack(true); } return; } if (actionId == actions.use) { if (activationMode == eAAM_OnPress) { m_useButtonPressed = true; } else if(activationMode == eAAM_OnRelease) { m_useButtonPressed = false; } } const bool isOnlyPickupAction = (actionId == actions.itemPickup); const bool isOnlyUseAction = (actionId == actions.use); const bool isOnlyHeavyWeaponRemove = (actionId == actions.heavyweaponremove); const bool isUseAction = (isOnlyUseAction || isOnlyPickupAction); if (isOnlyHeavyWeaponRemove && activationMode == eAAM_OnPress && PlayerCanStopUseHeavyWeapon(pPlayer)) { ReleaseHeavyWeapon(pPlayer); m_useHoldFiredAlready = true; } else if (isUseAction && activationMode == eAAM_OnPress) { // This will happen twice on keyboard since Use and itemPickup use same input // To avoid refactoring code right now, only allow self.UseEntity to be called once per input frame // But make sure this functions properly even if use and itemPickup inputs are changed bool fireUseEntity = false; if (isOnlyPickupAction) { if (m_usePressFiredForUse) // 2nd call this frame, don't call { m_usePressFiredForUse = false; // Reset m_usePressFiredForPickup = false; // Reset } else { fireUseEntity = true; m_usePressFiredForPickup = true; } } else if (isOnlyUseAction) { if (m_usePressFiredForPickup) // 2nd call this frame, don't call { m_usePressFiredForPickup = false; // Reset m_usePressFiredForUse = false; // Reset } else { fireUseEntity = true; m_usePressFiredForUse = true; } } if (fireUseEntity) { // Log("[tlh] @ Player:OnAction: action: "..action.." press path"); if (PlayerCanStopUseHeavyWeapon(pPlayer)) ReleaseHeavyWeapon(pPlayer); else UseEntityUnderPlayer(pPlayer); } } else if (isUseAction && activationMode == eAAM_OnHold && !m_useHoldFiredAlready) { bool bFired = false; IInteractor* pInteractor = pPlayer->GetInteractor(); if (pInteractor->GetOverEntityId() != 0) { m_useHoldFiredAlready = true; UseEntityUnderPlayer(pPlayer); bFired = true; } SHUDEventWrapper::OnInteractionUseHoldActivated(bFired); } else if (isUseAction && activationMode == eAAM_OnRelease) { m_useHoldFiredAlready = false; SHUDEventWrapper::OnInteractionUseHoldTrack(false); } } void CPlayerEntityInteraction::ReleaseHeavyWeapon(CPlayer* pPlayer) { IItem* pCurrentItem = pPlayer->GetCurrentItem(); if (pCurrentItem && PlayerCanInteract(pPlayer)) { EntityId heavyWeaponEntity = pCurrentItem->GetEntityId(); CallEntityScriptMethod( heavyWeaponEntity, "OnUsed", pPlayer, 0); } } void CPlayerEntityInteraction::JustInteracted( ) { m_lastUsedEntity.Update( gEnv->pRenderer->GetFrameID() ); } void CPlayerEntityInteraction::Update(CPlayer* pPlayer, float frameTime) { if(m_useButtonPressed && m_autoPickupDeactivatedTime <= 0.f) { IInteractor* pInteractor = pPlayer->GetInteractor(); if (pInteractor->GetOverEntityId() != 0) { EInteractionType interactionType = pPlayer->GetCurrentInteractionInfo().interactionType; if(interactionType == eInteraction_PickupItem || interactionType == eInteraction_ExchangeItem) { UseEntityUnderPlayer(pPlayer); m_useButtonPressed = false; m_autoPickupDeactivatedTime = g_pGameCVars->pl_autoPickupMinTimeBetweenPickups; } } } else if(m_autoPickupDeactivatedTime > 0.f) { m_autoPickupDeactivatedTime -= frameTime; } }
24.981618
135
0.724209
IvarJonsson
c43f80344cd433c8b41b71bb9d82b22ee132fae0
2,540
cpp
C++
src/types/OE_TCM.cpp
antsouchlos/OxygenEngine2
5a123a2dacbc3b66ba9e97b9e5db7d8c17490ddb
[ "MIT" ]
null
null
null
src/types/OE_TCM.cpp
antsouchlos/OxygenEngine2
5a123a2dacbc3b66ba9e97b9e5db7d8c17490ddb
[ "MIT" ]
22
2020-05-19T18:18:45.000Z
2022-03-31T12:11:08.000Z
src/types/OE_TCM.cpp
antsouchlos/OxygenEngine2
5a123a2dacbc3b66ba9e97b9e5db7d8c17490ddb
[ "MIT" ]
null
null
null
#include <types/OE_TCM.h> #include <types/OE_World.h> using namespace std; OE_TCM_Texture::OE_TCM_Texture(){} OE_TCM_Texture::~OE_TCM_Texture(){} std::string OE_TCM_Texture::to_str() const{ string output = outputTypeTag("TCM_Texture", {}); CSL_WriterBase::indent = CSL_WriterBase::indent + 1; output.append(outputVar("textureID", "\"" + OE_World::texturesList.id2name_[this->textureID] + "\"")); output.append("\n"); output.append(outputVar("mode", convert(this->mode))); output.append("\n"); output.append(outputVar("textureMulFactor", convert(this->textureMulFactor))); output.append("\n"); output.append(outputVar("uvmap", convert(this->uvmap))); output.append("\n"); CSL_WriterBase::indent = CSL_WriterBase::indent - 1; output.append(outputClosingTag("TCM_Texture")); return output; } std::atomic<std::size_t> OE_TCM::current_id(0); OE_TCM::OE_TCM(){ this->r = 0.0f; this->g = 0.0f; this->b = 0.0f; this->a = 0.0f; this->texture_array = false; this->combine_mode = 0; this->id = ++OE_TCM::current_id; } OE_TCM::OE_TCM(const string &name){ this->r = 0.0f; this->g = 0.0f; this->b = 0.0f; this->a = 0.0f; this->texture_array = false; this->combine_mode = 0; this->id = ++OE_TCM::current_id; } OE_TCM::~OE_TCM(){ } string OE_TCM::to_str() const{ string output = outputTypeTag("TextureCombineMode", {{"name", "\"" + OE_World::tcmsList.id2name_[this->id] + "\""}}); output.append("\n"); CSL_WriterBase::indent = CSL_WriterBase::indent + 1; output.append(outputVar("texture_array", convert((int)this->texture_array))); output.append("\n"); output.append(outputVar("r", convert(this->r))); output.append("\n"); output.append(outputVar("g", convert(this->g))); output.append("\n"); output.append(outputVar("b", convert(this->b))); output.append("\n"); output.append(outputVar("a", convert(this->a))); output.append("\n"); output.append(outputVar("combine_mode", convert(this->combine_mode))); output.append("\n"); for(const auto& x: this->textures){ output.append(x.to_str()); output.append("\n"); } CSL_WriterBase::indent = CSL_WriterBase::indent - 1; output.append(outputClosingTag("TextureCombineMode")); return output; }
28.539326
121
0.589764
antsouchlos
c44025b33c739370b13780f010faddb3269d47d0
2,631
cpp
C++
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-codepipeline/source/model/ActionOwner.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
2
2019-02-08T21:29:57.000Z
2021-07-27T06:59:19.000Z
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-codepipeline/source/model/ActionOwner.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
null
null
null
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-codepipeline/source/model/ActionOwner.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/codepipeline/model/ActionOwner.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace CodePipeline { namespace Model { namespace ActionOwnerMapper { static const int AWS_HASH = HashingUtils::HashString("AWS"); static const int ThirdParty_HASH = HashingUtils::HashString("ThirdParty"); static const int Custom_HASH = HashingUtils::HashString("Custom"); ActionOwner GetActionOwnerForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == AWS_HASH) { return ActionOwner::AWS; } else if (hashCode == ThirdParty_HASH) { return ActionOwner::ThirdParty; } else if (hashCode == Custom_HASH) { return ActionOwner::Custom; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<ActionOwner>(hashCode); } return ActionOwner::NOT_SET; } Aws::String GetNameForActionOwner(ActionOwner enumValue) { switch(enumValue) { case ActionOwner::AWS: return "AWS"; case ActionOwner::ThirdParty: return "ThirdParty"; case ActionOwner::Custom: return "Custom"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return ""; } } } // namespace ActionOwnerMapper } // namespace Model } // namespace CodePipeline } // namespace Aws
30.241379
92
0.627898
prateek-s
c444b20dbf0a892c04c5ae054b982a1891d074de
222
cpp
C++
Plugins/SimpleUGC/Source/SimpleUGC/Private/UGCBlueprintLibrary.cpp
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
null
null
null
Plugins/SimpleUGC/Source/SimpleUGC/Private/UGCBlueprintLibrary.cpp
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
null
null
null
Plugins/SimpleUGC/Source/SimpleUGC/Private/UGCBlueprintLibrary.cpp
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
null
null
null
#include "UGCBlueprintLibrary.h" class UObject; class UUGCRegistry; UUGCRegistry* UUGCBlueprintLibrary::GetUGCRegistry(UObject* WorldContextObject) { return NULL; } UUGCBlueprintLibrary::UUGCBlueprintLibrary() { }
17.076923
81
0.797297
Dr-Turtle
c44651d5068dfd51f367ce9519782b2cd8d2b4bd
652
cpp
C++
Binary Trees/25_longest_bloddline_sum.cpp
ritikrajdev/450DSA
a9efa8c8be781fd7b101407ac807a83b8a0929f4
[ "MIT" ]
null
null
null
Binary Trees/25_longest_bloddline_sum.cpp
ritikrajdev/450DSA
a9efa8c8be781fd7b101407ac807a83b8a0929f4
[ "MIT" ]
null
null
null
Binary Trees/25_longest_bloddline_sum.cpp
ritikrajdev/450DSA
a9efa8c8be781fd7b101407ac807a83b8a0929f4
[ "MIT" ]
null
null
null
class Solution { public: pair<int, int> max(pair<int, int> l, pair<int, int> r) { if (l.first > r.first) return l; else if (r.first > l.first) return r; else return r.second > l.second ? r : l; } pair<int, int> helper(Node* root) { if (!root) return {0, 0}; auto l = helper(root->left); auto r = helper(root->right); auto mx = max(l, r); mx.first += 1; mx.second += root->data; return mx; } int sumOfLongRootToLeafPath(Node *root) { return helper(root).second; } };
21.032258
62
0.46319
ritikrajdev
c44b20b5819c50c808b09be2a2d36b3a82c47157
318
hpp
C++
include/SAMPCpp/Everything.hpp
pacc-repo/samp-cpp
f23f9bb67f3210a1f46293b1d589e8daddae16f9
[ "MIT" ]
null
null
null
include/SAMPCpp/Everything.hpp
pacc-repo/samp-cpp
f23f9bb67f3210a1f46293b1d589e8daddae16f9
[ "MIT" ]
null
null
null
include/SAMPCpp/Everything.hpp
pacc-repo/samp-cpp
f23f9bb67f3210a1f46293b1d589e8daddae16f9
[ "MIT" ]
null
null
null
#pragma once #include SAMPCPP_PCH #include <SAMPCpp/SAMP/Player.hpp> #include <SAMPCpp/SAMP/Vehicle.hpp> #include <SAMPCpp/SAMP/Server.hpp> #include <SAMPCpp/SAMP/Native.hpp> #include <SAMPCpp/Core/Color.hpp> #include <SAMPCpp/Core/String.hpp> #include <SAMPCpp/Core/Formatting.hpp> #include <SAMPCpp/Core/Math.hpp>
24.461538
38
0.773585
pacc-repo
c44bd964f34eb6425f17e67ae9d1bdaaae283785
3,670
cpp
C++
Stikboldt/_MyPrefabs/UI/PF_PlayerPawn.cpp
Kair0z/StikBoldt-PC
5d978aa6b67e9f3a140136f2f0b766061e765c74
[ "MIT" ]
null
null
null
Stikboldt/_MyPrefabs/UI/PF_PlayerPawn.cpp
Kair0z/StikBoldt-PC
5d978aa6b67e9f3a140136f2f0b766061e765c74
[ "MIT" ]
null
null
null
Stikboldt/_MyPrefabs/UI/PF_PlayerPawn.cpp
Kair0z/StikBoldt-PC
5d978aa6b67e9f3a140136f2f0b766061e765c74
[ "MIT" ]
1
2021-09-23T06:21:53.000Z
2021-09-23T06:21:53.000Z
#include "stdafx.h" #include "PF_PlayerPawn.h" #include "SpriteComponent.h" #define InputID(playerID) (42 + (playerID + 1) * 2) PF_PlayerPawn::PF_PlayerPawn(size_t playerID) : m_pSprite{nullptr} , m_PlayerID{playerID} , m_Velocity{} , m_Speed{450.f} , m_PlayRequest{false} , m_State{State::Idle} , m_ExitRequest{false} { } void PF_PlayerPawn::ResetState() { m_State = State::Idle; } void PF_PlayerPawn::Initialize(const GameContext& context) { m_pSprite = new SpriteComponent{ m_DefaultTexture + std::to_wstring(m_PlayerID) + L".png", {} }; m_pSprite->SetDepth(0.4f - 0.05f * m_PlayerID); AddComponent(m_pSprite); InitInput(context); } void PF_PlayerPawn::InitInput(const GameContext& context) { InputManager* pInput = context.pInput; pInput->AddInputAction(InputAction( InputID(m_PlayerID) + (int)Input_PlayerPawn::A, InputTriggerState::Pressed, -1, -1, XINPUT_GAMEPAD_A, (GamepadIndex)m_PlayerID )); pInput->AddInputAction(InputAction( InputID(m_PlayerID) + (int)Input_PlayerPawn::B, InputTriggerState::Pressed, -1, -1, XINPUT_GAMEPAD_B, (GamepadIndex)m_PlayerID )); } void PF_PlayerPawn::Update(const GameContext& context) { ProcessInput(context); ProcessState(context); if (m_State != State::Pinned) Move(context); } SpriteComponent* PF_PlayerPawn::GetSprite() { return m_pSprite; } void PF_PlayerPawn::SetEnterGameHitbox(const MyUtils::Circle2D& hitbox) { m_GameEnterHitbox = hitbox; } void PF_PlayerPawn::SetExitGameHitbox(const MyUtils::Circle2D& hitbox) { m_GameExitHitbox = hitbox; } bool PF_PlayerPawn::PlayRequest() const { return m_PlayRequest; } bool PF_PlayerPawn::ExitRequest() const { return m_ExitRequest; } bool PF_PlayerPawn::IsPinned() const { return m_State == State::Pinned; } void PF_PlayerPawn::ProcessState(const GameContext&) { if (m_State != State::Pinned && (IsInRange(m_GameEnterHitbox) || IsInRange(m_GameExitHitbox))) { m_State = State::Active; } else if (m_State != State::Pinned) m_State = State::Idle; switch (m_State) { case State::Idle: m_pSprite->SetTexture(m_DefaultTexture + std::to_wstring(m_PlayerID) + L".png"); break; case State::Active: m_pSprite->SetTexture(m_ActiveTexture + std::to_wstring(m_PlayerID) + L".png"); break; case State::Pinned: m_pSprite->SetTexture(m_PinnedTexture + std::to_wstring(m_PlayerID) + L".png"); break; } } void PF_PlayerPawn::ProcessInput(const GameContext& context) { InputManager* pInput = context.pInput; if (pInput->IsActionTriggered(InputID(m_PlayerID) + (int)Input_PlayerPawn::A)) { TryPin(true); } if (pInput->IsActionTriggered(InputID(m_PlayerID) + (int)Input_PlayerPawn::B)) { TryPin(false); } XMFLOAT2 thumbPos = pInput->GetThumbstickPosition(true, (GamepadIndex)m_PlayerID); m_Velocity = { thumbPos.x, -thumbPos.y }; } void PF_PlayerPawn::TryPin(bool doPin) { if (!doPin) { m_State = State::Idle; return; } if (m_State == State::Active) m_State = State::Pinned; if (IsInRange(m_GameEnterHitbox)) m_PlayRequest = true; if (IsInRange(m_GameExitHitbox)) m_ExitRequest = true; } void PF_PlayerPawn::Move(const GameContext& context) { float dt = context.pGameTime->GetElapsed(); XMFLOAT2 newPos = m_pSprite->GetPivot(); m_pSprite->SetPivot({newPos.x + m_Speed * m_Velocity.x * dt, newPos.y + m_Speed* m_Velocity.y * dt}); } bool PF_PlayerPawn::IsInRange(MyUtils::Circle2D hitbox) const { XMFLOAT2 pos = m_pSprite->GetPivot(); XMVECTOR distanceFromHitboxCenter = XMVector2LengthEst(XMLoadFloat2(&pos) - XMLoadFloat2(&hitbox.m_Center)); XMFLOAT2 distances; XMStoreFloat2(&distances, distanceFromHitboxCenter); if (distances.x <= hitbox.m_Radius) return true; return false; }
23.525641
132
0.738147
Kair0z
c44cd029d7d5e611b88e6b6634545698e07f12a4
9,188
cpp
C++
compiler/AST/Operators/OperatorNode.cpp
mattmassicotte/three
3986c656724d1317bdb46d4777f8f952103d7ce7
[ "MIT" ]
8
2015-01-02T21:40:55.000Z
2016-05-12T10:48:09.000Z
compiler/AST/Operators/OperatorNode.cpp
mattmassicotte/three
3986c656724d1317bdb46d4777f8f952103d7ce7
[ "MIT" ]
null
null
null
compiler/AST/Operators/OperatorNode.cpp
mattmassicotte/three
3986c656724d1317bdb46d4777f8f952103d7ce7
[ "MIT" ]
null
null
null
#include "OperatorNode.h" #include "MemberAccessNode.h" #include "IndexerNode.h" #include "UnaryOperatorNode.h" #include "BinaryOperatorNode.h" #include "TernaryOperatorNode.h" #include "Callable/FunctionCallOperatorNode.h" #include "Callable/MethodCallOperatorNode.h" #include "compiler/AST/Variables/VariableNode.h" #include "compiler/Parser/Parser.h" #include "Operators.h" #include <assert.h> namespace Three { ASTNode* OperatorNode::parse(Parser& parser, ASTNode* left, uint32_t precedence) { OperatorNode* node = OperatorNode::createOperator(parser); if (!node) { assert(0 && "Message: operator expected!"); } node->setOp(parser.helper()->nextStr()); node->addChild(left); node->addChild(parser.parseExpression(precedence)); if (node->ternary()) { if (parser.helper()->next().type() != Token::Type::PunctuationColon) { assert(0 && "Message: Expecting colon in ternary operator"); } node->addChild(parser.parseExpression(precedence)); } return node; } ASTNode* OperatorNode::parseUnary(Parser& parser) { if (!parser.helper()->peek().isUnaryOperator()) { assert(0 && "Message: Unary operator expected"); } OperatorNode* node = OperatorNode::createOperator(parser, true); node->setOp(parser.helper()->nextStr()); // unary operators can only have secondary expressions // as arguments (identifiers, unary operators) node->addChild(parser.parseExpressionElement()); return node; } ASTNode* OperatorNode::parseTailing(Parser& parser, ASTNode* leftNode) { // possible tailing operators are: // . // -> // ( // [ for (;;) { switch (parser.helper()->peek().type()) { case Token::Type::OperatorDot: case Token::Type::OperatorArrow: case Token::Type::PunctuationOpenBracket: leftNode = OperatorNode::parseSingleTailing(parser, leftNode); break; case Token::Type::PunctuationOpenParen: leftNode = FunctionCallOperatorNode::parse(parser, leftNode); break; default: return leftNode; } // if we fail to parse anything, kill the loop if (!leftNode) { break; } } return nullptr; } ASTNode* OperatorNode::parseSingleTailing(Parser& parser, ASTNode* leftNode) { switch (parser.helper()->peek().type()) { case Token::Type::PunctuationOpenBracket: return IndexerNode::parse(parser, leftNode); case Token::Type::OperatorDot: if (leftNode->dataType().isPointer()) { return MethodCallOperatorNode::parse(parser, leftNode); } // intentional fallthrough if not a method call case Token::Type::OperatorArrow: return MemberAccessNode::parse(parser, leftNode); default: break; } assert(0 && "Message: Unable to parse tailing operator"); return leftNode; } OperatorNode* OperatorNode::createOperator(Parser& parser, bool unary) { if (unary) { switch (parser.helper()->peek().type()) { case Token::Type::OperatorStar: return new DereferenceOperatorNode(); case Token::Type::OperatorAmpersand: return new AddressOfOperatorNode(); case Token::Type::OperatorMinus: return new UnaryMinusOperatorNode(); case Token::Type::OperatorNot: return new NotOperatorNode(); case Token::Type::OperatorBinaryNot: case Token::Type::OperatorIncrement: case Token::Type::OperatorDecrement: break; default: assert(0); } } switch (parser.helper()->peek().type()) { case Token::Type::OperatorStar: return new MultiplicationOperatorNode(); case Token::Type::OperatorAmpersand: return new BinaryAndOperatorNode(); case Token::Type::OperatorMinus: return new SubtractionOperatorNode(); case Token::Type::OperatorIncrement: return new PlainBinaryOperatorNode("Increment Operator"); case Token::Type::OperatorDecrement: return new PlainBinaryOperatorNode("Decrement Operator"); case Token::Type::OperatorPlus: return new AdditionOperatorNode(); case Token::Type::OperatorDivide: return new DivisionOperatorNode(); case Token::Type::OperatorMod: return new PlainBinaryOperatorNode("Modulus Operator"); case Token::Type::OperatorDot: return new PlainBinaryOperatorNode("Dot Operator"); case Token::Type::OperatorArrow: return new PlainBinaryOperatorNode("Arrow Operator"); case Token::Type::OperatorEqual: return new PlainBinaryOperatorNode("Equal Operator"); case Token::Type::OperatorDeepEqual: return new PlainBinaryOperatorNode("Deep-Equal Operator"); case Token::Type::OperatorCompare: return new PlainBinaryOperatorNode("Compare Operator"); case Token::Type::OperatorNotEqual: return new NotEqualOperatorNode(); case Token::Type::OperatorGreaterThan: return new PlainBinaryOperatorNode("Greater-Than Operator"); case Token::Type::OperatorLessThan: return new PlainBinaryOperatorNode("Less-Than Operator"); case Token::Type::OperatorGreaterOrEqual: return new PlainBinaryOperatorNode("Greater-or-Equal Operator"); case Token::Type::OperatorLessOrEqual: return new PlainBinaryOperatorNode("Less-or-Equal Operator"); case Token::Type::OperatorLogicalAnd: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorLogicalOr: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorLogicalXor: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorNot: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorBinaryNot: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorBinaryOr: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorBinaryXor: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorLeftShift: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorRightShift: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorAssign: return new AssignOperatorNode(); case Token::Type::OperatorAddAssign: return new PlainBinaryOperatorNode("Add-Assign Operator"); case Token::Type::OperatorSubtractAssign: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorMultiplyAssign: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorDivideAssign: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorModAssign: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorBitwiseAndAssign: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorBitwiseOrAssign: return new PlainBinaryOperatorNode("Bitwise Or-Assign Operator"); case Token::Type::OperatorBitwiseXorAssign: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorLeftShiftAssign: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorRightShiftAssign: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorLogicalAndAssign: return new PlainBinaryOperatorNode(""); case Token::Type::OperatorLogicalOrAssign: return new PlainBinaryOperatorNode("Or-Assign Operator"); case Token::Type::OperatorQuestionMark: return new TernaryConditionalOperatorNode(); case Token::Type::OperatorCAS: return new CASOperatorNode(); default: break; } return nullptr; } DataType OperatorNode::dataType() const { assert(this->childCount() > 0); // TODO: is this correct? return this->childAtIndex(0)->dataType(); } std::string OperatorNode::nodeName() const { return "Operator"; } std::string OperatorNode::name() const { return "Operator!!!"; } std::string OperatorNode::str() const { return this->nodeName(); } std::string OperatorNode::op() const { return _operator; } void OperatorNode::setOp(const std::string& string) { _operator = string; } bool OperatorNode::ternary() const { return (this->op() == "?") || (this->op() == "cas"); } }
45.711443
121
0.61232
mattmassicotte
c44ddfa9a83a1d57935a9f41692006c150a06bb0
1,352
hpp
C++
include/dbus-glue-system/dbus/interfaces.hpp
5cript/dbus-mockery-system
3af2e94f6fd2340315d65088fda91dfb575c360c
[ "MIT" ]
null
null
null
include/dbus-glue-system/dbus/interfaces.hpp
5cript/dbus-mockery-system
3af2e94f6fd2340315d65088fda91dfb575c360c
[ "MIT" ]
null
null
null
include/dbus-glue-system/dbus/interfaces.hpp
5cript/dbus-mockery-system
3af2e94f6fd2340315d65088fda91dfb575c360c
[ "MIT" ]
null
null
null
#pragma once #include <dbus-glue/dbus_interface.hpp> namespace DBus::org::freedesktop::DBus { class ObjectManager { public: virtual ~ObjectManager() = default; public: // Methods virtual auto GetManagedObjects() -> std::unordered_map < DBusGlue::object_path, std::unordered_map < std::string, std::unordered_map <std::string, DBusGlue::variant> > > = 0; public: // Properties public: // Signals DBusGlue::signal < void ( DBusGlue::object_path, std::unordered_map <std::string, std::unordered_map <std::string, DBusGlue::variant>> ) > InterfacesAdded; DBusGlue::signal <void(DBusGlue::object_path, std::vector <std::string>)> InterfacesRemoved; }; class Introspectable { public: virtual ~Introspectable() = default; public: // Methods virtual auto Introspect() -> std::string /*xml*/ = 0; public: // Properties public: // signals }; } DBUS_DECLARE_NAMESPACE ( (DBus)(org)(freedesktop)(DBus), Introspectable, DBUS_DECLARE_METHODS(Introspect), DBUS_DECLARE_NO_PROPERTIES, DBUS_DECLARE_NO_SIGNALS ) DBUS_DECLARE_NAMESPACE ( (DBus)(org)(freedesktop)(DBus), ObjectManager, DBUS_DECLARE_METHODS(GetManagedObjects), DBUS_DECLARE_NO_PROPERTIES, DBUS_DECLARE_SIGNALS(InterfacesAdded, InterfacesRemoved) )
21.125
95
0.681953
5cript
c4538e0bef1287b5e25d7aa830319162c90719f1
3,997
cpp
C++
src/metadata/constraints.cpp
blumf/flamerobin
3b442c6786d916383f885d81f0303171fd8ce7c2
[ "MIT" ]
2
2019-05-29T08:32:18.000Z
2021-02-17T08:19:00.000Z
src/metadata/constraints.cpp
blumf/flamerobin
3b442c6786d916383f885d81f0303171fd8ce7c2
[ "MIT" ]
null
null
null
src/metadata/constraints.cpp
blumf/flamerobin
3b442c6786d916383f885d81f0303171fd8ce7c2
[ "MIT" ]
1
2020-06-15T06:49:18.000Z
2020-06-15T06:49:18.000Z
/* Copyright (c) 2004-2016 The FlameRobin Development Team 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. */ // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" // for all others, include the necessary headers (this file is usually all you // need because it includes almost all "standard" wxWindows headers #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include <vector> #include "metadata/constraints.h" #include "metadata/database.h" #include "metadata/MetadataItemVisitor.h" #include "metadata/table.h" bool Constraint::isSystem() const { Table* t = getTable(); if (t) return t->isSystem(); else return false; } const wxString Constraint::getTypeName() const { return "CONSTRAINT"; } wxString ColumnConstraint::getColumnList(const wxString& separator, const wxString& suffix) const { wxString result; for (std::vector<wxString>::const_iterator it = columnsM.begin(); it != columnsM.end(); ++it) { if (it != columnsM.begin()) result += separator; result += (*it) + suffix; } return result; }; bool ColumnConstraint::hasColumn(const wxString& column) const { return columnsM.end() != std::find(columnsM.begin(), columnsM.end(), column); } wxString ForeignKey::getReferencedColumnList() const { wxString result; for (std::vector<wxString>::const_iterator it = referencedColumnsM.begin(); it != referencedColumnsM.end(); ++it) { if (it != referencedColumnsM.begin()) result += ", "; result += (*it); } return result; }; wxString ForeignKey::getJoin(bool quoted) const { Identifier reftab(referencedTableM); wxString rtab = (quoted ? reftab.getQuoted() : reftab.get()); wxString table = (quoted ? getTable()->getQuotedName() : getTable()->getName_()); wxString result; std::vector<wxString>::const_iterator im = columnsM.begin(); for (std::vector<wxString>::const_iterator it = referencedColumnsM.begin(); it != referencedColumnsM.end(); ++it, ++im) { if (!result.IsEmpty()) result += " AND "; Identifier col1(*im); Identifier col2(*it); wxString c1 = (quoted ? col1.getQuoted() : col1.get()); wxString c2 = (quoted ? col2.getQuoted() : col2.get()); result += table + "." + c1 + " = " + rtab + "." + c2; } return result; } void ForeignKey::acceptVisitor(MetadataItemVisitor* visitor) { visitor->visitForeignKey(*this); } void UniqueConstraint::acceptVisitor(MetadataItemVisitor* visitor) { visitor->visitUniqueConstraint(*this); } void PrimaryKeyConstraint::acceptVisitor(MetadataItemVisitor* visitor) { visitor->visitPrimaryKeyConstraint(*this); } Table* Constraint::getTable() const { MetadataItem* m = getParent(); while (m) { if (Table* t = dynamic_cast<Table*>(m)) return t; m = m->getParent(); } return 0; }
29.828358
97
0.677758
blumf
c4556beff38dd7e4c62aa3481341e1f910047daf
150
hpp
C++
firing_char/xsdl_image.hpp
phao/topshooter_xp
e5cc75e47751fa116ca106580b5b4d46cf781c4c
[ "MIT" ]
4
2018-07-09T19:38:27.000Z
2021-03-02T19:31:38.000Z
firing_char/xsdl_image.hpp
phao/topshooter_xp
e5cc75e47751fa116ca106580b5b4d46cf781c4c
[ "MIT" ]
null
null
null
firing_char/xsdl_image.hpp
phao/topshooter_xp
e5cc75e47751fa116ca106580b5b4d46cf781c4c
[ "MIT" ]
2
2020-04-25T18:05:30.000Z
2020-07-14T21:19:17.000Z
#ifndef X_SDL_IMAGE_HPP #define X_SDL_IMAGE_HPP #include "xsdl.hpp" namespace ximg { xsdl::Surface load(const char *file_name); } // ximg #endif
10.714286
28
0.74
phao
c4659a0414befd2926015d41a149aecc6cb578a5
3,438
hpp
C++
include/sireen/metrics.hpp
Jetpie/SiReen
00365023117bec88391bfb37d9549fdca75ac10b
[ "BSD-2-Clause" ]
4
2015-03-18T15:00:38.000Z
2016-01-04T13:09:59.000Z
include/sireen/metrics.hpp
Jetpie/SiReen
00365023117bec88391bfb37d9549fdca75ac10b
[ "BSD-2-Clause" ]
null
null
null
include/sireen/metrics.hpp
Jetpie/SiReen
00365023117bec88391bfb37d9549fdca75ac10b
[ "BSD-2-Clause" ]
null
null
null
// Optimized spatial distance metrics // // @author: Bingqing Qu // // Copyright (C) 2014-2015 Bingqing Qu <sylar.qu@gmail.com> // // @license: See LICENSE at root directory #ifndef SIREEN_METRICS_H_ #define SIREEN_METRICS_H_ #include <string.h> #include <math.h> //#define NDEBUG using namespace std; // spatial namespace spat { /** * Compute cosine similarity between features. If the input vector * is marked as normalized, the simplified computation will be * applied. * * @param x vector x * @param y vector y * @param dim feature dimension * @param noralized flag to determine the nomalization state of * feature vecter. * * @return cosine distance of features */ template <class T> T cosine(const T* x, const T* y, const size_t dim, const bool normalized) { T similarity = 0; if(normalized) { for(size_t i = 0; i < dim ; ++i) similarity += x[i] * y[i]; } else { double x_base = 0, y_base = 0; for(size_t i = 0; i < dim ; ++i) { x_base += x[i] * x[i]; y_base += y[i] * y[i]; similarity += x[i] * y[i]; } if(similarity) similarity /= sqrt(x_base) * sqrt(y_base); } return (1-similarity); } // use a trick for euclidean(x,y) = 2 - cosine_similarity if // input vectors are normalized /** * Compute euclidean similarity between features. If the input vector * is marked as normalized, use a trick for: * euclidean(x,y) = 2 - cosine_similarity * * @param x vector x * @param y vector y * @param dim feature dimension * @param noralized flag to determine the nomalization state of * feature vecter. * * @return euclidean distance of features */ template <class T> T euclidean(const T* x,const T* y, const size_t dim, const bool normalized) { if(normalized) { return (2* cosine(x,y,dim,true)); } else { T dist = 0 ; T tmp = 0; for(size_t i = 0; i < dim ; ++i) { tmp = x[i] - y[i]; dist += tmp * tmp; } return sqrt(dist); } } /** * compute euclidean distance in terms of using optimized comparison * startegy. If the cumulative squared distance has beyond the * current best, it will stop and return an incomplete result. * Else if the final result can beat current best, return true * with the complete distance value. * * @param x vector x * @param y vector y * @param dim feature dimension * @param target current best value * @param dist distance reference * */ template <class T> bool optimize_compare(const T* x,const T* y, const T target, const size_t dim, T &dist) { // flush dist = 0.0; T tmp = 0; for(size_t i = 0; i < dim ; ++i) { tmp = x[i] - y[i]; dist += tmp * tmp; if(dist >= target) return false; } return true; } } #endif
27.285714
73
0.509889
Jetpie
c46706b3346eb05e789949f808b5583b4baf7800
21,299
hpp
C++
framework/areg/base/RuntimeObject.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
70
2021-07-20T11:26:16.000Z
2022-03-27T11:17:43.000Z
framework/areg/base/RuntimeObject.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
32
2021-07-31T05:20:44.000Z
2022-03-20T10:11:52.000Z
framework/areg/base/RuntimeObject.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
40
2021-11-02T09:45:38.000Z
2022-03-27T11:17:46.000Z
#pragma once /************************************************************************ * This file is part of the AREG SDK core engine. * AREG SDK is dual-licensed under Free open source (Apache version 2.0 * License) and Commercial (with various pricing models) licenses, depending * on the nature of the project (commercial, research, academic or free). * You should have received a copy of the AREG SDK license description in LICENSE.txt. * If not, please contact to info[at]aregtech.com * * \copyright (c) 2017-2021 Aregtech UG. All rights reserved. * \file areg/base/RuntimeObject.hpp * \ingroup AREG SDK, Asynchronous Event Generator Software Development Kit * \author Artak Avetyan * \brief AREG Platform Runtime Object class. * All instances of Runtime Object may have individual * class ID. To define class ID, use macro: * DECLARE_RUNTIME and IMPLEMENT_RUNTIME * ************************************************************************/ /************************************************************************ * Include files. ************************************************************************/ #include "areg/base/GEGlobal.h" #include "areg/base/Object.hpp" #include "areg/base/private/RuntimeBase.hpp" #include "areg/base/RuntimeClassID.hpp" #include "areg/base/NEUtilities.hpp" /** * \brief MACRO to declare Runtime Class ID in runtime object. * * \example Runtime Class ID declaration via MACRO * * In this small example the class MyClass is declared as Runtime Object * predefined MACRO define Runtime Class ID, which is used in * function convert(). Function convert() returns valid pointer to * MyClass object if Runtime Object is an instance of MyClass. * Otherwise it will return nullptr. * * class MyClass : public RuntimeObject * { * DECLARE_RUNTIME(MyClass) * public: * MyClass( void ); * ~MyClass( void ); * }; * IMPLEMENT_RUNTIME(MyClass, RuntimeObject) * * MyClass* convert(RuntimeObject& runtimeObj) * { * return RUNTIME_CAST(&runtimeObj, MyClass); * } **/ /************************************************************************/ // Runtime object MACRO definition. Begin /************************************************************************/ /** * \brief Declare this MACRO in your class to make runtime compatible * Your class should be derived from RuntimeObject class. * \param ClassName The name of Runtime Class. Should not be string. * \example DECLARE_RUNTIME(MyClass) **/ ////////////////////////////////////////////////////////////////////////// // DECLARE_RUNTIME macro definition ////////////////////////////////////////////////////////////////////////// #define DECLARE_RUNTIME(ClassName) \ /*********************************************************************/ \ /** Static members and constants **/ \ /*********************************************************************/ \ public: \ /** \brief Returns RuntimeClassID object **/ \ static const RuntimeClassID & _getClassId( void ); \ /*********************************************************************/ \ /** RuntimeBase class overrides **/ \ /*********************************************************************/ \ /** \brief Returns the Runtime Class Identifier object **/ \ virtual const RuntimeClassID & getRuntimeClassId( void ) const override; \ /** \brief Returns the class name (Identifier name) **/ \ virtual const char* getRuntimeClassName( void ) const override; \ /** \brief Returns the calculated number of runtime class. **/ \ virtual unsigned int getRuntimeClassNumber( void ) const override; \ /** \brief Checks class instance by Class Identifier **/ \ /** Checking is done hiearchically and if any class **/ \ /** in base hierarchi has same RuntimeClassID, **/ \ /** returns true. Otherwise, return false. **/ \ /** \param classId The Class Identifier to check. **/ \ virtual bool isInstanceOfRuntimeClass(const RuntimeClassID & classId) const override; \ /** \brief Checks class instance by given name **/ \ /** Checking is done hiearchically and if any class **/ \ /** in base hierarchi has same name, returns true. **/ \ /** Otherwise, return false. **/ \ /** \param className The name of class to check. **/ \ virtual bool isInstanceOfRuntimeClass(const char * className) const override; \ /** \brief Checks class instance by name. **/ \ /** \param className The name of class to check. **/ \ virtual bool isInstanceOfRuntimeClass( unsigned int classMagic ) const override; \ /** * \brief Use this MACRO in source code and specify the base class of Runtime Object. * \param ClassName The name of Runtime Class. Should not be string. * \param BaseClassName The name of base / parent class. Should not be string. * \example IMPLEMENT_RUNTIME(MyClass, RuntimeObject) **/ ////////////////////////////////////////////////////////////////////////// // IMPLEMENT_RUNTIME macro definition ////////////////////////////////////////////////////////////////////////// #define IMPLEMENT_RUNTIME(ClassName, BaseClassName) \ /** Return class identifier object **/ \ const RuntimeClassID & ClassName::_getClassId( void ) \ { static const RuntimeClassID _classId(#ClassName); return _classId; } \ /** Return class identifier object **/ \ const RuntimeClassID & ClassName::getRuntimeClassId( void ) const \ { return ClassName::_getClassId(); } \ /** Return class name **/ \ const char* ClassName::getRuntimeClassName( void ) const \ { return ClassName::_getClassId().getName(); } \ /** Return calculated number **/ \ unsigned int ClassName::getRuntimeClassNumber( void ) const \ { return ClassName::_getClassId().getMagic(); } \ /** Check class instance by Class Identifier **/ \ bool ClassName::isInstanceOfRuntimeClass( const RuntimeClassID & classId ) const \ { return ((ClassName::_getClassId() == classId) || BaseClassName::isInstanceOfRuntimeClass(classId)); } \ /** Check class instance by name **/ \ bool ClassName::isInstanceOfRuntimeClass( const char * className ) const \ { return ((className == ClassName::_getClassId()) || BaseClassName::isInstanceOfRuntimeClass(className)); } \ /** Check class instance by number **/ \ bool ClassName::isInstanceOfRuntimeClass( unsigned int classMagic ) const \ { return ((classMagic == ClassName::_getClassId()) || BaseClassName::isInstanceOfRuntimeClass(classMagic)); } /** * \brief Use MACRO in source code of class template and specify the base class. * class template function implementation. * \param Template The template type definition * \param ClassName The name of Runtime Class. Should not be string. * \param BaseClassName The name of base / parent class. Should not be string. * \param ClassIdType The template Runtime Class ID * \example IMPLEMENT_RUNTIME_TEMPLATE(template <class DATA_CLASS, class DATA_CLASS_TYPE>, MyClass<DATA_CLASS, DATA_CLASS_TYPE>, RuntimeObject, MyClass); **/ ////////////////////////////////////////////////////////////////////////// // IMPLEMENT_RUNTIME_TEMPLATE macro definition ////////////////////////////////////////////////////////////////////////// #define IMPLEMENT_RUNTIME_TEMPLATE(Template, ClassName, BaseClassName, ClassIdType) \ /** Return class identifier object **/ \ Template const RuntimeClassID & ClassName::_getClassId( void ) \ { static const RuntimeClassID _classId(#ClassName); return _classId; } \ /** Return class identifier object **/ \ Template const RuntimeClassID& ClassName::getRuntimeClassId( void ) const \ { return ClassName::_getClassId(); } \ /** Return class name **/ \ Template const char* ClassName::getRuntimeClassName( void ) const \ { return ClassName::_getClassId().getName(); } \ /** Return class number **/ \ Template unsigned int ClassName::getRuntimeClassNumber( void ) const \ { return ClassName::_getClassId().getMagic(); } \ /** Check class instance by Class Identifier **/ \ Template bool ClassName::isInstanceOfRuntimeClass( const RuntimeClassID & classId ) const \ { return ((ClassName::_getClassId() == classId) || BaseClassName::isInstanceOfRuntimeClass(classId)); } \ /** Check class instance by name**/ \ Template bool ClassName::isInstanceOfRuntimeClass( const char * className ) const \ { return ((className == ClassName::_getClassId()) || BaseClassName::isInstanceOfRuntimeClass(className)); } \ /** Check class instance by number **/ \ Template bool ClassName::isInstanceOfRuntimeClass( unsigned int classMagic ) const \ { return ((classMagic == ClassName::_getClassId()) || BaseClassName::isInstanceOfRuntimeClass(classMagic)); } /** * \brief Use this MACRO to make exact object casting of instance of constant object during runtime. * It returns pointer of object if the Runtime Class ID is matching to given ClassName * object. Otherwise, it will return nullptr pointer. * \param ptr Pointer to object * \param ClassName The name of class to cast **/ #define RUNTIME_CONST_EXACT_CAST(ptr, ClassName) static_cast<const ClassName *>(::RuntimeCast(static_cast<const RuntimeObject *>(ptr), #ClassName)) /** * \brief Use this MACRO to make fast casting of instance of constant object during runtime. * It returns pointer of object if the Runtime Class ID is matching to given ClassName * object. Otherwise, it will return nullptr pointer. * \param ptr Pointer to object * \param ClassName The name of class to cast **/ #define RUNTIME_CONST_FAST_CAST(ptr, ClassName) static_cast<const ClassName *>(::RuntimeCast(static_cast<const RuntimeObject *>(ptr), ClassName::_getClassId())) /** * \brief Use this MACRO to make casting of instance of constant object during runtime. * It returns pointer of object if the Runtime Class ID is matching to given ClassName * object. Otherwise, it will return nullptr pointer. * \param ptr Pointer to object * \param ClassName The name of class to cast **/ #define RUNTIME_CONST_CAST(ptr, ClassName) RUNTIME_CONST_FAST_CAST(ptr, ClassName) /** * \brief Use this MACRO to make fast casting of instance of object during runtime. * It returns pointer of object if the Runtime Class ID is matching to given ClassName * object. Otherwise, it will return nullptr pointer. * \param ptr Pointer to object * \param ClassName The name of class to cast **/ #define RUNTIME_CAST(ptr, ClassName) const_cast<ClassName *>(RUNTIME_CONST_CAST(ptr, ClassName)) /************************************************************************/ // Runtime object MACRO definition. End /************************************************************************/ ////////////////////////////////////////////////////////////////////////// // RuntimeObject class declaration ////////////////////////////////////////////////////////////////////////// /** * \brief Runtime class object is a base class for all Runtime classes, * which contain class name used in Runtime operation. **/ class AREG_API RuntimeObject : private RuntimeBase // Base Runtime class, declared as private , public Object // Instance of Object class { ////////////////////////////////////////////////////////////////////////// // Constructor / Destructor ////////////////////////////////////////////////////////////////////////// protected: /** * \brief Constructor **/ RuntimeObject( void ) = default; /** * \brief Destructor **/ virtual ~RuntimeObject( void ) = default; ////////////////////////////////////////////////////////////////////////// // Attributes ////////////////////////////////////////////////////////////////////////// public: /************************************************************************/ // Declare Runtime standard functions and variables /************************************************************************/ /** * \brief The Runtime Object should contain runtime information. **/ DECLARE_RUNTIME(RuntimeObject) ////////////////////////////////////////////////////////////////////////// // Operations ////////////////////////////////////////////////////////////////////////// public: /** * \brief Makes casting of pointer of object during runtime * by given class identifier. If class is an instance * of given class identifier, it returns valid pointer. * Otherwise, it returns nullptr. * \param classId Class identifier to make casting * \return Returns valid pointer, if class is an instance of passed * class identifier. Otherwise return nullptr. **/ inline const RuntimeObject* runtimeCast(const RuntimeClassID & classId) const; /** * \brief Makes casting of pointer of object during runtime * by given class name. If class is an instance * of given class name, it returns valid pointer. * Otherwise, it returns nullptr. * \param className Class name to make casting * \return Returns valid pointer, if class is an instance of passed * class name. Otherwise return nullptr. **/ inline const RuntimeObject* runtimeCast(const char * className) const; /** * \brief Makes casting of pointer of object during runtime * by given class number. If class numbers have same * magic numbers, it returns valid pointer. * Otherwise, it returns nullptr. * \param classNumber The magic number of the class to compare * \return Returns valid pointer, if class is an instance of passed * magic number of the class. Otherwise return nullptr. **/ inline const RuntimeObject* runtimeCast(unsigned int classNumber) const; /************************************************************************/ // friend global operations /************************************************************************/ /** * \brief Makes casting of constant pointer of object during runtime * by given class identifier. If class is an instance * of given class identifier, it returns valid pointer. * Otherwise, it returns nullptr. * \param ptr Constant Pointer of object to cast * \param classId Class identifier to make casting * \return Returns valid pointer, if class is an instance of passed * class identifier. Otherwise return nullptr. **/ friend inline const RuntimeObject* RuntimeCast(const RuntimeObject * ptr, const RuntimeClassID & classId); /** * \brief Makes casting of constant pointer of object during runtime * by given class name. If class is an instance * of given class name, it returns valid pointer. * Otherwise, it returns nullptr. * \param ptr Constant Pointer of object to cast * \param className Class name to make casting * \return Returns valid pointer, if class is an instance of passed * class name. Otherwise return nullptr. **/ friend inline const RuntimeObject* RuntimeCast(const RuntimeObject* ptr, const char* className); /** * \brief Makes casting of constant pointer of object during runtime * by given class number (magic number). If class has same magic, * number, it returns valid pointer. * Otherwise, it returns nullptr. * \param ptr Constant Pointer of object to cast * \param classNumber Class number (magic number) to compare. * \return Returns valid pointer, if class has same magic number. * Otherwise return nullptr. **/ friend const RuntimeObject* RuntimeCast( const RuntimeObject* ptr, unsigned int classNumber ); ////////////////////////////////////////////////////////////////////////// // Hidden / Forbidden methods ////////////////////////////////////////////////////////////////////////// private: DECLARE_NOCOPY_NOMOVE( RuntimeObject ); }; ////////////////////////////////////////////////////////////////////////// // RuntimeObject class inline function implementation ////////////////////////////////////////////////////////////////////////// inline const RuntimeObject* RuntimeObject::runtimeCast( const RuntimeClassID & classId ) const { return (isInstanceOfRuntimeClass( classId ) ? this : nullptr); } inline const RuntimeObject* RuntimeObject::runtimeCast( const char* className ) const { return (isInstanceOfRuntimeClass( className ) ? this : nullptr); } inline const RuntimeObject* RuntimeObject::runtimeCast( unsigned int classNumber ) const { return (isInstanceOfRuntimeClass( classNumber ) ? this : nullptr); } inline const RuntimeObject* RuntimeCast(const RuntimeObject * ptr, const RuntimeClassID & classId) { return (ptr != nullptr ? ptr->runtimeCast(classId) : nullptr); } inline const RuntimeObject* RuntimeCast(const RuntimeObject * ptr, const char * className) { return (ptr != nullptr ? ptr->runtimeCast(className) : nullptr); } inline const RuntimeObject* RuntimeCast(const RuntimeObject* ptr, unsigned int classNumber) { return (ptr != nullptr ? ptr->runtimeCast(classNumber) : nullptr); }
58.837017
164
0.487206
Ali-Nasrolahi
c467743a3f61ba501bfd1e1caccf2bad61cf15a5
3,492
cpp
C++
GutsAndMaggots/hooks/update_status_effects.cpp
idmontie/gptp
14d68e5eac84c2f3085ac25a7fff31a07ea387f6
[ "0BSD" ]
8
2015-04-03T16:50:59.000Z
2021-01-06T17:12:29.000Z
GutsAndMaggots/hooks/update_status_effects.cpp
idmontie/gptp
14d68e5eac84c2f3085ac25a7fff31a07ea387f6
[ "0BSD" ]
6
2015-04-03T18:10:56.000Z
2016-02-18T05:04:21.000Z
GutsAndMaggots/hooks/update_status_effects.cpp
idmontie/gptp
14d68e5eac84c2f3085ac25a7fff31a07ea387f6
[ "0BSD" ]
6
2015-04-04T04:37:33.000Z
2018-04-09T09:03:50.000Z
#include "update_status_effects.h" #include "../SCBW/api.h" #include "../SCBW/enumerations.h" #include "../SCBW/scbwdata.h" #include "irradiate.h" namespace { //Helper functions that should be used only in this file u8 getAcidSporeOverlayAdjustment(const CUnit* const unit); } //unnamed namespace namespace hooks { //Detour for UpdateStatusEffects() (AKA RestoreAllUnitStats()) //Original function address: 0x00492F70 (SCBW 1.16.1) //Note: this function is called every 8 ticks (when unit->cycleCounter reaches 8 == 0) void updateStatusEffectsHook(CUnit *unit) { //Default StarCraft logic if (unit->stasisTimer) { unit->stasisTimer--; if (unit->stasisTimer == 0) unit->removeStasisField(); } //익스트랙터는 스팀팩 타이머를 따로 쓰니까 제외 if (unit->id != UnitId::extractor) { if (unit->stimTimer) { unit->stimTimer--; if (unit->stimTimer == 0) unit->updateSpeed(); } } if (unit->ensnareTimer) { unit->ensnareTimer--; if (unit->ensnareTimer == 0) { unit->removeOverlay(ImageId::EnsnareOverlay_Small, ImageId::EnsnareOverlay_Large); unit->updateSpeed(); } } if (unit->defensiveMatrixTimer) { unit->defensiveMatrixTimer--; if (unit->defensiveMatrixTimer == 0) { unit->reduceDefensiveMatrixHp(unit->defensiveMatrixHp); } } if (unit->irradiateTimer) { unit->irradiateTimer--; doIrradiateDamage(unit); if (unit->irradiateTimer == 0) { unit->removeOverlay(ImageId::Irradiate_Small, ImageId::Irradiate_Large); unit->irradiatedBy = NULL; unit->irradiatePlayerId = 8; } } if (unit->lockdownTimer) { unit->lockdownTimer--; if (unit->lockdownTimer == 0) unit->removeLockdown(); } if (unit->maelstromTimer) { unit->maelstromTimer--; if (unit->maelstromTimer == 0) unit->removeMaelstrom(); } if (unit->plagueTimer) { unit->plagueTimer--; if (!(unit->status & UnitStatus::Invincible)) { s32 damage = (Weapon::DamageAmount[WeaponId::Plague] << 8) / 76; if (unit->hitPoints > damage) unit->damageHp(damage); } if (unit->plagueTimer == 0) unit->removeOverlay(ImageId::PlagueOverlay_Small, ImageId::PlagueOverlay_Large); } if (unit->isUnderStorm) unit->isUnderStorm--; u8 previousAcidSporeCount = unit->acidSporeCount; for (int i = 0; i <= 8; ++i) { if (unit->acidSporeTime[i]) { unit->acidSporeTime[i]--; if (unit->acidSporeTime[i] == 0) unit->acidSporeCount--; } } if (unit->acidSporeCount) { u32 acidOverlayId = getAcidSporeOverlayAdjustment(unit) + ImageId::AcidSpores_1_Overlay_Small; if (!unit->getOverlay(acidOverlayId)) { unit->removeOverlay(ImageId::AcidSpores_1_Overlay_Small, ImageId::AcidSpores_6_9_Overlay_Large); if (unit->subunit) unit = unit->subunit; unit->sprite->createTopOverlay(acidOverlayId); } } else if (previousAcidSporeCount) { unit->removeOverlay(ImageId::AcidSpores_1_Overlay_Small, ImageId::AcidSpores_6_9_Overlay_Large); } } } //hooks namespace { /**** Helper function definitions. Do not change anything below this! ****/ u8 getAcidSporeOverlayAdjustment(const CUnit* const unit) { u8 adjustment = unit->acidSporeCount >> 1; return (adjustment < 3 ? adjustment : 3) + 4 * scbw::getUnitOverlayAdjustment(unit); } } //unnamed namespace
29.1
103
0.642039
idmontie
c469db436015ada74c52e6e95e303beb0bf05009
4,545
cpp
C++
src/2016/day10.cpp
BruJu/AdventOfCode
a9161649882429bc1f995424544ce4cdafb69caa
[ "WTFPL", "MIT" ]
1
2020-12-11T13:37:06.000Z
2020-12-11T13:37:06.000Z
src/2016/day10.cpp
BruJu/AdventOfCode2020
a9161649882429bc1f995424544ce4cdafb69caa
[ "WTFPL", "MIT" ]
null
null
null
src/2016/day10.cpp
BruJu/AdventOfCode2020
a9161649882429bc1f995424544ce4cdafb69caa
[ "WTFPL", "MIT" ]
null
null
null
#include "../advent_of_code.hpp" #include "../util/instruction_reader.hpp" #include <algorithm> #include <regex> #include <array> #include <variant> #include <stack> // https://adventofcode.com/2016/day/10 namespace { class Taker { public: virtual void take(int32_t value) = 0; }; class Robot : public Taker { std::optional<int32_t> value1; std::optional<int32_t> value2; public: void take(int32_t value) override { if (value1 && value == *value1) return; if (value2 && value == *value2) return; if (!value1) value1 = value; else if (!value2) value2 = value; else std::cerr << "Robot have more than 2 values\n"; } std::optional<std::pair<int32_t, int32_t>> get_values() const { if (!value1 || !value2) return std::nullopt; if (*value1 < *value2) return std::pair<int32_t, int32_t>{ *value1, *value2 }; else return std::pair<int32_t, int32_t>{ *value2, *value1 }; } }; class Output_ : public Taker { std::optional<int32_t> m_value; public: void take(int32_t value) override { if (m_value && *m_value != value) return; m_value = value; } int32_t operator*() { return m_value.value(); } }; struct ValueAction { int32_t value; int32_t bot; }; struct BotAction { int32_t bot; bool dest_low_bot; int32_t dest_low_number; bool dest_high_bot; int32_t dest_high_number; }; using Instruction = std::variant<ValueAction, BotAction>; class Factory { std::map<int32_t, Robot > bots; std::map<int32_t, Output_> outputs; Taker & find(bool is_bot, int32_t target) { if (is_bot) { return bots[target]; } else { return outputs[target]; } } public: // ==== VISITOR // The visitor return true if the instruction have been processed, // false if the system couldn't process it. bool operator()(ValueAction va) { bots[va.bot].take(va.value); return true; } bool operator()(BotAction ba) { auto & bot = bots[ba.bot]; const auto values = bot.get_values(); if (!values) { return false; } find(ba.dest_low_bot , ba.dest_low_number ).take(values->first); find(ba.dest_high_bot, ba.dest_high_number).take(values->second); return true; } // ==== OUTPUT std::optional<int32_t> find_responsible_for(int32_t chip1, int32_t chip2) { const std::pair<int32_t, int32_t> pair = std::pair<int32_t, int32_t>(chip1, chip2); for (const auto & [id, robot] : bots) { if (robot.get_values() == pair) { return id; } } return std::nullopt; } int32_t find_part_b() { return *outputs[0] * *outputs[1] * *outputs[2]; } }; } Output day_2016_10(const std::vector<std::string> & lines, const DayExtraInfo &) { bj::InstructionReader<Instruction> ir; ir.add_handler( R"(^value ([0-9]*) goes to bot ([0-9]*)$)", [](const std::vector<std::string> & values) -> Instruction { return ValueAction{ std::stoi(values[0]), std::stoi(values[1]) }; } ); ir.add_handler( R"(^bot ([0-9]*) gives low to (bot|output) ([0-9]*) and high to (bot|output) ([0-9]*)$)", [](const std::vector<std::string> & values) -> Instruction { return BotAction { std::stoi(values[0]), values[1] == "bot", std::stoi(values[2]), values[3] == "bot", std::stoi(values[4]) }; } ); auto instructions = ir(lines).value(); Factory factory; // Assign instructions until they have all been used while (instructions.begin() != instructions.end()) { auto it = instructions.begin(); while (it != instructions.end()) { const bool ok = std::visit(factory, *it); if (ok) { it = instructions.erase(it); } else { ++it; } } } return Output( factory.find_responsible_for(17, 61).value(), factory.find_part_b() ); }
27.379518
97
0.520572
BruJu
c47807c65b9c4376647474a730705a2d7fce8aaa
9,561
cpp
C++
src/meshWalker.cpp
jildertviet/ofxJVisuals
878c5b0e7a7dda49ddb71b3f5d19c13987706a73
[ "MIT" ]
null
null
null
src/meshWalker.cpp
jildertviet/ofxJVisuals
878c5b0e7a7dda49ddb71b3f5d19c13987706a73
[ "MIT" ]
6
2021-10-16T07:10:04.000Z
2021-12-26T13:23:54.000Z
src/meshWalker.cpp
jildertviet/ofxJVisuals
878c5b0e7a7dda49ddb71b3f5d19c13987706a73
[ "MIT" ]
null
null
null
// // meshWalker.cpp // meshTrails // // Created by Jildert Viet on 18-01-18. // // #include "meshWalker.hpp" meshWalker::meshWalker(ofMesh* m, ofVec2f dimensions){ this->m = m; destination = m->getVertex(0); this->dimensions = dimensions; numPoints = ((dimensions.x + 1) * (dimensions.y + 1)); // cout << "Num points on mesh: " << numPoints << endl; trail.setMode(OF_PRIMITIVE_LINES); trail.enableColors(); getDestination(ofVec2f(1,0)); // color = ofFloatColor(ofRandom(0.7, 1.0), ofRandom(0.3, 0.5), ofRandom(0.9, 1.0)); speed = ofRandom(3, 7) * 0.3; locOnGrid = ofVec2f(0,0); loc = m->getVertex(0); // segmentLength = m->getVertex(0).distance(m->getVertex(1)); // diagonalSegmentLength = segmentLength * sqrt(2); // Sqrt(2) // cout << "segmentLength: " << segmentLength << endl; // cout << "diagonalSegmentLength: " << diagonalSegmentLength << endl; } void meshWalker::specificFunction(){ if(numSteps > 1 && destination != ofVec3f(-1, -1, -1)){ loc += direction * speed; numSteps--; } else if(numSteps <= 1){ loc = destination; // Get new random destination? // getDestination(getPerlinDirection()); if(staticDirection){ getDestination(ofVec2f(1,0)); } else{ while(!getDestination(getDirection())); } if(trailPoints.size() >= trailLength) trailPoints.erase(trailPoints.begin()); trailPoints.push_back(loc); } } void meshWalker::display(){ ofSetLineWidth(3); displayTrail(); // ofDrawRectangle(loc-ofVec3f(5,5,0), 10, 10); // ofSetColor(ofColor::darkGreen); // ofDrawRectangle(destination-ofVec3f(5,5,0), 10, 10); // ofSetColor(255); // ofDrawSphere(loc,3); } bool meshWalker::getDestination(ofVec2f d){ if(locOnGrid.y == 0 && d.y == -1) return false; locOnGrid += d; // (0,0) + (0,1), down, becomes: (0,1) (4,3) + (1,0), right, becomes: (5,3) if(locOnGrid.x >= dimensions.x){ locOnGrid.x = dimensions.x; meshIndex = ((locOnGrid.x-1) * dimensions.y * 6 + (locOnGrid.y * 6)) + 1; } else if(locOnGrid.x < 0){ locOnGrid.x = 0; } if(locOnGrid.y >= dimensions.y){ locOnGrid.y = dimensions.y; meshIndex =(locOnGrid.x * dimensions.y * 6 + ((locOnGrid.y - 1) *6)) + 4; } else if(locOnGrid.y < 0){ locOnGrid.y = 0; } if(locOnGrid.x < dimensions.x && locOnGrid.y < dimensions.y){ // cout << "Normal move" << endl; meshIndex = ((locOnGrid.x * dimensions.y * 6) + (locOnGrid.y * 6)); } if(locOnGrid == dimensions){ // cout << "Right bottom" << endl; meshIndex = m->getNumVertices() - 1; } destination = m->getVertex(meshIndex); // destination += ofVec3f(0,0,1); direction = destination - loc; // (2,2) - (1,1), direction: (1,1) ///// (4,0) - (0,0) = direction(4,0).norm -> (1,0) direction.normalize(); // cout << locOnGrid << endl; travelDistance = loc.distance(destination); numSteps = travelDistance / speed; numStepsStart = numSteps; if(numStepsStart == 0){ return false; } else{ return true; } // How many steps to take? After n steps, loc = destination, get new destination. // loc += direction * speed; (0,0) + ((1,0) * (0.5)) = (0.5, 0) - (1, 0) - (1.5, 0) - (2, 0) } ofVec3f meshWalker::getPerlinDirection(){ perlinReadPoint += 0.1; ofVec2f d = ofVec2f(ofMap(ofNoise(perlinReadPoint), 0, 1, -1, 1), ofMap(ofNoise(perlinReadPoint+5), 0, 1, -1, 1)); d.x = round(d.x); d.y = round(d.y); return d; } ofVec3f meshWalker::getDirection(){ // Get angle (45, 90, -90 etc), add or subtract 45, normalize this direction char seed = ofRandom(2); // cout << "Seed: " << (int)seed << endl; if(seed >= 1){ globalDirection.rotate(45, ofVec3f(0,0,1)); } else{ globalDirection.rotate(-45, ofVec3f(0,0,1)); } globalDirection.normalize(); globalDirection.x = round(globalDirection.x); globalDirection.y = round(globalDirection.y); if(globalDirection == ofVec2f(-1, 1) || globalDirection == ofVec2f(1, -1)) return getDirection(); return globalDirection; } void meshWalker::displayTrail(){ trail.clear(); if(trailPoints.size() > 1){ float ratio = (1 - numSteps/(float)numStepsStart); ofVec3f p = trailPoints[1] - trailPoints[0]; p *= ratio; trail.addVertex(trailPoints[0] + p); for(uint16 i=1; i<trailPoints.size(); i++){ trail.addVertex(trailPoints[i]); } trail.addVertex(loc); for(uint16 i=0; i<trail.getNumVertices()-1; i++){ trail.addIndex(i); trail.addIndex(i+1); } ofFloatColor c = color; c.a = 0; trail.addColor(c); for(uint16 i=1; i<trail.getNumVertices(); i++) trail.addColor(color); // addFade(); addFadeFromStart(); // for(uint16 i=0; i<trail.getNumVertices(); i++) // ofDrawCircle(trail.getVertex(i), 4); } if(bDrawCircles){ ofSetColor(255); for(uint16 i=0; i<trailPoints.size(); i++) ofDrawCircle(trailPoints[i], 4); ofSetColor(ofColor(255,0,0)); ofDrawCircle(loc, 4); // cout << "Loc: " << loc << endl; } ofSetColor(255); trail.draw(); } void meshWalker::addFade(){ // int length; // length += trailPoints[0].distance(trailPoints[1]); // for(uint16 i=0; i<trail.getNumVertices()-2; i++){ // if(trailPoints[i].x == trailPoints[i+1].x || trailPoints[i].y == trailPoints[i+1].y){ // length += segmentLength; // } else { // length += diagonalSegmentLength; // } // } // length += trailPoints.back().distance(loc); // cout << "Length: " << length << endl; int toPlace = fadeLength; int totalLength = toPlace; uint32 writePos = 0; // float distance = trail.getVertex(writePos).distance(trail.getVertex(writePos+1)); float distance = glm::distance(trail.getVertex(writePos),trail.getVertex(writePos+1)); float prevAlpha = 0; if(!isinf(distance) && distance != 0){ while(toPlace > distance && writePos < trail.getNumVertices()){ if(!isinf(distance) && distance != 0){ writePos++; float a = (distance / toPlace) + prevAlpha; a = ofMap(a, 0., 1., 0., color.a); // cout << a << endl; trail.getColors()[writePos].a = a; toPlace -= distance; ofVec3f p1 = trail.getVertex(writePos); // cout << "P1: " << p1 << endl; ofVec3f p2 = trail.getVertex(writePos+1); // cout << "P2: " << p2 << endl; distance = p1.distance(p2); // cout << "distance: " << distance << endl; // cout << "toPlace: " << toPlace << endl; if( trail.getVertex(writePos) == trail.getVertex(writePos+1) || distance == 0){ toPlace--; break; } if(writePos >= trail.getNumVertices()) writePos = trail.getNumVertices(); prevAlpha = a; } else{ writePos++; ofVec3f p1 = trail.getVertex(writePos); ofVec3f p2 = trail.getVertex(writePos+1); distance = p1.distance(p2); } } } if(toPlace <= distance || writePos == trail.getNumVertices() - 1){ // cout << "first point: " << trail.getVertex(writePos+1) << " second: " << trail.getVertex(writePos) << endl; // ofVec3f direction = ( - .normalize(); glm::vec3 direction = trail.getVertex(writePos+1) - glm::normalize(trail.getVertex(writePos)); // cout << "Direction: " << direction << endl; ofVec3f newPoint = trail.getVertex(writePos) + (direction * (toPlace)); // cout << "newPoint: " << newPoint << endl; // ofDrawCircle(newPoint, 3); trail.addVertex(newPoint); trail.addColor(color); uint32 nextIndex = trail.getNumVertices(); nextIndex--; // cout << "nextIndex: " << nextIndex << endl; // cout << "writePos: " << writePos << endl; trail.getIndices().insert(trail.getIndices().begin() + ((writePos)*2 + 1), nextIndex); trail.getIndices().insert(trail.getIndices().begin() + ((writePos)*2 + 1), nextIndex); } } void meshWalker::addFadeFromStart(){ for(uint32 i=0; i<trail.getNumVertices(); i++){ float a = (float)i / trail.getNumVertices(); a = ofMap(a, 0., 1., 0., color.a); // if(a<0) // cout << 1 << endl; trail.getColors()[i].a = a; } }
34.268817
126
0.50957
jildertviet
c47d1cf850386dfc1675f15a4a4526073fa855e0
4,597
cpp
C++
utils/signals/programmer.cpp
racktopsystems/kyua
1929dccc5cda71cddda71485094822d3c3862902
[ "BSD-3-Clause" ]
106
2015-01-20T14:49:12.000Z
2022-03-09T01:31:51.000Z
utils/signals/programmer.cpp
racktopsystems/kyua
1929dccc5cda71cddda71485094822d3c3862902
[ "BSD-3-Clause" ]
81
2015-02-23T23:23:41.000Z
2021-07-21T13:51:56.000Z
utils/signals/programmer.cpp
racktopsystems/kyua
1929dccc5cda71cddda71485094822d3c3862902
[ "BSD-3-Clause" ]
27
2015-09-30T20:33:34.000Z
2022-02-14T04:00:08.000Z
// Copyright 2010 The Kyua Authors. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Google Inc. nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "utils/signals/programmer.hpp" extern "C" { #include <signal.h> } #include <cerrno> #include "utils/format/macros.hpp" #include "utils/logging/macros.hpp" #include "utils/noncopyable.hpp" #include "utils/sanity.hpp" #include "utils/signals/exceptions.hpp" namespace utils { namespace signals { /// Internal implementation for the signals::programmer class. struct programmer::impl : utils::noncopyable { /// The number of the signal managed by this programmer. int signo; /// Whether the signal is currently programmed by us or not. bool programmed; /// The signal handler that we replaced; to be restored on unprogramming. struct ::sigaction old_sa; /// Initializes the internal implementation of the programmer. /// /// \param signo_ The signal number. impl(const int signo_) : signo(signo_), programmed(false) { } }; } // namespace signals } // namespace utils namespace signals = utils::signals; /// Programs a signal handler. /// /// \param signo The signal for which to install the handler. /// \param handler The handler to install. /// /// \throw signals::system_error If there is an error programming the signal. signals::programmer::programmer(const int signo, const handler_type handler) : _pimpl(new impl(signo)) { struct ::sigaction sa; sa.sa_handler = handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (::sigaction(_pimpl->signo, &sa, &_pimpl->old_sa) == -1) { const int original_errno = errno; throw system_error(F("Could not install handler for signal %s") % _pimpl->signo, original_errno); } else _pimpl->programmed = true; } /// Destructor; unprograms the signal handler if still programmed. /// /// Given that this is a destructor and it can't report errors back to the /// caller, the caller must attempt to call unprogram() on its own. signals::programmer::~programmer(void) { if (_pimpl->programmed) { LW("Destroying still-programmed signals::programmer object"); try { unprogram(); } catch (const system_error& e) { UNREACHABLE; } } } /// Unprograms the signal handler. /// /// \pre The signal handler is programmed (i.e. this can only be called once). /// /// \throw system_error If unprogramming the signal failed. If this happens, /// the signal is left programmed, this object forgets about the signal and /// therefore there is no way to restore the original handler. void signals::programmer::unprogram(void) { PRE(_pimpl->programmed); // If we fail, we don't want the destructor to attempt to unprogram the // handler again, as it would result in a crash. _pimpl->programmed = false; if (::sigaction(_pimpl->signo, &_pimpl->old_sa, NULL) == -1) { const int original_errno = errno; throw system_error(F("Could not reset handler for signal %s") % _pimpl->signo, original_errno); } }
33.071942
79
0.700239
racktopsystems
c47ef9f0f6157a2c37fa70b2f0bc5edfc2a3055d
697
cpp
C++
Wonderland/Wonderland/Editor/Modules/VulkanWrapper/Resource/Texture/Texture Backup/VWTextureGroupRequest.cpp
RodrigoHolztrattner/Wonderland
ffb71d47c1725e7cd537e2d1380962b5dfdc3d75
[ "MIT" ]
3
2018-04-09T13:01:07.000Z
2021-03-18T12:28:48.000Z
Wonderland/Wonderland/Editor/Modules/VulkanWrapper/Resource/Texture/Texture Backup/VWTextureGroupRequest.cpp
RodrigoHolztrattner/Wonderland
ffb71d47c1725e7cd537e2d1380962b5dfdc3d75
[ "MIT" ]
null
null
null
Wonderland/Wonderland/Editor/Modules/VulkanWrapper/Resource/Texture/Texture Backup/VWTextureGroupRequest.cpp
RodrigoHolztrattner/Wonderland
ffb71d47c1725e7cd537e2d1380962b5dfdc3d75
[ "MIT" ]
1
2021-03-18T12:28:50.000Z
2021-03-18T12:28:50.000Z
//////////////////////////////////////////////////////////////////////////////// // Filename: FluxMyWrapper.cpp //////////////////////////////////////////////////////////////////////////////// #include "VWTextureGroupRequest.h" #include "..\..\VWContext.h" VulkanWrapper::VWTextureGroupRequest::VWTextureGroupRequest() { // Set the initial data // ... } VulkanWrapper::VWTextureGroupRequest::~VWTextureGroupRequest() { } void VulkanWrapper::VWTextureGroupRequest::Create(Reference::Blob<VWTextureGroup>* _resourceReference, HashedStringIdentifier _resourceId) { // Set the resource ptr m_TextureGroupReference = _resourceReference; // Set the id m_TextureGroupIdentifier = _resourceId; }
29.041667
138
0.602582
RodrigoHolztrattner
c4803c8e8e7fc061fab3079af3b618cec0979e3e
5,396
cpp
C++
vision/src/main/cpp/TapeProcessing.cpp
ben327/2019-DeepSpace
0eda4ebde9335952afe73701928d68766aeb2651
[ "MIT" ]
null
null
null
vision/src/main/cpp/TapeProcessing.cpp
ben327/2019-DeepSpace
0eda4ebde9335952afe73701928d68766aeb2651
[ "MIT" ]
null
null
null
vision/src/main/cpp/TapeProcessing.cpp
ben327/2019-DeepSpace
0eda4ebde9335952afe73701928d68766aeb2651
[ "MIT" ]
null
null
null
#include "Display.h" #include "Capture.h" #include "TapeProcessing.h" #include "Display.h" #include <opencv2/opencv.hpp> #include "opencv2/objdetect.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/core/core.hpp" #include <stdio.h> #include <iostream> #include <cameraserver/CameraServer.h> #include <cscore.h> #include "devices/kinect.h" cv::RNG rngTape(12345); void TapeProcessing::Init() { Process::Init(); processType = "TapeProcessing"; } void TapeProcessing::Periodic() { Process::Periodic(); if (_capture.IsValidFrameThresh() && _capture.IsValidFrameTrack()) { //_capture.CopyCaptureMat(_imgProcessedThresh); _capture.CopyCaptureMat(_imgProcessing); _imgProcessedTrack = cv::Mat::zeros(_videoMode.height, _videoMode.width, CV_8UC3); cv::cvtColor(_imgProcessing, _imgProcessing, cv::COLOR_BGR2HSV); //cv::cvtColor(_imgProcessedThresh, _imgProcessedThresh, cv::COLOR_BGR2HSV); //cv::inRange(_imgProcessing, cv::Scalar(40, 0, 75), cv::Scalar(75, 255, 125), _imgProcessedTrack); cv::inRange(_imgProcessing, cv::Scalar(40, 0, 75), cv::Scalar(75, 255, 125), _imgProcessing); cv::findContours(_imgProcessing, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_TC89_KCOS); filteredContours.clear(); for (int i = 0; i < contours.size(); i++) { if (cv::contourArea(contours[i]) > 20) filteredContours.push_back(contours[i]); } //Get RotatedRectangles centres.clear(); //clear the vectors heights.clear(); lefts.clear(); rights.clear(); cv::Scalar color = cv::Scalar(255, 255, 255); for (int i = 0; i < filteredContours.size(); i++) { cv::drawContours(_imgProcessedTrack, filteredContours, (int)i, color); cv::RotatedRect rotatedRect = cv::minAreaRect(filteredContours[i]); cv::Point2f centre = rotatedRect.center; cv::Point2f rectPoints[4]; rotatedRect.points(rectPoints); float angle; cv::Point2f edge1 = cv::Vec2f(rectPoints[1].x, rectPoints[1].y) - cv::Vec2f(rectPoints[0].x, rectPoints[0].y); cv::Point2f edge2 = cv::Vec2f(rectPoints[2].x, rectPoints[2].y) - cv::Vec2f(rectPoints[1].x, rectPoints[1].y); cv::Point2f usedEdge = edge1; if(cv::norm(edge2) > cv::norm(edge1)) { usedEdge = edge2; } cv::Point2f reference = cv::Vec2f(1,0); // horizontal edge angle = 180.0f/CV_PI * acos((reference.x * usedEdge.x + reference.y * usedEdge.y) / (cv::norm(reference) * cv::norm(usedEdge))); float min = rectPoints[0].y; float max = rectPoints[0].y; for (int j = 1; j < 4; j++) { //find the minimum and maximum y-values of each rectangle if (rectPoints[j].y > max) { max = rectPoints[j].y; } if (rectPoints[j].y < min) { min = rectPoints[j].y; } } float height = max - min; //get the height of each rectangle centres.push_back(centre); heights.push_back(height); if (angle > 95 && angle < 125) { //angle range for right classification rights.push_back(true); lefts.push_back(false); } else if (angle < 85 && angle > 55) { //angle range for left classification rights.push_back(false); lefts.push_back(true); } else { rights.push_back(false); lefts.push_back(false); } } int leftmost = -1; float leftPos = 640; targets.clear(); angles.clear(); distances.clear(); for (int i = 0; i < filteredContours.size(); i++) { if (lefts[i]) { //checks if current iteration is a left for (int j = 0; j < filteredContours.size(); j++) { if (rights[j] && centres[j].x < leftPos && centres[j].x > centres[i].x) { //checks if nested iteration is a right and left of the last checked one leftmost = j; } } if (leftmost > -1) { targets.push_back((centres[i]+centres[leftmost]) / 2); //adds the Points2f position of each target to a vector distances.push_back(184 / (heights[i] + heights[leftmost])); //adds the estimated distance to each target. Calibrate by changing the number. float widthAdjust = 0.0058 * distances[distances.size() - 1] * abs(centres[i].x - centres[leftmost].x); //Calibrate distance, then adjust the first number until robot facing target gives 0 degrees. if (widthAdjust > 1.0) { widthAdjust = 1.0; } try { //shoot, acos can throw an error if I've missed an edge-case, and I'm too tired to look for one. angles.push_back(heights[leftmost] > heights[i] ? 180.0f/CV_PI * acos(widthAdjust) : -180.0f/CV_PI * acos(widthAdjust)); } catch (...) { angles.push_back(0); } } } } for (int i = 0; i < targets.size(); i++) { std::stringstream dis; dis << distances[i]; std::stringstream ang; ang << angles[i]; cv::rectangle(_imgProcessedTrack, targets[i] + cv::Point2f(-3,-3), targets[i] + cv::Point2f(3,3), color, 2); //draw small rectangle on target locations cv::putText(_imgProcessedTrack, dis.str() + "m, " + ang.str() + "deg", targets[i] + cv::Point2f(-25,25), cv::FONT_HERSHEY_COMPLEX_SMALL, 1, cv::Scalar(255,0,255)); //text with distance and angle on target } } }
36.958904
210
0.62954
ben327
c48bae73c6d29a327730869255a726ec6efb542f
219
cpp
C++
baidusearch.cpp
serpapi/serpapi-search-cpp
fc1cafc05d3e2c2b1661789d96f916441d33ecd3
[ "MIT" ]
null
null
null
baidusearch.cpp
serpapi/serpapi-search-cpp
fc1cafc05d3e2c2b1661789d96f916441d33ecd3
[ "MIT" ]
null
null
null
baidusearch.cpp
serpapi/serpapi-search-cpp
fc1cafc05d3e2c2b1661789d96f916441d33ecd3
[ "MIT" ]
null
null
null
#include <serpapisearch.hpp> #include <baidusearch.hpp> namespace serpapi { using namespace std; BaiduSearch::BaiduSearch(map<string,string> parameter, string apiKey): SerpApiSearch(parameter, apiKey, "baidu") { } }
21.9
113
0.767123
serpapi
c48c60716eb89d1dc2806360078782fd80bef0f8
1,034
cpp
C++
src/Mods.cpp
hntd187/RE2-Mod-Framework
40e078e6cc31b84d729219e53614659d5338efff
[ "MIT" ]
8
2019-12-01T11:45:09.000Z
2021-07-28T20:50:51.000Z
src/Mods.cpp
hntd187/RE2-Mod-Framework
40e078e6cc31b84d729219e53614659d5338efff
[ "MIT" ]
1
2020-09-01T01:18:18.000Z
2021-04-19T01:47:25.000Z
src/Mods.cpp
hntd187/RE2-Mod-Framework
40e078e6cc31b84d729219e53614659d5338efff
[ "MIT" ]
1
2021-04-08T15:21:24.000Z
2021-04-08T15:21:24.000Z
#include <spdlog/spdlog.h> #include "IntegrityCheckBypass.hpp" #include "PositionHooks.hpp" #include "DeveloperTools.hpp" #include "Speedrun.h" #include "Mods.hpp" #include "ObjectExplorer.hpp" Mods::Mods() { #ifdef RE3 m_mods.emplace_back(std::make_unique<IntegrityCheckBypass>()); #endif m_mods.emplace_back(std::make_unique<PositionHooks>()); m_mods.emplace_back(std::make_unique<Speedrun>()); #ifdef DEVELOPER m_mods.emplace_back(std::make_unique<DeveloperTools>()); #endif } std::optional<std::string> Mods::on_initialize() const { for (auto &mod : m_mods) { if (auto e = mod->on_initialize(); e != std::nullopt) { return e; } } utility::Config cfg{"re2_fw_config.txt"}; for (auto &mod : m_mods) { mod->on_config_load(cfg); } return std::nullopt; } void Mods::on_frame() const { for (auto &mod : m_mods) { mod->on_frame(); } } void Mods::on_draw_ui() const { for (auto &mod : m_mods) { mod->on_draw_ui(); } }
19.509434
66
0.635397
hntd187
c48cc454fa9326c11402b9eb583a3ad946e39d35
8,264
cc
C++
src/io/io_hdf5.cc
EPTlib/b1map-sim
2f5836907b06453cd71a15c8e7a632f7327d621c
[ "MIT" ]
3
2021-03-02T19:36:56.000Z
2022-02-03T00:01:11.000Z
src/io/io_hdf5.cc
EPTlib/b1map-sim
2f5836907b06453cd71a15c8e7a632f7327d621c
[ "MIT" ]
1
2021-06-10T13:43:00.000Z
2021-06-10T13:43:00.000Z
src/io/io_hdf5.cc
EPTlib/b1map-sim
2f5836907b06453cd71a15c8e7a632f7327d621c
[ "MIT" ]
null
null
null
/***************************************************************************** * * Program: b1map-sim * Author: Alessandro Arduino <a.arduino@inrim.it> * * MIT License * * Copyright (c) 2020 Alessandro Arduino * Istituto Nazionale di Ricerca Metrologica (INRiM) * Strada delle cacce 91, 10135 Torino * ITALY * * 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 "b1map/io/io_hdf5.h" #include <algorithm> using namespace b1map; using namespace b1map::io; namespace { /** * Provide the uri, given url and urn. * * @param url url * @param urn urn * * @return uri */ inline std::string URI(const std::string &url, const std::string &urn) { std::string uri("/"+url+"/"+urn); size_t pos = uri.find("//"); while (pos != std::string::npos) { uri.replace(pos, 2, "/"); pos = uri.find("//"); } return uri; } /** * Create an hdf5 group, given an url. * * @param file hdf5 file * @param url url * * @return hdf5 group */ inline H5::Group CreateGroup(const H5::H5File &file, const std::string &url) { size_t depth = 0; size_t snip = url.find_first_of("/", 0) ? 0 : 1; size_t snap = url.find_first_of("/", snip); std::string subpath = url.substr(snip,snap); H5::Group* tmp, group; while (!subpath.empty()) { try { group = depth ? tmp->openGroup(subpath) : file.openGroup(subpath); } catch (const H5::Exception&) { group = depth ? tmp->createGroup(subpath) : file.createGroup(subpath); } snip = ++snap; snap = url.find_first_of("/",snip); subpath = url.substr(snip,snap); tmp = &group; depth++; } return *tmp; } // HDF5 types traits template <typename T> struct HDF5Types; // traits specialisations template <> struct HDF5Types<size_t> { static const H5::DataType Type() { return H5::PredType::NATIVE_ULONG; } }; template<> struct HDF5Types<double> { static const H5::DataType Type() { return H5::PredType::NATIVE_DOUBLE; } }; template<> struct HDF5Types<float> { static const H5::DataType Type() { return H5::PredType::NATIVE_FLOAT; } }; template<> struct HDF5Types<int> { static const H5::DataType Type() { return H5::PredType::NATIVE_INT; } }; template<> struct HDF5Types<long> { static const H5::DataType Type() { return H5::PredType::NATIVE_LONG; } }; } // // IOh5 constructor IOh5:: IOh5(const std::string &fname, const Mode mode) : fname_(fname), mode_(mode) { H5::Exception::dontPrint(); switch (mode_) { case Mode::In: file_ = H5::H5File(fname_, H5F_ACC_RDONLY); break; case Mode::Out: file_ = H5::H5File(fname_, H5F_ACC_TRUNC); break; case Mode::Append: try { file_ = H5::H5File(fname_, H5F_ACC_RDWR); } catch (const H5::FileIException&) { file_ = H5::H5File(fname_, H5F_ACC_TRUNC); } break; } return; } // IOh5 destructor IOh5:: ~IOh5() { file_.close(); return; } // IOh5 read dataset template <typename T> State IOh5:: ReadDataset(Image<T> *img, const std::string &url, const std::string &urn) { H5::Exception::dontPrint(); try { // locate the dataset H5::DataSet dset = file_.openDataSet(URI(url,urn)); H5::DataSpace dspace = dset.getSpace(); // read the data std::vector<hsize_t> dims(dspace.getSimpleExtentNdims()); size_t ndim = dspace.getSimpleExtentDims(dims.data(),NULL); std::vector<int> nn(dims.size()); std::reverse_copy(dims.begin(),dims.end(),nn.begin()); *img = Image<T>(nn); dset.read(img->GetData().data(),::HDF5Types<T>::Type()); } catch (const H5::FileIException&) { return State::HDF5FileException; } catch (const H5::DataSetIException&) { return State::HDF5DatasetException; } catch (const H5::DataSpaceIException&) { return State::HDF5DataspaceException; } catch (const H5::DataTypeIException&) { return State::HDF5DatatypeException; } return State::Success; } // IOh5 write dataset template <typename T> State IOh5:: WriteDataset(const Image<T> &img, const std::string &url, const std::string &urn) const { H5::Exception::dontPrint(); try { // open or create the group H5::Group group; try { group = file_.openGroup(url); } catch (const H5::Exception&) { group = CreateGroup(file_,url); } // create the dataset int n_dim = img.GetNDim(); std::vector<hsize_t> dims(n_dim); std::reverse_copy(img.GetSize().begin(),img.GetSize().end(),dims.begin()); H5::DataSpace dspace(n_dim,dims.data()); H5::DataType dtype(::HDF5Types<T>::Type()); H5::DataSet dset; try { dset = group.createDataSet(urn,dtype,dspace); } catch (const H5::Exception&) { dset = group.openDataSet(urn); } // write the data in the dataset dset.write(img.GetData().data(),dtype,dspace); } catch (const H5::FileIException&) { return State::HDF5FileException; } catch (const H5::GroupIException&) { return State::HDF5FileException; } catch (const H5::DataSetIException&) { return State::HDF5DatasetException; } catch (const H5::DataSpaceIException&) { return State::HDF5DataspaceException; } catch (const H5::DataTypeIException&) { return State::HDF5DatatypeException; } return State::Success; } // Template specialisations // ReadDataset template State IOh5::ReadDataset<size_t>(Image<size_t> *img, const std::string &url, const std::string &urn); template State IOh5::ReadDataset<float>(Image<float> *img, const std::string &url, const std::string &urn); template State IOh5::ReadDataset<double>(Image<double> *img, const std::string &url, const std::string &urn); template State IOh5::ReadDataset<int>(Image<int> *img, const std::string &url, const std::string &urn); template State IOh5::ReadDataset<long>(Image<long> *img, const std::string &url, const std::string &urn); // WriteDataset template State IOh5::WriteDataset<size_t>(const Image<size_t> &img, const std::string &url, const std::string &urn) const; template State IOh5::WriteDataset<float>(const Image<float> &img, const std::string &url, const std::string &urn) const; template State IOh5::WriteDataset<double>(const Image<double> &img, const std::string &url, const std::string &urn) const; template State IOh5::WriteDataset<int>(const Image<int> &img, const std::string &url, const std::string &urn) const; template State IOh5::WriteDataset<long>(const Image<long> &img, const std::string &url, const std::string &urn) const;
34.722689
122
0.606486
EPTlib
c48ee9cb4d13e7b44b02486b378f5612c0ba7ab6
601
cpp
C++
Online-Judge-Solution/Codeforces Solutions/ECR(A.Maximum Increase).cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
Online-Judge-Solution/Codeforces Solutions/ECR(A.Maximum Increase).cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
Online-Judge-Solution/Codeforces Solutions/ECR(A.Maximum Increase).cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define ll long long int #define max 100009 using namespace std; int main() { ll a[max],i,n,k; while(cin>>n) { ll count=0,k=1; for(i=0; i<n; i++) { cin>>a[i]; } for(i=0; i<(n-1); i++) { if(a[i]<a[i+1]) k++; else { if(k>=count) count=k; k=1; } } if(count==0 || k>=count) printf("%lld\n",k); else printf("%lld\n",count); } return 0; }
18.212121
35
0.33777
arifparvez14
c492c455f06727073b4745a7c606fceda8b828dd
9,862
cc
C++
libqpdf/QPDFAnnotationObjectHelper.cc
tomty89/qpdf
e0775238b8b011755b9682555a8449b8a71f33eb
[ "Apache-2.0" ]
1,812
2015-01-27T09:07:20.000Z
2022-03-30T23:03:15.000Z
libqpdf/QPDFAnnotationObjectHelper.cc
tomty89/qpdf
e0775238b8b011755b9682555a8449b8a71f33eb
[ "Apache-2.0" ]
584
2015-01-24T00:31:12.000Z
2022-03-24T21:42:38.000Z
libqpdf/QPDFAnnotationObjectHelper.cc
tomty89/qpdf
e0775238b8b011755b9682555a8449b8a71f33eb
[ "Apache-2.0" ]
204
2015-04-09T16:28:06.000Z
2022-03-29T14:29:45.000Z
#include <qpdf/QPDFAnnotationObjectHelper.hh> #include <qpdf/QTC.hh> #include <qpdf/QPDFMatrix.hh> #include <qpdf/QUtil.hh> #include <qpdf/QPDF.hh> #include <qpdf/QPDFNameTreeObjectHelper.hh> QPDFAnnotationObjectHelper::Members::~Members() { } QPDFAnnotationObjectHelper::Members::Members() { } QPDFAnnotationObjectHelper::QPDFAnnotationObjectHelper(QPDFObjectHandle oh) : QPDFObjectHelper(oh) { } std::string QPDFAnnotationObjectHelper::getSubtype() { return this->oh.getKey("/Subtype").getName(); } QPDFObjectHandle::Rectangle QPDFAnnotationObjectHelper::getRect() { return this->oh.getKey("/Rect").getArrayAsRectangle(); } QPDFObjectHandle QPDFAnnotationObjectHelper::getAppearanceDictionary() { return this->oh.getKey("/AP"); } std::string QPDFAnnotationObjectHelper::getAppearanceState() { if (this->oh.getKey("/AS").isName()) { QTC::TC("qpdf", "QPDFAnnotationObjectHelper AS present"); return this->oh.getKey("/AS").getName(); } QTC::TC("qpdf", "QPDFAnnotationObjectHelper AS absent"); return ""; } int QPDFAnnotationObjectHelper::getFlags() { QPDFObjectHandle flags_obj = this->oh.getKey("/F"); return flags_obj.isInteger() ? flags_obj.getIntValueAsInt() : 0; } QPDFObjectHandle QPDFAnnotationObjectHelper::getAppearanceStream( std::string const& which, std::string const& state) { QPDFObjectHandle ap = getAppearanceDictionary(); std::string desired_state = state.empty() ? getAppearanceState() : state; if (ap.isDictionary()) { QPDFObjectHandle ap_sub = ap.getKey(which); if (ap_sub.isStream() && desired_state.empty()) { QTC::TC("qpdf", "QPDFAnnotationObjectHelper AP stream"); return ap_sub; } if (ap_sub.isDictionary() && (! desired_state.empty())) { QTC::TC("qpdf", "QPDFAnnotationObjectHelper AP dictionary"); QPDFObjectHandle ap_sub_val = ap_sub.getKey(desired_state); if (ap_sub_val.isStream()) { QTC::TC("qpdf", "QPDFAnnotationObjectHelper AP sub stream"); return ap_sub_val; } } } QTC::TC("qpdf", "QPDFAnnotationObjectHelper AP null"); return QPDFObjectHandle::newNull(); } std::string QPDFAnnotationObjectHelper::getPageContentForAppearance( std::string const& name, int rotate, int required_flags, int forbidden_flags) { if (! getAppearanceStream("/N").isStream()) { return ""; } // The appearance matrix computed by this method is the // transformation matrix that needs to be in effect when drawing // this annotation's appearance stream on the page. The algorithm // for computing the appearance matrix described in section 12.5.5 // of the ISO-32000 PDF spec is similar but not identical to what // we are doing here. // When rendering an appearance stream associated with an // annotation, there are four relevant components: // // * The appearance stream's bounding box (/BBox) // * The appearance stream's matrix (/Matrix) // * The annotation's rectangle (/Rect) // * In the case of form fields with the NoRotate flag, the // page's rotation // When rendering a form xobject in isolation, just drawn with a // /Do operator, there is no form field, so page rotation is not // relevant, and there is no annotation, so /Rect is not relevant, // so only /BBox and /Matrix are relevant. The effect of these are // as follows: // * /BBox is treated as a clipping region // * /Matrix is applied as a transformation prior to rendering the // appearance stream. // There is no relationship between /BBox and /Matrix in this // case. // When rendering a form xobject in the context of an annotation, // things are a little different. In particular, a matrix is // established such that /BBox, when transformed by /Matrix, would // fit completely inside of /Rect. /BBox is no longer a clipping // region. To illustrate the difference, consider a /Matrix of // [2 0 0 2 0 0], which is scaling by a factor of two along both // axes. If the appearance stream drew a rectangle equal to /BBox, // in the case of the form xobject in isolation, this matrix would // cause only the lower-left quadrant of the rectangle to be // visible since the scaling would cause the rest of it to fall // outside of the clipping region. In the case of the form xobject // displayed in the context of an annotation, such a matrix would // have no effect at all because it would be applied to the // bounding box first, and then when the resulting enclosing // quadrilateral was transformed to fit into /Rect, the effect of // the scaling would be undone. // Our job is to create a transformation matrix that compensates // for these differences so that the appearance stream of an // annotation can be drawn as a regular form xobject. // To do this, we perform the following steps, which overlap // significantly with the algorithm in 12.5.5: // 1. Transform the four corners of /BBox by applying /Matrix to // them, creating an arbitrarily transformed quadrilateral. // 2. Find the minimum upright rectangle that encompasses the // resulting quadrilateral. This is the "transformed appearance // box", T. // 3. Compute matrix A that maps the lower left and upper right // corners of T to the annotation's /Rect. This can be done by // scaling so that the sizes match and translating so that the // scaled T exactly overlaps /Rect. // If the annotation's /F flag has bit 4 set, this means that // annotation is to be rotated about its upper left corner to // counteract any rotation of the page so it remains upright. To // achieve this effect, we do the following extra steps: // 1. Perform the rotation on /BBox box prior to transforming it // with /Matrix (by replacing matrix with concatenation of // matrix onto the rotation) // 2. Rotate the destination rectangle by the specified amount // 3. Apply the rotation to A as computed above to get the final // appearance matrix. QPDFObjectHandle rect_obj = this->oh.getKey("/Rect"); QPDFObjectHandle as = getAppearanceStream("/N").getDict(); QPDFObjectHandle bbox_obj = as.getKey("/BBox"); QPDFObjectHandle matrix_obj = as.getKey("/Matrix"); int flags = getFlags(); if (flags & forbidden_flags) { QTC::TC("qpdf", "QPDFAnnotationObjectHelper forbidden flags"); return ""; } if ((flags & required_flags) != required_flags) { QTC::TC("qpdf", "QPDFAnnotationObjectHelper missing required flags"); return ""; } if (! (bbox_obj.isRectangle() && rect_obj.isRectangle())) { return ""; } QPDFMatrix matrix; if (matrix_obj.isMatrix()) { QTC::TC("qpdf", "QPDFAnnotationObjectHelper explicit matrix"); matrix = QPDFMatrix(matrix_obj.getArrayAsMatrix()); } else { QTC::TC("qpdf", "QPDFAnnotationObjectHelper default matrix"); } QPDFObjectHandle::Rectangle rect = rect_obj.getArrayAsRectangle(); bool do_rotate = (rotate && (flags & an_no_rotate)); if (do_rotate) { // If the the annotation flags include the NoRotate bit and // the page is rotated, we have to rotate the annotation about // its upper left corner by the same amount in the opposite // direction so that it will remain upright in absolute // coordinates. Since the semantics of /Rotate for a page are // to rotate the page, while the effect of rotating using a // transformation matrix is to rotate the coordinate system, // the opposite directionality is explicit in the code. QPDFMatrix mr; mr.rotatex90(rotate); mr.concat(matrix); matrix = mr; double rect_w = rect.urx - rect.llx; double rect_h = rect.ury - rect.lly; switch (rotate) { case 90: QTC::TC("qpdf", "QPDFAnnotationObjectHelper rotate 90"); rect = QPDFObjectHandle::Rectangle( rect.llx, rect.ury, rect.llx + rect_h, rect.ury + rect_w); break; case 180: QTC::TC("qpdf", "QPDFAnnotationObjectHelper rotate 180"); rect = QPDFObjectHandle::Rectangle( rect.llx - rect_w, rect.ury, rect.llx, rect.ury + rect_h); break; case 270: QTC::TC("qpdf", "QPDFAnnotationObjectHelper rotate 270"); rect = QPDFObjectHandle::Rectangle( rect.llx - rect_h, rect.ury - rect_w, rect.llx, rect.ury); break; default: // ignore break; } } // Transform bounding box by matrix to get T QPDFObjectHandle::Rectangle bbox = bbox_obj.getArrayAsRectangle(); QPDFObjectHandle::Rectangle T = matrix.transformRectangle(bbox); if ((T.urx == T.llx) || (T.ury == T.lly)) { // avoid division by zero return ""; } // Compute a matrix to transform the appearance box to the rectangle QPDFMatrix AA; AA.translate(rect.llx, rect.lly); AA.scale((rect.urx - rect.llx) / (T.urx - T.llx), (rect.ury - rect.lly) / (T.ury - T.lly)); AA.translate(-T.llx, -T.lly); if (do_rotate) { AA.rotatex90(rotate); } as.replaceKey("/Subtype", QPDFObjectHandle::newName("/Form")); return ( "q\n" + AA.unparse() + " cm\n" + name + " Do\n" + "Q\n"); }
34.725352
77
0.639018
tomty89
c4950a24915a3d1aca02ce229cd2cd7374a32d0f
958
cpp
C++
C++/Ugly Number.cpp
mafia1989/leetcode
f0bc9708a58602866818120556d8b8caf114811e
[ "MIT" ]
3
2015-08-29T15:25:13.000Z
2015-08-29T15:25:21.000Z
C++/Ugly Number.cpp
mafia1989/leetcode
f0bc9708a58602866818120556d8b8caf114811e
[ "MIT" ]
null
null
null
C++/Ugly Number.cpp
mafia1989/leetcode
f0bc9708a58602866818120556d8b8caf114811e
[ "MIT" ]
null
null
null
// Ugly Number // Total Accepted: 20939 Total Submissions: 63734 Difficulty: Easy // Write a program to check whether a given number is an ugly number. // Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. // Note that 1 is typically treated as an ugly number. //My solution class Solution { public: bool isUgly(int num) { if(num < 1) return false; if(num == 1) return true; while(num != 1 ) { if(num%2 == 0) { num /= 2; } else if(num%3 == 0) { num /= 3; } else if(num%5 == 0) { num /=5; } else return false; } return true; } };
21.288889
168
0.458246
mafia1989
c49664c18de62fa563a3253581516fef411f1350
1,303
cpp
C++
Src/EBAMRElliptic/AMReX_NeumannConductivityEBBC.cpp
jameslehoux/amrex
5553b6af63da745ef13ecdb51654b72ec1cca544
[ "BSD-3-Clause-LBNL" ]
1
2021-05-20T13:04:05.000Z
2021-05-20T13:04:05.000Z
Src/EBAMRElliptic/AMReX_NeumannConductivityEBBC.cpp
jameslehoux/amrex
5553b6af63da745ef13ecdb51654b72ec1cca544
[ "BSD-3-Clause-LBNL" ]
null
null
null
Src/EBAMRElliptic/AMReX_NeumannConductivityEBBC.cpp
jameslehoux/amrex
5553b6af63da745ef13ecdb51654b72ec1cca544
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include "AMReX_NeumannConductivityEBBC.H" #include "AMReX_EBArith.H" namespace amrex { void NeumannConductivityEBBC::applyEBFlux(EBCellFAB & a_lphi, const EBCellFAB & a_phi, const vector<VolIndex> & a_vofsToChange, const MFIter & a_mfi, const Real & a_factor, const bool & a_useHomogeneous) { BL_PROFILE("NeumannConductivityEBBC::applyEBFlux"); Real flux = 0.0; const EBISBox& ebisBox = a_phi.getEBISBox(); for(int ivof = 0; ivof < a_vofsToChange.size(); ivof++) { const VolIndex& vof = a_vofsToChange[ivof]; RealVect centroid = ebisBox.bndryCentroid(vof); centroid *= m_dx; centroid += m_probLo; RealVect point = EBArith::getVoFLocation(vof, m_dx, centroid); Real value = bcvaluefunc(point); flux = value; const Real& areaFrac = ebisBox.bndryArea(vof); flux *= areaFrac; Real bcoef = (*m_bcoe)[a_mfi].getEBFlux()(vof,0); flux *= m_beta*bcoef; a_lphi(vof,0) += flux * a_factor; } } }
36.194444
92
0.508058
jameslehoux
7bcb82e29563a71d25d737bde2758280045927a5
3,164
cpp
C++
src/mods/SecretMissionTimer.cpp
praydog/dx11_mod_base
cfbce80313b782813a959c2d2ceb69705643a6cd
[ "MIT" ]
1
2022-03-26T22:57:55.000Z
2022-03-26T22:57:55.000Z
src/mods/SecretMissionTimer.cpp
praydog/dx11_mod_base
cfbce80313b782813a959c2d2ceb69705643a6cd
[ "MIT" ]
null
null
null
src/mods/SecretMissionTimer.cpp
praydog/dx11_mod_base
cfbce80313b782813a959c2d2ceb69705643a6cd
[ "MIT" ]
null
null
null
#include "SecretMissionTimer.hpp" bool SecretMissionTimer::cheaton{false}; bool SecretMissionTimer::isM9NoStart{false}; uintptr_t SecretMissionTimer::timerRet; uintptr_t SecretMissionTimer::m9Ret; uintptr_t SecretMissionTimer::m9Jne; float SecretMissionTimer::timer = 90.0f; static naked void timer_detour() { __asm { cmp byte ptr [SecretMissionTimer::cheaton], 1 je cheat originalcode: movss xmm0, [rbx+0x5C] jmp qword ptr [SecretMissionTimer::timerRet] cheat: movss xmm0, [SecretMissionTimer::timer] movss [rbx+0x5C], xmm0 jmp qword ptr [SecretMissionTimer::timerRet] } } static naked void m9_groundtimer_detour() { __asm { cmp byte ptr [SecretMissionTimer::cheaton], 0 je originalcode cmp byte ptr [SecretMissionTimer::isM9NoStart], 0 je originalcode cheat: jmp qword ptr[SecretMissionTimer::m9Ret] originalcode: test rdx, rdx jne ret_jne jmp qword ptr [SecretMissionTimer::m9Ret] ret_jne: jmp qword ptr [SecretMissionTimer::m9Jne] } } std::optional<std::string> SecretMissionTimer::on_initialize() { init_check_box_info(); auto base = g_framework->get_module().as<HMODULE>(); // note HMODULE m_is_enabled= &cheaton; m_on_page = Page_SecretMission; m_full_name_string = "Freeze secret missions timer (+)"; m_author_string = "VPZadov"; m_description_string = "Also can prevent starting \"no ground\" timer on sm9."; auto timerAddr = m_patterns_cache->find_addr(base, "F3 0F 10 43 5C 0F 5A C0 F2");// DevilMayCry5.exe+9473C0 if (!timerAddr) { return "Unanable to find timerAddr pattern."; } auto m9Addr = m_patterns_cache->find_addr(base, "3F 48 8B 56 28 48 8B CB 48 85 D2 75 1B");// DevilMayCry5.exe+1FA2CC9; +0x8 if (!m9Addr) { return "Unanable to find m9Addr pattern."; } m9Jne = m9Addr.value() + 0x8 + 0x20; if (!install_hook_absolute(timerAddr.value(), m_timer_hook, &timer_detour, &timerRet, 0x5)) { spdlog::error("[{}] failed to initialize", get_name()); return "Failed to initialize SecretMissionTimer.timer"; } if (!install_hook_absolute(m9Addr.value()+0x8, m_m9_hook, &m9_groundtimer_detour, &m9Ret, 0x5)) { spdlog::error("[{}] failed to initialize", get_name()); return "Failed to initialize SecretMissionTimer.timer"; } return Mod::on_initialize(); } void SecretMissionTimer::on_config_load(const utility::Config& cfg) { timer = cfg.get<float>("SecretMissionTimer.timer").value_or(90.0f); isM9NoStart = cfg.get<bool>("SecretMissionTimer.isM9NoStart").value_or(true); } void SecretMissionTimer::on_config_save(utility::Config& cfg) { cfg.set<float>("SecretMissionTimer.timer", timer); cfg.set<float>("SecretMissionTimer.isM9NoStart", isM9NoStart); } // void SecretMissionTimer::on_frame(){} void SecretMissionTimer::on_draw_ui() { ImGui::TextWrapped("Timer value: "); ImGui::InputFloat("##timerInput", &timer, 0.0f, 0.0f, "%.2f"); ImGui::Checkbox("Disable sm9 no ground start timer", &isM9NoStart); } // void SecretMissionTimer::on_draw_debug_ui(){} void SecretMissionTimer::init_check_box_info() { m_check_box_name = m_prefix_check_box_name + std::string(get_name()); m_hot_key_name = m_prefix_hot_key_name + std::string(get_name()); }
26.588235
124
0.738938
praydog
7bd14cc97d73ffe5159cf4892b3de434212037bf
6,407
cc
C++
tests/spp_alloc_test.cc
RadoslawChmielarz/sparsepp
856dd563c8e453d8d9c5d0c6e43f404eb22db6d2
[ "BSD-3-Clause" ]
1,212
2016-08-22T00:34:34.000Z
2022-03-23T16:28:38.000Z
tests/spp_alloc_test.cc
RadoslawChmielarz/sparsepp
856dd563c8e453d8d9c5d0c6e43f404eb22db6d2
[ "BSD-3-Clause" ]
82
2016-08-23T11:05:50.000Z
2021-07-21T20:57:23.000Z
tests/spp_alloc_test.cc
RadoslawChmielarz/sparsepp
856dd563c8e453d8d9c5d0c6e43f404eb22db6d2
[ "BSD-3-Clause" ]
143
2016-08-22T20:03:33.000Z
2022-03-05T02:18:17.000Z
#include <memory> #include <cassert> #include <cstdio> #include <stdlib.h> #include <algorithm> #include <vector> // enable debugging code in spp_bitset.h #define SPP_TEST 1 #include <sparsepp/spp_timer.h> #include <sparsepp/spp_memory.h> #include <sparsepp/spp_dlalloc.h> using namespace std; static float _to_mb(uint64_t m) { return (float)((double)m / (1024 * 1024)); } // ----------------------------------------------------------- // ----------------------------------------------------------- template <class T, class A> class TestAlloc { public: TestAlloc(size_t num_alloc = 8000000) : _num_alloc(num_alloc) { _allocated.resize(_num_alloc, nullptr); _sizes.resize(_num_alloc, 0); _start_mem_usage = spp::GetProcessMemoryUsed(); } void run() { srand(43); // always same sequence of random numbers for (size_t i=0; i<_num_alloc; ++i) _sizes[i] = std::max(2, (rand() % 5) * 2); spp::Timer<std::milli> timer; // allocate small buffers // ---------------------- for (size_t i=0; i<_num_alloc; ++i) { _allocated[i] = _allocator.allocate(_sizes[i]); _set_buf(_allocated[i], _sizes[i]); } #if 1 // and grow the buffers to a max size of 24 each // --------------------------------------------- for (uint32_t j=4; j<26; j += 2) { for (size_t i=0; i<_num_alloc; ++i) { // if ( _sizes[i] < j) // windows allocator friendly! if ((rand() % 4) != 3 && _sizes[i] < j) // really messes up windows allocator { _allocated[i] = _allocator.reallocate(_allocated[i], _sizes[i], j); _check_buf(_allocated[i], _sizes[i]); _set_buf(_allocated[i], j); _sizes[i] = j; } } } #endif #if 0 // test erase (shrinking the buffers) // --------------------------------------------- for (uint32_t j=28; j>4; j -= 2) { for (size_t i=0; i<_num_alloc; ++i) { // if ( _sizes[i] < j) // windows allocator friendly! if ((rand() % 4) != 3 && _sizes[i] > j) // really messes up windows allocator { _allocated[i] = _allocator.reallocate(_allocated[i], _sizes[i], j); _check_buf1(_allocated[i], _sizes[i]); _set_buf(_allocated[i], j); _sizes[i] = j; } } } #endif #if 0 // and grow the buffers back to a max size of 24 each // -------------------------------------------------- for (uint32_t j=4; j<26; j += 2) { for (size_t i=0; i<_num_alloc; ++i) { // if ( _sizes[i] < j) // windows allocator friendly! if ((rand() % 4) != 3 && _sizes[i] < j) // really messes up windows allocator { _allocated[i] = _allocator.reallocate(_allocated[i], _sizes[i], j); _check_buf(_allocated[i], _sizes[i]); _set_buf(_allocated[i], j); _sizes[i] = j; } } } #endif size_t total_units = 0; for (size_t i=0; i<_num_alloc; ++i) total_units += _sizes[i]; uint64_t mem_usage = spp::GetProcessMemoryUsed(); uint64_t alloc_mem_usage = mem_usage - _start_mem_usage; uint64_t expected_mem_usage = total_units * sizeof(T); // finally free the memory // ----------------------- for (size_t i=0; i<_num_alloc; ++i) { _check_buf(_allocated[i], _sizes[i]); _allocator.deallocate(_allocated[i], _sizes[i]); } uint64_t mem_usage_end = spp::GetProcessMemoryUsed(); printf("allocated %zd entities of size %zd\n", total_units, sizeof(T)); printf("done in %3.2f seconds, mem_usage %4.1f/%4.1f/%4.1f MB\n", timer.get_total() / 1000, _to_mb(_start_mem_usage), _to_mb(mem_usage), _to_mb(mem_usage_end)); printf("mem usage: %4.1f, expected mem usage: %4.1f\n", _to_mb(alloc_mem_usage), _to_mb(expected_mem_usage)); if (expected_mem_usage <= alloc_mem_usage) printf("overhead: %4.1f%%\n", (float)((double)(alloc_mem_usage - expected_mem_usage) / expected_mem_usage) * 100); else printf("bug: alloc_mem_usage <= expected_mem_usage\n"); std::vector<T *>().swap(_allocated); std::vector<uint32_t>().swap(_sizes); printf("\nmem usage after freeing vectors: %4.1f\n", _to_mb(spp::GetProcessMemoryUsed())); } private: void _set_buf(T *buff, uint32_t sz) { *buff = (T)sz; buff[sz - 1] = (T)sz; } void _check_buf1(T *buff, uint32_t sz) { assert(*buff == (T)sz); (void)(buff + sz); // silence warning } void _check_buf(T *buff, uint32_t sz) { assert(*buff == (T)sz && buff[sz - 1] == (T)sz); (void)(buff + sz); // silence warning } size_t _num_alloc; uint64_t _start_mem_usage; std::vector<T *> _allocated; std::vector<uint32_t> _sizes; A _allocator; }; // ----------------------------------------------------------- // ----------------------------------------------------------- template <class X, class A> void run_test(const char *alloc_name) { printf("\n---------------- testing %s\n\n", alloc_name); printf("\nmem usage before the alloc test: %4.1f\n", _to_mb(spp::GetProcessMemoryUsed())); { TestAlloc< X, A > test_alloc; test_alloc.run(); } printf("mem usage after the alloc test: %4.1f\n", _to_mb(spp::GetProcessMemoryUsed())); printf("\n\n"); } // ----------------------------------------------------------- // ----------------------------------------------------------- int main() { typedef uint64_t X; run_test<X, spp::libc_allocator<X>>("libc_allocator"); run_test<X, spp::spp_allocator<X>>("spp_allocator"); }
33.369792
111
0.469018
RadoslawChmielarz
7bdba162b837c48ca49d0467939958e31b57a7a0
408
cpp
C++
Leetcode/problem_solving/leetcode_easy_Q448.cpp
Vikash-8090-Yadav/AllProgramming_Basic
76721256edcb91520d1b5132aa59ac37eebdf7c3
[ "MIT" ]
2
2022-01-04T12:04:51.000Z
2022-01-04T18:52:26.000Z
Leetcode/problem_solving/leetcode_easy_Q448.cpp
Vikash-8090-Yadav/AllProgramming_Basic
76721256edcb91520d1b5132aa59ac37eebdf7c3
[ "MIT" ]
null
null
null
Leetcode/problem_solving/leetcode_easy_Q448.cpp
Vikash-8090-Yadav/AllProgramming_Basic
76721256edcb91520d1b5132aa59ac37eebdf7c3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; vector<int> findDisappearedNumbers(vector<int>& nums){ int len = nums.size(); vector<int> v2; unordered_map<int,int> m; for(auto x : nums){ m[x]++; } for(int i =1;i<=len;++i){ if(m[i]==0){ v2.push_back(i); } } return v2; } int main(){ vector<int> v1 ={1,1}; vector<int> v2 =findDisappearedNumbers(v1); for(auto x : v2){ cout<<x<<" "; } }
16.32
54
0.598039
Vikash-8090-Yadav
7bded11f95e69e9b76e45c9d0e63015881e432c6
359
cc
C++
leet_code/Minimum_Swaps_to_Make_Strings_Equal/solve.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
1
2020-04-11T22:04:23.000Z
2020-04-11T22:04:23.000Z
leet_code/Minimum_Swaps_to_Make_Strings_Equal/solve.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
null
null
null
leet_code/Minimum_Swaps_to_Make_Strings_Equal/solve.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
null
null
null
class Solution { public: int minimumSwap(string s1, string s2) { int xy = 0, yx = 0; for (int i = 0; i < s1.length(); ++i) { if (s1[i] == 'x' && s2[i] == 'y') { ++xy; } else if (s1[i] == 'y' && s2[i] == 'x') { ++yx; } } if (xy % 2 == yx % 2) { return (xy / 2) + (yx / 2) + (xy % 2) + (yx % 2); } else { return -1; } } };
17.95
52
0.392758
ldy121
7be4bec1c6efd3175475046cf14766102156ba75
1,774
cpp
C++
modules/ReadLine/readline.cpp
Rod-Lin/Ink
527b258afc35b3d2a723d198c54cfb57bdaac127
[ "MIT" ]
1
2016-01-01T02:23:55.000Z
2016-01-01T02:23:55.000Z
modules/ReadLine/readline.cpp
Rod-Lin/Ink
527b258afc35b3d2a723d198c54cfb57bdaac127
[ "MIT" ]
null
null
null
modules/ReadLine/readline.cpp
Rod-Lin/Ink
527b258afc35b3d2a723d198c54cfb57bdaac127
[ "MIT" ]
null
null
null
#include <readline/readline.h> #include <readline/history.h> #include <string> #include "core/object.h" #include "core/general.h" #include "core/native/native.h" #include "core/interface/engine.h" using namespace ink; using namespace std; Ink_Object *InkNative_ReadLine_Read(Ink_InterpreteEngine *engine, Ink_ContextChain *context, Ink_Object *base, Ink_ArgcType argc, Ink_Object **argv, Ink_Object *this_p) { if (!checkArgument(engine, argc, argv, 1, INK_STRING)) { return NULL_OBJ; } string pmt = as<Ink_String>(argv[0])->getValue(); char *ret_val = readline(pmt.c_str()); Ink_Object *ret = NULL_OBJ; if (!ret_val || !*ret_val) { goto CLEAN; } ret = new Ink_String(engine, string(ret_val)); add_history(ret_val); CLEAN: if (ret_val) free(ret_val); return ret; } void InkMod_ReadLine_bondTo(Ink_InterpreteEngine *engine, Ink_Object *bondee) { bondee->setSlot_c("read", new Ink_FunctionObject(engine, InkNative_ReadLine_Read)); return; } Ink_Object *InkMod_ReadLine_Loader(Ink_InterpreteEngine *engine, Ink_ContextChain *context, Ink_Object *base, Ink_ArgcType argc, Ink_Object **argv, Ink_Object *this_p) { if (!checkArgument(engine, argc, 2)) { return NULL_OBJ; } Ink_Object *apply_to = argv[1]; Ink_Object *readline_pkg = addPackage(engine, apply_to, "readline", new Ink_FunctionObject(engine, InkMod_ReadLine_Loader)); InkMod_ReadLine_bondTo(engine, readline_pkg); return NULL_OBJ; } extern "C" { static Ink_ModuleID ink_native_readline_mod_id; void InkMod_Loader(Ink_InterpreteEngine *engine, Ink_ContextChain *context) { addPackage(engine, context, "readline", new Ink_FunctionObject(engine, InkMod_ReadLine_Loader)); return; } int InkMod_Init(Ink_ModuleID id) { ink_native_readline_mod_id = id; return 0; } }
24.30137
168
0.756483
Rod-Lin
7be68f6b9e8eff8c84d7be9bafd1c1d3100c6fb6
463
cpp
C++
Introduction to CPP/Easy/Vector_Erase.cpp
voids-solutions/Hacker-Rank-Solutions
05ac3b61890c7b032ca22166184090428ddcfcbd
[ "Unlicense" ]
1
2019-04-07T20:13:20.000Z
2019-04-07T20:13:20.000Z
Introduction to CPP/Easy/Vector_Erase.cpp
voids-solutions/Hacker-Rank-Solutions
05ac3b61890c7b032ca22166184090428ddcfcbd
[ "Unlicense" ]
null
null
null
Introduction to CPP/Easy/Vector_Erase.cpp
voids-solutions/Hacker-Rank-Solutions
05ac3b61890c7b032ca22166184090428ddcfcbd
[ "Unlicense" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { vector<int> vec; int x,a,b,c,temp; cin >>x; for (size_t i = 0; i < x; i++) { cin >>temp; vec.push_back(temp); } cin >>a>>b>>c; vec.erase(vec.begin()+a-1); vec.erase(vec.begin()+b-1,vec.begin()+c-1); cout <<vec.size()<<endl; for(auto a:vec) cout <<a<<" "; return 0; }
17.148148
47
0.533477
voids-solutions
7becd015a53697294f33a8e3e85f56546484eefb
4,501
cpp
C++
src/Screens/MusicSelect/Options/OptionPage.cpp
Subject38/jujube
664b995cc65fa6045433b4837d765c62fe6490b4
[ "MIT" ]
19
2020-02-28T20:34:12.000Z
2022-01-28T20:18:25.000Z
src/Screens/MusicSelect/Options/OptionPage.cpp
Subject38/jujube
664b995cc65fa6045433b4837d765c62fe6490b4
[ "MIT" ]
7
2019-10-22T09:43:16.000Z
2022-03-12T00:15:13.000Z
src/Screens/MusicSelect/Options/OptionPage.cpp
Subject38/jujube
664b995cc65fa6045433b4837d765c62fe6490b4
[ "MIT" ]
5
2019-10-22T08:14:57.000Z
2021-03-13T06:32:04.000Z
#include "OptionPage.hpp" #include <iostream> #include <memory> #include <vector> #include "../Ribbon.hpp" #include "../Panels/SubpagePanel.hpp" #include "../Panels/MarkerPanel.hpp" #include "AudioOffset.hpp" #include "InputRemap.hpp" namespace MusicSelect { void OptionPage::update() { this->setPosition(get_ribbon_x(), get_ribbon_y()); } RibbonPage::RibbonPage(const PanelLayout& layout, ScreenResources& t_resources) : OptionPage(t_resources), m_ribbon(layout, t_resources), back_button(t_resources) { } bool MusicSelect::RibbonPage::handle_raw_input(const sf::Event::KeyEvent& key_event) { auto button = preferences.key_mapping.key_to_button(key_event.code); if (not button) { return false; } auto button_index = Input::button_to_index(*button); if (button_index > 13) { return false; } button_click(*button); return true; } void RibbonPage::button_click(const Input::Button& button) { shared.button_highlight.button_pressed(button); auto button_index = Input::button_to_index(button); if (button_index < 12) { m_ribbon.click_on(button); } else { switch (button) { case Input::Button::B13: m_ribbon.move_left(); break; case Input::Button::B14: m_ribbon.move_right(); break; default: break; } } } void RibbonPage::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); target.draw(m_ribbon, states); back_button.setPosition(2.f*get_panel_step(), 3.f*get_panel_step()); target.draw(back_button, states); } MainOptionPage::MainOptionPage(ScreenResources& t_resources) : RibbonPage(MainOptionPage::create_layout(t_resources), t_resources) { } PanelLayout MainOptionPage::create_layout(ScreenResources& t_resources) { std::vector<std::shared_ptr<Panel>> subpages; auto marker_select = std::make_shared<MarkerSelect>(t_resources); subpages.emplace_back(std::make_shared<SubpagePanel>(t_resources, std::move(marker_select), "markers")); auto input_page = std::make_shared<InputOptionPage>(t_resources); subpages.emplace_back(std::make_shared<SubpagePanel>(t_resources, std::move(input_page), "input")); auto audio_page = std::make_shared<AudioOptionPage>(t_resources); subpages.emplace_back(std::make_shared<SubpagePanel>(t_resources, std::move(audio_page), "audio")); return PanelLayout{subpages, t_resources}; } InputOptionPage::InputOptionPage(ScreenResources& t_resources) : RibbonPage(InputOptionPage::create_layout(t_resources), t_resources) { } PanelLayout InputOptionPage::create_layout(ScreenResources& t_resources) { std::vector<std::shared_ptr<Panel>> subpages; auto input_remap = std::make_shared<InputRemap>(t_resources); subpages.emplace_back(std::make_shared<SubpagePanel>(t_resources, std::move(input_remap), "remap\nbuttons")); return PanelLayout{subpages, t_resources}; } MarkerSelect::MarkerSelect(ScreenResources& t_resources) : RibbonPage(MarkerSelect::create_layout(t_resources), t_resources) { } MarkerSelect::~MarkerSelect() { resources.selected_marker.reset(); } PanelLayout MarkerSelect::create_layout(ScreenResources& t_resources) { std::vector<std::shared_ptr<Panel>> markers; for (const auto &[name, marker] : t_resources.shared.markers) { markers.emplace_back(std::make_shared<MarkerPanel>(t_resources, marker)); } return PanelLayout{markers, t_resources}; } AudioOptionPage::AudioOptionPage(ScreenResources& t_resources) : RibbonPage(AudioOptionPage::create_layout(t_resources), t_resources) { } PanelLayout AudioOptionPage::create_layout(ScreenResources& t_resources) { std::vector<std::shared_ptr<Panel>> subpages; auto audio_offset = std::make_shared<AudioOffset>(t_resources); subpages.emplace_back( std::make_shared<SubpagePanel>( t_resources, std::move(audio_offset), "audio\noffset" ) ); return PanelLayout{subpages, t_resources}; } }
35.164063
117
0.65341
Subject38
7beda22fc0e27a949e1cf4e5e51de920dfcec6eb
656
cpp
C++
examples/array/validator.cpp
fushar/tokilib
1fcb3f9da6007350b5ae4aacd5e85803326a006f
[ "MIT" ]
16
2015-08-09T05:22:01.000Z
2022-03-30T08:51:43.000Z
examples/array/validator.cpp
fushar/tokilib
1fcb3f9da6007350b5ae4aacd5e85803326a006f
[ "MIT" ]
3
2015-08-08T15:46:05.000Z
2015-08-08T15:46:06.000Z
examples/array/validator.cpp
fushar/tokilib
1fcb3f9da6007350b5ae4aacd5e85803326a006f
[ "MIT" ]
11
2015-11-15T08:30:35.000Z
2022-03-30T08:51:54.000Z
/* * Test Case Validator via tokilib * * Problem: Array * Problem author: TOKI Scientific Committee * Validator author: TOKI Scientific Committee */ #include "../../validator.h" int N_max, data_max; void validateCase() { int N = inf.readInt(1, N_max, "N"); inf.readEoln(); for (int i = 0; i < N; i++) { inf.readInt(1, data_max, format("data[%d]", i)); if (i + 1 < N) inf.readSpace(); } inf.readEoln(); inf.readEof(); } int main(int argc, char* argv[]) { beginValidator(argc, argv); beginSubtask(); { N_max = 1e3; data_max = 1e3; } endSubtask(); beginSubtask(); { N_max = 1e5; data_max = 1e9; } endSubtask(); endValidator(); }
18.742857
63
0.628049
fushar
7bf023bd40c7e7a78ac7150fe64d4035009fb078
9,440
hpp
C++
include/ripple/container/array_traits.hpp
robclu/ripple
734dfa77e100a86b3c60589d41ca627e41d4a783
[ "MIT" ]
4
2021-04-25T16:38:12.000Z
2021-12-23T08:32:15.000Z
include/ripple/container/array_traits.hpp
robclu/ripple
734dfa77e100a86b3c60589d41ca627e41d4a783
[ "MIT" ]
null
null
null
include/ripple/container/array_traits.hpp
robclu/ripple
734dfa77e100a86b3c60589d41ca627e41d4a783
[ "MIT" ]
null
null
null
/**=--- ripple/container/array_traits.hpp ------------------ -*- C++ -*- ---==** * * Ripple * * Copyright (c) 2019 - 2021 Rob Clucas. * * This file is distributed under the MIT License. See LICENSE for details. * *==-------------------------------------------------------------------------==* * * \file array_traits.hpp * \brief This file defines forward declarations and traits for arrays. * *==------------------------------------------------------------------------==*/ #ifndef RIPPLE_CONTAINER_ARRAY_TRAITS_HPP #define RIPPLE_CONTAINER_ARRAY_TRAITS_HPP #include <ripple/storage/storage_layout.hpp> #include <ripple/utility/number.hpp> namespace ripple { /*==--- [forward declarations] ---------------------------------------------==*/ /** * The Array class defines a static interface for array types -- essentially * types which have contiguous storage and can be accessed with the index * operator. * * The implementation is provided by the template type Impl. * \tparam Impl The implementation of the array interface. */ template <typename Impl> struct Array; /** * This is an implementation class for a statically sized vector class with a * flexible storage layout. * * \note This is an implementation class, there are aliases for vectors, * \sa Vector, \sa Vec. * * \tparam T The type of the data for the vector. * \tparam Size The size of the vector. * \tparam Layout The storage layout of the vector. */ template <typename T, typename Size, typename Layout = ContiguousOwned> struct VecImpl; /*==--- [traits] -----------------------------------------------------------==*/ /** * This structs defines traits for arrays. This implementation is the default * implementation and is for a type which is not an array. It needs to be * specialzied for any type which does implement the interface. * * \tparam T The type to get the array traits for. */ template <typename T> struct ArrayTraits { // clang-format off /** The value type for the array. */ using Value = std::decay_t<T>; /** Defines the type of the layout for the array. */ using Layout = ContiguousOwned; /** Defines the type for an array of type T */ using Array = VecImpl<Value, Num<1>, Layout>; /** * A type with the same type as the implementation with the given number of * elements and layout. * \tparam Elements The number of elements in the vector. * \tparam L The layout for the the vector. */ template <size_t Elements, typename L = ContiguousOwned> using ImplType = VecImpl<Value, Num<Elements>, L>; /** Returns the number of elements in the array. */ static constexpr auto size = 1; // clang-format on }; /** * Specialization of the ArrayTraits class for the VecImpl class. * * \tparam T The type of the data for the vec. * \tparam Size The size of the vector. * \tparam Layout The storage layout of the vector. */ template <typename T, typename Size, typename LayoutType> struct ArrayTraits<VecImpl<T, Size, LayoutType>> { // clang-format off /** The value type stored in the array. */ using Value = std::decay_t<T>; /** Defines the type of the layout for the array. */ using Layout = LayoutType; /** Defines the type of an array of the value type. */ using Array = VecImpl<Value, Size, Layout>; /** * A type with the same type as the implementation with the given number of * elements and layout. * \tparam Elements The number of elements in the vector. * \tparam L The layout for the the vector. */ template <size_t Elements, typename L = ContiguousOwned> using ImplType = VecImpl<Value, Num<Elements>, L>; /** Returns the number of elements in the array. */ static constexpr auto size = Size::value; // clang-format on }; /** * Specialization of the ArrayTraits class for the any class which implements * the array interface. * * \tparam Impl The implementation type of the array interface. */ template <typename Impl> struct ArrayTraits<Array<Impl>> { private: /** Defines the type of the implementation traits. */ using Traits = ArrayTraits<Impl>; public: // clang-format off /** Defines the value type of the array. */ using Value = typename Traits::Value; /** Defines the type of the layout for the array. */ using Layout = typename Traits::Layout; /** Defines the type of an array of the value type. */ using Array = typename Traits::Array; /** * A type with the same type as the implementation with the given number of * elements and layout. * \tparam Elements The number of elements in the vector. * \tparam L The layout for the the vector. */ template <size_t Elements, typename L = ContiguousOwned> using ImplType = typename Traits::template ImplType<Elements, L>; /** Returns the number of elements in the array. */ static constexpr auto size = Traits::size; // clang-format on }; /*==--- [aliases & constants] ----------------------------------------------==*/ /** * Alias for a vector to store data of type T with Size elements. * * \note This uses the default layout type for the vector. * * \tparam T The type to store in the vector. * \tparam Size The size of the vector. */ template <typename T, size_t Size, typename Layout = ContiguousOwned> using Vec = VecImpl<T, Num<Size>, Layout>; /** * Defines an alias to create a contiguous 1D vector of type T. * \tparam T The type of the data for the vector. * \tparam Layout The layout for the vector. */ template <typename T, typename Layout = ContiguousOwned> using Vec1d = VecImpl<T, Num<1>, Layout>; /** * Defines an alias to create a contiguous 2D vector of type T. * \tparam T The type of the data for the vector. * \tparam Layout The layout for the vector. */ template <typename T, typename Layout = ContiguousOwned> using Vec2d = VecImpl<T, Num<2>, Layout>; /** * Defines an alias to create a contiguous 3D vector of type T. * \tparam T The type of the data for the vector. * \tparam Layout The layout for the vector. */ template <typename T, typename Layout = ContiguousOwned> using Vec3d = VecImpl<T, Num<3>, Layout>; /** * Gets the array traits for the type T. * \tparam T The type to get the array traits for. */ template <typename T> using array_traits_t = ArrayTraits<std::decay_t<T>>; /** * Returns true if the template parameter is an Array. * \tparam T The type to determine if is an array. */ template <typename T> static constexpr bool is_array_v = std::is_base_of_v<Array<std::decay_t<T>>, std::decay_t<T>>; /** * Defines a fallback vector type based on the type T. * \tparam T The type to base the fallback on. */ template <typename T, typename Traits = array_traits_t<T>> using VecFallback = VecImpl<typename Traits::Value, Num<Traits::size>, ContiguousOwned>; /** * Returns an implementation type which is copyable and trivially constructable * between implementations ImplA and ImplB. This will first check the valididy * of ImplA, and then of ImplB. * * An implementation is valid if the storage type of the implementation is * **not** a pointer (since the data for the pointer will then need to be * allocaed) and **is** trivially constructible. * * If neither ImplA nor ImplB are valid, then this will default to using the * Vec type with a value type of ImplA and a the size of ImplA. * * \tparam ImplA The type of the first array implementation. * \tparam ImplB The type of the second array implementation. */ template < typename ImplA, typename ImplB, typename LayoutA = typename array_traits_t<ImplA>::Layout, typename LayoutB = typename array_traits_t<ImplB>::Layout, bool ValidityA = std::is_same_v<LayoutA, ContiguousOwned>, bool ValidityB = std::is_same_v<LayoutB, ContiguousOwned>, typename Fallback = VecFallback<ImplA>> using array_impl_t = std::conditional_t< ValidityA, ImplA, std::conditional_t<ValidityB, ImplB, Fallback>>; /*==--- [enables] ----------------------------------------------------------==*/ /** * Defines a valid type if the type T is either the same as the value type of * the array implementation Impl, or convertible to the value type. * * \tparam T The type to base the enable on. * \tparam Impl The array implementation to get the value type from. */ template < typename T, typename Impl, typename Type = std::decay_t<T>, typename Value = typename ArrayTraits<Impl>::Value> using array_value_enable_t = std::enable_if_t< (std::is_same_v<Type, Value> || std::is_convertible_v<Type, Value>)&&!is_array_v<Type>, int>; /** * Defines a valid type if the type T is an array. * \tparam T The type to base the enable on. */ template <typename T> using array_enable_t = std::enable_if_t<is_array_v<T>, int>; /** * Defines a valid type if the type T is _not_ an array. * \tparam T The type to base the enable on. */ template <typename T> using non_array_enable_t = std::enable_if_t<!is_array_v<T>, int>; /** * Defines a valid type if the type T is an array and the size of the array is * Size. * \tparam T The type to check if is an array. * \tparam Size The size the array must have. */ template <typename T, size_t Size> using array_size_enable_t = std::enable_if_t<is_array_v<T> && (array_traits_t<T>::size == Size), int>; } // namespace ripple #endif // RIPPLE_CONTAINER_ARRAY_TRAITS_HPP
33.239437
80
0.66928
robclu
7bf2d2a01e2861c008f227ee1be9c110408f24a0
1,381
cc
C++
tests/cc/swap.cc
project-arcana/arcana-samples
7dbe2cab765d4d86c6e96b4ab542cac75608a0b0
[ "MIT" ]
2
2019-08-06T08:13:27.000Z
2019-09-28T07:16:46.000Z
tests/swap.cc
Philip-Trettner/clean-core
dc70db2432e753f1d77a722070c398464590e0a1
[ "MIT" ]
null
null
null
tests/swap.cc
Philip-Trettner/clean-core
dc70db2432e753f1d77a722070c398464590e0a1
[ "MIT" ]
1
2020-01-22T18:04:53.000Z
2020-01-22T18:04:53.000Z
#include <nexus/test.hh> #include <clean-core/utility.hh> #include <clean-core/vector.hh> #include <vector> namespace foo { bool used_custom_swap = false; struct bar { }; void swap(bar&, bar&) { used_custom_swap = true; } } namespace fuz { struct baz { }; } TEST("cc::swap") { foo::bar a, b; // found via ADL foo::used_custom_swap = false; swap(a, b); CHECK(foo::used_custom_swap); // std::swap does NOT find via ADL foo::used_custom_swap = false; std::swap(a, b); CHECK(!foo::used_custom_swap); // cc::swap finds via ADL foo::used_custom_swap = false; cc::swap(a, b); CHECK(foo::used_custom_swap); cc::vector<int> u, v; // swap(u, v); - ERROR: no adl swap std::swap(u, v); // OK via move cc::swap(u, v); // OK via move } TEST("cc::swap - using std::swap") { using std::swap; foo::bar a, b; // found via ADL foo::used_custom_swap = false; swap(a, b); CHECK(foo::used_custom_swap); // std::swap does NOT find via ADL foo::used_custom_swap = false; std::swap(a, b); CHECK(!foo::used_custom_swap); // cc::swap finds via ADL foo::used_custom_swap = false; cc::swap(a, b); CHECK(foo::used_custom_swap); cc::vector<int> u, v; swap(u, v); // OK, uses std::move std::swap(u, v); // OK via move cc::swap(u, v); // OK via move }
18.413333
50
0.589428
project-arcana
7bf6b5fd532c0961967365c3af1dd31c1a4a7d93
759
cpp
C++
Dev/src/Core/assert.cpp
MarkusRannare/FryEngine
79f60599c1cd5f4f28714f24916950461d5cbbba
[ "MIT" ]
1
2021-12-20T14:21:41.000Z
2021-12-20T14:21:41.000Z
Dev/src/Core/assert.cpp
MarkusRannare/FryEngine
79f60599c1cd5f4f28714f24916950461d5cbbba
[ "MIT" ]
null
null
null
Dev/src/Core/assert.cpp
MarkusRannare/FryEngine
79f60599c1cd5f4f28714f24916950461d5cbbba
[ "MIT" ]
null
null
null
#include "Assert.h" #include "Debug.h" #include "message_box.h" #include "string_stream.h" #include <cstdlib> using namespace foundation; namespace fry_core { void Assert( const char* Expression, const char* File, int Line ) { using namespace string_stream; Buffer B( foundation::memory_globals::default_allocator() ); B << "Assertion failed: " << Expression << "\n\n" << File << ":" << Line; message_box::EButtonPressed ButtonPressed = message_box::Show( c_str( B ), "Assertion failed", message_box::B_CancelTryAgainContinue | message_box::I_Error ); if( ButtonPressed == message_box::BP_Continue ) { TOGGLE_BREAKPOINT(); std::exit( -1 ); } else if( ButtonPressed == message_box::BP_Cancel ) { std::exit( -1 ); } } }
23.71875
160
0.682477
MarkusRannare
7bf736ec7e5c1175e6a45af2f03054acca6691bc
350
cpp
C++
yarpl/src/yarpl/Refcounted.cpp
benjchristensen/rsocket-cpp
26299669be5c9df67d11fa105deb5f453436803d
[ "BSD-3-Clause" ]
null
null
null
yarpl/src/yarpl/Refcounted.cpp
benjchristensen/rsocket-cpp
26299669be5c9df67d11fa105deb5f453436803d
[ "BSD-3-Clause" ]
null
null
null
yarpl/src/yarpl/Refcounted.cpp
benjchristensen/rsocket-cpp
26299669be5c9df67d11fa105deb5f453436803d
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2004-present Facebook. All Rights Reserved. #include "yarpl/Refcounted.h" namespace yarpl { #if !defined(NDEBUG) Refcounted::Refcounted() { ++objects_; } Refcounted::~Refcounted() { --objects_; } size_t Refcounted::objects() { return objects_; } std::atomic_size_t Refcounted::objects_{0}; #endif /* !NDEBUG */ } // yarpl
13.461538
56
0.688571
benjchristensen
7bfa613c902f2e9d0d1b13c4c8bfdfa46a4d091e
1,556
cpp
C++
server/src/cache_support_filter.cpp
courtarro/beefweb
879f68d8be5339c73b02bf32c9fa39027cd66fab
[ "MIT" ]
148
2017-08-25T13:32:05.000Z
2022-03-17T18:40:49.000Z
server/src/cache_support_filter.cpp
courtarro/beefweb
879f68d8be5339c73b02bf32c9fa39027cd66fab
[ "MIT" ]
160
2017-08-16T19:58:53.000Z
2022-02-26T09:57:38.000Z
server/src/cache_support_filter.cpp
courtarro/beefweb
879f68d8be5339c73b02bf32c9fa39027cd66fab
[ "MIT" ]
24
2018-05-23T18:59:47.000Z
2022-03-23T17:25:01.000Z
#include "cache_support_filter.hpp" #include "request.hpp" #include "response.hpp" #include "fnv_hash.hpp" namespace msrv { CacheSupportFilter::CacheSupportFilter() = default; CacheSupportFilter::~CacheSupportFilter() = default; void CacheSupportFilter::endRequest(Request* request) { FileResponse* fileResponse = dynamic_cast<FileResponse*>(request->response.get()); if (!fileResponse) return; auto etagValue = calculateETag(fileResponse); auto ifNoneMatchValue = request->getHeader(HttpHeader::IF_NONE_MATCH); if (ifNoneMatchValue == etagValue) { auto notModifiedResponse = Response::custom(HttpStatus::S_304_NOT_MODIFIED); setCacheHeaders(notModifiedResponse.get(), etagValue); request->response = std::move(notModifiedResponse); } else { setCacheHeaders(fileResponse, etagValue); } } void CacheSupportFilter::setCacheHeaders(Response* reponse, const std::string& etag) { reponse->headers[HttpHeader::CACHE_CONTROL] = "max-age=3, must-revalidate"; reponse->headers[HttpHeader::ETAG] = etag; } std::string CacheSupportFilter::calculateETag(FileResponse* response) { const auto& pathString = response->path.native(); FnvHash hash; hash.addBytes(pathString.data(), pathString.size() * sizeof(Path::value_type)); hash.addValue(response->info.size); hash.addValue(response->info.timestamp); hash.addValue(response->info.inode); std::stringstream etag; etag << '"' << std::hex << hash.value() << '"'; return etag.str(); } }
28.290909
86
0.706298
courtarro
d00e503e1f37bc9361d0c1c3ed8e343cf4cbecc5
3,898
cpp
C++
Chapter05/standard_algorithm_features.cpp
markusbuchholz/Cpp-High-Performance-Second-Edition
9d8ce97fae15a5f893a780fb3f8b187d11961a43
[ "MIT" ]
57
2020-07-09T22:54:31.000Z
2022-03-31T14:18:41.000Z
Chapter05/standard_algorithm_features.cpp
markusbuchholz/Cpp-High-Performance-Second-Edition
9d8ce97fae15a5f893a780fb3f8b187d11961a43
[ "MIT" ]
5
2021-04-02T17:25:31.000Z
2021-07-30T09:38:42.000Z
Chapter05/standard_algorithm_features.cpp
PacktPublishing/Cpp-High-Performance-Second-Edition
9d8ce97fae15a5f893a780fb3f8b187d11961a43
[ "MIT" ]
36
2019-12-25T19:30:47.000Z
2022-03-16T16:41:02.000Z
// Requires C++20 #include <version> #if defined(__cpp_lib_ranges) #include <gtest/gtest.h> #include <algorithm> #include <iostream> #include <list> #include <numeric> #include <ranges> #include <vector> TEST(AlgorithmFeatures, RemoveErase) { auto v = std::vector{1, 2, 2, 3}; auto new_end = std::remove(v.begin(), v.end(), 2); v.erase(new_end, v.end()); auto result = std::vector{1, 3}; ASSERT_EQ(v, result); } TEST(AlgorithmFeatures, RemoveEraseUsingRanges) { auto v = std::vector{1, 2, 2, 3}; auto r = std::ranges::remove(v, 2); v.erase(r.begin(), r.end()); auto result = std::vector{1, 3}; ASSERT_EQ(v, result); } TEST(AlgorithmFeatures, UniqueErase) { auto v = std::vector{1, 2, 2, 3}; auto new_end = std::unique(v.begin(), v.end()); v.erase(new_end, v.end()); auto result = std::vector{1, 2, 3}; ASSERT_EQ(v, result); } TEST(AlgorithmFeatures, UniqueEraseUsingRanges) { auto v = std::vector{1, 2, 2, 3}; auto r = std::ranges::unique(v); v.erase(r.begin(), r.end()); auto result = std::vector{1, 2, 3}; ASSERT_EQ(v, result); } TEST(AlgorithmFeatures, PreAllocateSpace) { auto v = std::vector{1, 2, 3, 4}; auto squared = std::vector<int>{}; squared.resize(v.size()); std::transform(v.begin(), v.end(), squared.begin(), [](int x) { return x * x; }); auto result = std::vector{1, 4, 9, 16}; ASSERT_EQ(squared, result); } TEST(AlgorithmFeatures, BackInserter) { auto square = [](int x) { return x * x; }; auto v = std::vector{1, 2, 3, 4}; // Insert into std::vector auto squared_vec = std::vector<int>{}; std::ranges::transform(v, std::back_inserter(squared_vec), square); // Insert into std::set auto squared_set = std::set<int>{}; std::ranges::transform(v, std::inserter(squared_set, squared_set.end()), square); } // operator<() and operator==() TEST(AlgorithmFeatures, ComparisonOperators) { struct Flower { auto operator<=>(const Flower& f) const = default; bool operator==(const Flower&) const = default; int height_{}; }; auto garden = std::vector<Flower>{{67}, {28}, {14}}; // std::max_element() uses operator<() auto tallest = std::max_element(garden.begin(), garden.end()); // std::find() uses operator==() auto perfect = *std::find(garden.begin(), garden.end(), Flower{28}); } TEST(AlgorithmFeatures, CustomComparatorFunctions) { auto names = std::vector<std::string>{"Ralph", "Lisa", "Homer", "Maggie", "Apu", "Bart"}; std::sort(names.begin(), names.end(), [](const std::string& a, const std::string& b) { return a.size() < b.size(); }); // names is now "Apu", "Lisa", "Bart", "Ralph", "Homer", "Maggie" // Find names with length 3 auto x = std::find_if(names.begin(), names.end(), [](const auto& v) { return v.size() == 3; }); // x points to "Apu" ASSERT_EQ(*x, "Apu"); } TEST(AlgorithmFeatures, Projections) { auto names = std::vector<std::string>{"Ralph", "Lisa", "Homer", "Maggie", "Apu", "Bart"}; std::ranges::sort(names, std::less<>{}, &std::string::size); // names is now "Apu", "Lisa", "Bart", "Ralph", "Homer", "Maggie" // Find names with length 3 auto x = std::ranges::find(names, 3, &std::string::size); ASSERT_EQ(*x, "Apu"); } TEST(AlgorithmFeatures, LambdaProjections) { struct Player { std::string name{}; int level{}; float health{1.0f}; // … }; auto players = std::vector<Player>{ {"Aki", 1, 9.f}, {"Nao", 2, 7.f}, {"Rei", 2, 3.f}}; auto level_and_health = [](const Player& p) { return std::tie(p.level, p.health); }; // Order players by level, then health std::ranges::sort(players, std::greater<>{}, level_and_health); ASSERT_EQ(players.front().name, "Nao"); } #endif // ranges
27.069444
74
0.592612
markusbuchholz
d010fc722b5a3de9fb104ff8d42937dedb4da325
5,484
cpp
C++
src/to_420.cpp
stevenhoving/yuvconvert
40d36ee0fc036b10f128c3aabe346b93748afde0
[ "MIT" ]
3
2020-01-28T16:54:53.000Z
2020-12-22T06:45:39.000Z
src/to_420.cpp
stevenhoving/yuvconvert
40d36ee0fc036b10f128c3aabe346b93748afde0
[ "MIT" ]
1
2018-09-16T13:54:22.000Z
2018-09-16T13:54:22.000Z
src/to_420.cpp
stevenhoving/yuvconvert
40d36ee0fc036b10f128c3aabe346b93748afde0
[ "MIT" ]
null
null
null
/* Copyright(c) 2018 Steven Hoving * * 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 "to_420.h" #include "to_420_c.h" #include "to_420_ssse3.h" #include "yuvconvert.h" namespace yuvconvert { using bgrx_row_to_y_row = void(const unsigned char *src, unsigned char *dst, const int width); using bgrx_row_to_yuv_row = void(const unsigned char *src, unsigned char *dst_y, unsigned char *dst_u, unsigned char *dst_v, const int width); void bgra_to_420(unsigned char *destination[3], const int dst_stride[3], const unsigned char *const source[3], const int width, const int height, const int src_stride[3]) { auto src = source[0]; auto y = destination[0]; auto u = destination[1]; auto v = destination[2]; const auto raw_stride = src_stride[0]; const auto y_stride = dst_stride[0]; const auto u_stride = dst_stride[1]; const auto v_stride = dst_stride[2]; for (int line = 0; line < height; line += 2) { bgra_row_to_yuv_row_c(src, y, u, v, width); src += raw_stride; y += y_stride; u += u_stride; v += v_stride; bgra_row_to_y_row_c(src, y, width); src += raw_stride; y += y_stride; } } void bgr_to_420(unsigned char *destination[3], const int dst_stride[3], const unsigned char *const source[3], const int width, const int height, const int src_stride[3]) { auto src = source[0]; auto y = destination[0]; auto u = destination[1]; auto v = destination[2]; const auto raw_stride = src_stride[0]; const auto y_stride = dst_stride[0]; const auto u_stride = dst_stride[1]; const auto v_stride = dst_stride[2]; for (int line = 0; line < height; line += 2) { bgr_row_to_yuv_row_c(src, y, u, v, width); src += raw_stride; y += y_stride; u += u_stride; v += v_stride; bgr_row_to_y_row_c(src, y, width); src += raw_stride; y += y_stride; } } void bgr_to_420(unsigned char *destination[3], const int dst_stride[3], const unsigned char *const source[3], const int width, const int height, const int src_stride[3], simd_mode mode /*= simd_mode::plain_c*/) { auto src = source[0]; auto y = destination[0]; auto u = destination[1]; auto v = destination[2]; const auto raw_stride = src_stride[0]; const auto y_stride = dst_stride[0]; const auto u_stride = dst_stride[1]; const auto v_stride = dst_stride[2]; bgrx_row_to_yuv_row *yuv_row_converter = nullptr; bgrx_row_to_y_row *y_row_converter = nullptr; if (mode == simd_mode::plain_c) { yuv_row_converter = bgr_row_to_yuv_row_c; y_row_converter = bgr_row_to_y_row_c; } else if (mode == simd_mode::ssse3) { yuv_row_converter = bgr_row_to_yuv_row_ssse3; y_row_converter = bgr_row_to_y_row_ssse3; } for (int line = 0; line < height; line += 2) { yuv_row_converter(src, y, u, v, width); src += raw_stride; y += y_stride; u += u_stride; v += v_stride; y_row_converter(src, y, width); src += raw_stride; y += y_stride; } } void bgra_to_420(unsigned char *destination[3], const int dst_stride[3], const unsigned char *const source[3], const int width, const int height, const int src_stride[3], simd_mode mode /*= simd_mode::plain_c*/) { auto src = source[0]; auto y = destination[0]; auto u = destination[1]; auto v = destination[2]; const auto raw_stride = src_stride[0]; const auto y_stride = dst_stride[0]; const auto u_stride = dst_stride[1]; const auto v_stride = dst_stride[2]; bgrx_row_to_yuv_row *yuv_row_converter = nullptr; bgrx_row_to_y_row *y_row_converter = nullptr; if (mode == simd_mode::plain_c) { yuv_row_converter = bgra_row_to_yuv_row_c; y_row_converter = bgra_row_to_y_row_c; } else if (mode == simd_mode::ssse3) { yuv_row_converter = bgra_row_to_yuv_row_ssse3; y_row_converter = bgra_row_to_y_row_ssse3; } for (int line = 0; line < height; line += 2) { yuv_row_converter(src, y, u, v, width); src += raw_stride; y += y_stride; u += u_stride; v += v_stride; y_row_converter(src, y, width); src += raw_stride; y += y_stride; } } } // namespace yuvconvert
33.036145
142
0.652443
stevenhoving
d01cb9d1d05d4fcf90117b4fa4bca9a2876427a7
50,374
cpp
C++
src/server/game/DataStores/DBCStores.cpp
Arkania/ArkCORE
2484554a7b54be0b652f9dc3c5a8beba79df9fbf
[ "OpenSSL" ]
42
2015-01-05T10:00:07.000Z
2022-02-18T14:51:33.000Z
src/server/game/DataStores/DBCStores.cpp
superllout/WOW
3d0eeb940cccf8ab7854259172c6d75a85ee4f7d
[ "OpenSSL" ]
null
null
null
src/server/game/DataStores/DBCStores.cpp
superllout/WOW
3d0eeb940cccf8ab7854259172c6d75a85ee4f7d
[ "OpenSSL" ]
31
2015-01-09T02:04:29.000Z
2021-09-01T13:20:20.000Z
/* * Copyright (C) 2005 - 2013 MaNGOS <http://www.getmangos.com/> * * Copyright (C) 2008 - 2013 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2010 - 2013 ProjectSkyfire <http://www.projectskyfire.org/> * * Copyright (C) 2011 - 2013 ArkCORE <http://www.arkania.net/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "gamePCH.h" #include "DBCStores.h" #include "Logging/Log.h" #include "SharedDefines.h" #include "SpellMgr.h" #include "DBCfmt.h" #include <map> typedef std::map<uint16, uint32> AreaFlagByAreaID; typedef std::map<uint32, uint32> AreaFlagByMapID; struct WMOAreaTableTripple { WMOAreaTableTripple (int32 r, int32 a, int32 g) : groupId(g), rootId(r), adtId(a) { } bool operator < (const WMOAreaTableTripple& b) const { return memcmp(this, &b, sizeof(WMOAreaTableTripple)) < 0; } // ordered by entropy; that way memcmp will have a minimal medium runtime int32 groupId; int32 rootId; int32 adtId; }; typedef std::map<WMOAreaTableTripple, WMOAreaTableEntry const *> WMOAreaInfoByTripple; DBCStorage<AreaTableEntry> sAreaStore(AreaTableEntryfmt); DBCStorage<AreaGroupEntry> sAreaGroupStore(AreaGroupEntryfmt); DBCStorage<AreaPOIEntry> sAreaPOIStore(AreaPOIEntryfmt); static AreaFlagByAreaID sAreaFlagByAreaID; static AreaFlagByMapID sAreaFlagByMapID; // for instances without generated *.map files static WMOAreaInfoByTripple sWMOAreaInfoByTripple; DBCStorage<AchievementEntry> sAchievementStore(Achievementfmt); DBCStorage<AchievementCriteriaEntry> sAchievementCriteriaStore(AchievementCriteriafmt); DBCStorage<AreaTriggerEntry> sAreaTriggerStore(AreaTriggerEntryfmt); DBCStorage<ArmorLocationEntry> sArmorLocationStore(ArmorLocationfmt); DBCStorage<AuctionHouseEntry> sAuctionHouseStore(AuctionHouseEntryfmt); DBCStorage<BankBagSlotPricesEntry> sBankBagSlotPricesStore(BankBagSlotPricesEntryfmt); DBCStorage<BattlemasterListEntry> sBattlemasterListStore(BattlemasterListEntryfmt); DBCStorage<BarberShopStyleEntry> sBarberShopStyleStore(BarberShopStyleEntryfmt); DBCStorage<CharStartOutfitEntry> sCharStartOutfitStore(CharStartOutfitEntryfmt); DBCStorage<CharTitlesEntry> sCharTitlesStore(CharTitlesEntryfmt); DBCStorage<ChatChannelsEntry> sChatChannelsStore(ChatChannelsEntryfmt); DBCStorage<ChrClassesEntry> sChrClassesStore(ChrClassesEntryfmt); DBCStorage<ChrRacesEntry> sChrRacesStore(ChrRacesEntryfmt); DBCStorage<CinematicSequencesEntry> sCinematicSequencesStore(CinematicSequencesEntryfmt); DBCStorage<CreatureDisplayInfoEntry> sCreatureDisplayInfoStore(CreatureDisplayInfofmt); DBCStorage<CreatureFamilyEntry> sCreatureFamilyStore(CreatureFamilyfmt); DBCStorage<CreatureSpellDataEntry> sCreatureSpellDataStore(CreatureSpellDatafmt); DBCStorage<CreatureTypeEntry> sCreatureTypeStore(CreatureTypefmt); DBCStorage<CurrencyTypesEntry> sCurrencyTypesStore(CurrencyTypesfmt); DBCStorage<DestructibleModelDataEntry> sDestructibleModelDataStore(DestructibleModelDatafmt); DBCStorage<DungeonEncounterEntry> sDungeonEncounterStore(DungeonEncounterfmt); DBCStorage<DurabilityQualityEntry> sDurabilityQualityStore(DurabilityQualityfmt); DBCStorage<DurabilityCostsEntry> sDurabilityCostsStore(DurabilityCostsfmt); DBCStorage<EmotesEntry> sEmotesStore(EmotesEntryfmt); DBCStorage<EmotesTextEntry> sEmotesTextStore(EmotesTextEntryfmt); typedef std::map<uint32, SimpleFactionsList> FactionTeamMap; static FactionTeamMap sFactionTeamMap; DBCStorage<FactionEntry> sFactionStore(FactionEntryfmt); DBCStorage<FactionTemplateEntry> sFactionTemplateStore(FactionTemplateEntryfmt); DBCStorage<GameObjectDisplayInfoEntry> sGameObjectDisplayInfoStore(GameObjectDisplayInfofmt); DBCStorage<GemPropertiesEntry> sGemPropertiesStore(GemPropertiesEntryfmt); DBCStorage<GlyphPropertiesEntry> sGlyphPropertiesStore(GlyphPropertiesfmt); DBCStorage<GlyphSlotEntry> sGlyphSlotStore(GlyphSlotfmt); DBCStorage<GtBarberShopCostBaseEntry> sGtBarberShopCostBaseStore(GtBarberShopCostBasefmt); DBCStorage<GtCombatRatingsEntry> sGtCombatRatingsStore(GtCombatRatingsfmt); DBCStorage<GtChanceToMeleeCritBaseEntry> sGtChanceToMeleeCritBaseStore(GtChanceToMeleeCritBasefmt); DBCStorage<GtChanceToMeleeCritEntry> sGtChanceToMeleeCritStore(GtChanceToMeleeCritfmt); DBCStorage<GtChanceToSpellCritBaseEntry> sGtChanceToSpellCritBaseStore(GtChanceToSpellCritBasefmt); DBCStorage<GtChanceToSpellCritEntry> sGtChanceToSpellCritStore(GtChanceToSpellCritfmt); //DBCStorage <GtOCTRegenHPEntry> sGtOCTRegenHPStore(GtOCTRegenHPfmt); //DBCStorage <GtOCTRegenMPEntry> sGtOCTRegenMPStore(GtOCTRegenMPfmt); -- not used currently //DBCStorage <GtRegenHPPerSptEntry> sGtRegenHPPerSptStore(GtRegenHPPerSptfmt); DBCStorage<GtRegenMPPerSptEntry> sGtRegenMPPerSptStore(GtRegenMPPerSptfmt); DBCStorage<gtSpellScaling> sGtSpellScalingStore(GtSpellScalingfmt); DBCStorage<HolidaysEntry> sHolidaysStore(Holidaysfmt); DBCStorage<ItemArmorQualityEntry> sItemArmorQualityStore(ItemArmorQualityfmt); DBCStorage<ItemArmorShieldEntry> sItemArmorShieldStore(ItemArmorShieldfmt); DBCStorage<ItemArmorTotalEntry> sItemArmorTotalStore(ItemArmorTotalfmt); DBCStorage<ItemBagFamilyEntry> sItemBagFamilyStore(ItemBagFamilyfmt); //DBCStorage <ItemCondExtCostsEntry> sItemCondExtCostsStore(ItemCondExtCostsEntryfmt); DBCStorage<ItemDamageEntry> sItemDamageAmmoStore(ItemDamagefmt); DBCStorage<ItemDamageEntry> sItemDamageOneHandStore(ItemDamagefmt); DBCStorage<ItemDamageEntry> sItemDamageOneHandCasterStore(ItemDamagefmt); DBCStorage<ItemDamageEntry> sItemDamageRangedStore(ItemDamagefmt); DBCStorage<ItemDamageEntry> sItemDamageThrownStore(ItemDamagefmt); DBCStorage<ItemDamageEntry> sItemDamageTwoHandStore(ItemDamagefmt); DBCStorage<ItemDamageEntry> sItemDamageTwoHandCasterStore(ItemDamagefmt); DBCStorage<ItemDamageEntry> sItemDamageWandStore(ItemDamagefmt); //DBCStorage <ItemDisplayInfoEntry> sItemDisplayInfoStore(ItemDisplayTemplateEntryfmt); -- not used currently DBCStorage<ItemExtendedCostEntry> sItemExtendedCostStore(ItemExtendedCostEntryfmt); DBCStorage<ItemLimitCategoryEntry> sItemLimitCategoryStore(ItemLimitCategoryEntryfmt); DBCStorage<ItemRandomPropertiesEntry> sItemRandomPropertiesStore(ItemRandomPropertiesfmt); DBCStorage<ItemRandomSuffixEntry> sItemRandomSuffixStore(ItemRandomSuffixfmt); DBCStorage<ItemSetEntry> sItemSetStore(ItemSetEntryfmt); DBCStorage<ItemReforgeEntry> sItemReforgeStore(ItemReforgefmt); DBCStorage<LFGDungeonEntry> sLFGDungeonStore(LFGDungeonEntryfmt); DBCStorage<LockEntry> sLockStore(LockEntryfmt); DBCStorage<MailTemplateEntry> sMailTemplateStore(MailTemplateEntryfmt); DBCStorage<MapEntry> sMapStore(MapEntryfmt); // DBC used only for initialization sMapDifficultyMap at startup. DBCStorage<MapDifficultyEntry> sMapDifficultyStore(MapDifficultyEntryfmt); // only for loading MapDifficultyMap sMapDifficultyMap; DBCStorage<MovieEntry> sMovieStore(MovieEntryfmt); DBCStorage<MountCapabilityEntry> sMountCapabilityStore(MountCapabilityfmt); DBCStorage<MountTypeEntry> sMountTypeStore(MountTypefmt); DBCStorage<OverrideSpellDataEntry> sOverrideSpellDataStore(OverrideSpellDatafmt); DBCStorage<PvPDifficultyEntry> sPvPDifficultyStore(PvPDifficultyfmt); DBCStorage<QuestSortEntry> sQuestSortStore(QuestSortEntryfmt); DBCStorage<QuestXPEntry> sQuestXPStore(QuestXPfmt); DBCStorage<QuestFactionRewEntry> sQuestFactionRewardStore(QuestFactionRewardfmt); DBCStorage<RandomPropertiesPointsEntry> sRandomPropertiesPointsStore(RandomPropertiesPointsfmt); DBCStorage<ScalingStatDistributionEntry> sScalingStatDistributionStore(ScalingStatDistributionfmt); DBCStorage<ScalingStatValuesEntry> sScalingStatValuesStore(ScalingStatValuesfmt); DBCStorage<SkillLineEntry> sSkillLineStore(SkillLinefmt); DBCStorage<SkillLineAbilityEntry> sSkillLineAbilityStore(SkillLineAbilityfmt); DBCStorage<SoundEntriesEntry> sSoundEntriesStore(SoundEntriesfmt); DBCStorage<SpellItemEnchantmentEntry> sSpellItemEnchantmentStore(SpellItemEnchantmentfmt); DBCStorage<SpellItemEnchantmentConditionEntry> sSpellItemEnchantmentConditionStore(SpellItemEnchantmentConditionfmt); DBCStorage<SpellEntry> sSpellStore(True_SpellEntryfmt); DBCStorage<SpellEntry_n> sTrueSpellStore(SpellEntryfmt); SpellCategoryStore sSpellCategoryStore; PetFamilySpellsStore sPetFamilySpellsStore; DBCStorage<SpellAuraOptionsEntry> sSpellAuraOptionsStore(SpellAuraOptionsfmt); DBCStorage<SpellAuraRestrictionsEntry> sSpellAuraRestrictionsStore(SpellAuraRestrictionsfmt); DBCStorage<SpellCastingRequirementsEntry> sSpellCastingRequirementsStore(SpellCastingRequirementsfmt); DBCStorage<SpellCategoriesEntry> sSpellCategoriesStore(SpellCategoriesfmt); DBCStorage<SpellClassOptionsEntry> sSpellClassOptionsStore(SpellClassOptionsfmt); DBCStorage<SpellCooldownsEntry> sSpellCooldownsStore(SpellCooldownsfmt); DBCStorage<SpellEffectEntry> sSpellEffectStore(SpellEffectfmt); DBCStorage<SpellEquippedItemsEntry> sSpellEquippedItemsStore(SpellEquippedItemsfmt); DBCStorage<SpellInterruptsEntry> sSpellInterruptsStore(SpellInterruptsfmt); DBCStorage<SpellLevelsEntry> sSpellLevelsStore(SpellLevelsfmt); DBCStorage<SpellPowerEntry> sSpellPowerStore(SpellPowerfmt); DBCStorage<SpellReagentsEntry> sSpellReagentsStore(SpellReagentsfmt); DBCStorage<SpellScalingEntry> sSpellScalingStore(SpellScalingfmt); DBCStorage<SpellShapeshiftEntry> sSpellShapeshiftStore(SpellShapeshiftfmt); DBCStorage<SpellTargetRestrictionsEntry> sSpellTargetRestrictionsStore(SpellTargetRestrictionsfmt); DBCStorage<SpellTotemsEntry> sSpellTotemsStore(SpellTotemsfmt); SpellEffectMap sSpellEffectMap; DBCStorage<SpellCastTimesEntry> sSpellCastTimesStore(SpellCastTimefmt); DBCStorage<SpellDifficultyEntry> sSpellDifficultyStore(SpellDifficultyfmt); DBCStorage<SpellDurationEntry> sSpellDurationStore(SpellDurationfmt); DBCStorage<SpellFocusObjectEntry> sSpellFocusObjectStore(SpellFocusObjectfmt); DBCStorage<SpellRadiusEntry> sSpellRadiusStore(SpellRadiusfmt); DBCStorage<SpellRangeEntry> sSpellRangeStore(SpellRangefmt); DBCStorage<SpellRuneCostEntry> sSpellRuneCostStore(SpellRuneCostfmt); DBCStorage<SpellShapeshiftFormEntry> sSpellShapeshiftFormStore(SpellShapeshiftFormfmt); //DBCStorage <StableSlotPricesEntry> sStableSlotPricesStore(StableSlotPricesfmt); DBCStorage<SummonPropertiesEntry> sSummonPropertiesStore(SummonPropertiesfmt); DBCStorage<GuildPerksEntry> sGuildPerksStore(GuildPerksfmt); DBCStorage<TalentEntry> sTalentStore(TalentEntryfmt); TalentSpellPosMap sTalentSpellPosMap; DBCStorage<TalentTabEntry> sTalentTabStore(TalentTabEntryfmt); DBCStorage<TalentTreePrimarySpellsEntry> sTalentTreePrimarySpellsStore(TalentTreePrimarySpellsfmt); // store absolute bit position for first rank for talent inspect static uint32 sTalentTabPages[MAX_CLASSES][3]; DBCStorage<TaxiNodesEntry> sTaxiNodesStore(TaxiNodesEntryfmt); TaxiMask sTaxiNodesMask; TaxiMask sOldContinentsNodesMask; TaxiMask sHordeTaxiNodesMask; TaxiMask sAllianceTaxiNodesMask; TaxiMask sDeathKnightTaxiNodesMask; // DBC used only for initialization sTaxiPathSetBySource at startup. TaxiPathSetBySource sTaxiPathSetBySource; DBCStorage<TaxiPathEntry> sTaxiPathStore(TaxiPathEntryfmt); // DBC used only for initialization sTaxiPathNodeStore at startup. TaxiPathNodesByPath sTaxiPathNodesByPath; static DBCStorage<TaxiPathNodeEntry> sTaxiPathNodeStore(TaxiPathNodeEntryfmt); DBCStorage<TotemCategoryEntry> sTotemCategoryStore(TotemCategoryEntryfmt); DBCStorage<VehicleEntry> sVehicleStore(VehicleEntryfmt); DBCStorage<VehicleSeatEntry> sVehicleSeatStore(VehicleSeatEntryfmt); DBCStorage<WMOAreaTableEntry> sWMOAreaTableStore(WMOAreaTableEntryfmt); DBCStorage<WorldMapAreaEntry> sWorldMapAreaStore(WorldMapAreaEntryfmt); DBCStorage<WorldMapOverlayEntry> sWorldMapOverlayStore(WorldMapOverlayEntryfmt); DBCStorage<WorldSafeLocsEntry> sWorldSafeLocsStore(WorldSafeLocsEntryfmt); typedef std::list<std::string> StoreProblemList; uint32 DBCFileCount = 0; static bool LoadDBC_assert_print (uint32 fsize, uint32 rsize, const std::string& filename) { sLog->outError("Size of '%s' setted by format string (%u) not equal size of C++ structure (%u).", filename.c_str(), fsize, rsize); // ASSERT must fail after function call return false; } template<class T> inline void LoadDBC (uint32& availableDbcLocales, StoreProblemList& errlist, DBCStorage<T>& storage, const std::string& dbc_path, const std::string& filename, const std::string * custom_entries = NULL, const std::string * idname = NULL) { // compatibility format and C++ structure sizes if (!(DBCFileLoader::GetFormatRecordSize(storage.GetFormat()) == sizeof(T) || LoadDBC_assert_print(DBCFileLoader::GetFormatRecordSize(storage.GetFormat()), sizeof(T), filename))) return; ++DBCFileCount; std::string dbc_filename = dbc_path + filename; SqlDbc * sql = NULL; if (custom_entries) sql = new SqlDbc(&filename, custom_entries, idname, storage.GetFormat()); if (storage.Load(dbc_filename.c_str(), sql)) { } else { // sort problematic dbc to (1) non compatible and (2) non-existed FILE * f = fopen(dbc_filename.c_str(), "rb"); if (f) { printf("Can't LOAD dbc %s !\n", dbc_filename.c_str()); char buf[100]; snprintf(buf, 100, " (exist, but have %d fields instead " SIZEFMTD ") Wrong client version DBC file?", storage.GetFieldCount(), strlen(storage.GetFormat())); errlist.push_back(dbc_filename + buf); fclose(f); } else { printf("Can't OPEN dbc %s !\n", dbc_filename.c_str()); errlist.push_back(dbc_filename); } } delete sql; } void LoadDBCStores (const std::string& dataPath) { uint32 oldMSTime = getMSTime(); std::string dbcPath = dataPath + "dbc/"; StoreProblemList bad_dbc_files; uint32 availableDbcLocales = 0xFFFFFFFF; LoadDBC(availableDbcLocales, bad_dbc_files, sAreaStore, dbcPath, "AreaTable.dbc"); // must be after sAreaStore loading for (uint32 i = 0; i < sAreaStore.GetNumRows(); ++i) // areaflag numbered from 0 { if (AreaTableEntry const* area = sAreaStore.LookupEntry(i)) { // fill AreaId->DBC records sAreaFlagByAreaID.insert(AreaFlagByAreaID::value_type(uint16(area->ID), area->exploreFlag)); // fill MapId->DBC records (skip sub zones and continents) if (area->zone == 0 && area->mapid != 0 && area->mapid != 1 && area->mapid != 530 && area->mapid != 571) sAreaFlagByMapID.insert(AreaFlagByMapID::value_type(area->mapid, area->exploreFlag)); } } LoadDBC(availableDbcLocales, bad_dbc_files, sAchievementStore, dbcPath, "Achievement.dbc"/*, &CustomAchievementfmt, &CustomAchievementIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sAchievementCriteriaStore, dbcPath, "Achievement_Criteria.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sAreaTriggerStore, dbcPath, "AreaTrigger.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sArmorLocationStore, dbcPath, "ArmorLocation.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sAreaGroupStore, dbcPath, "AreaGroup.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sAreaPOIStore, dbcPath, "AreaPOI.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sAuctionHouseStore, dbcPath, "AuctionHouse.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sBankBagSlotPricesStore, dbcPath, "BankBagSlotPrices.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sBattlemasterListStore, dbcPath, "BattlemasterList.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sBarberShopStyleStore, dbcPath, "BarberShopStyle.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sCharStartOutfitStore, dbcPath, "CharStartOutfit.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sCharTitlesStore, dbcPath, "CharTitles.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sChatChannelsStore, dbcPath, "ChatChannels.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sChrClassesStore, dbcPath, "ChrClasses.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sChrRacesStore, dbcPath, "ChrRaces.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sCinematicSequencesStore, dbcPath, "CinematicSequences.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureDisplayInfoStore, dbcPath, "CreatureDisplayInfo.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureFamilyStore, dbcPath, "CreatureFamily.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureSpellDataStore, dbcPath, "CreatureSpellData.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureTypeStore, dbcPath, "CreatureType.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sCurrencyTypesStore, dbcPath, "CurrencyTypes.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sDungeonEncounterStore, dbcPath, "DungeonEncounter.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sDurabilityCostsStore, dbcPath, "DurabilityCosts.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sDurabilityQualityStore, dbcPath, "DurabilityQuality.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sEmotesStore, dbcPath, "Emotes.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sEmotesTextStore, dbcPath, "EmotesText.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sFactionStore, dbcPath, "Faction.dbc"); for (uint32 i = 0; i < sFactionStore.GetNumRows(); ++i) { FactionEntry const * faction = sFactionStore.LookupEntry(i); if (faction && faction->team) { SimpleFactionsList &flist = sFactionTeamMap[faction->team]; flist.push_back(i); } } LoadDBC(availableDbcLocales, bad_dbc_files, sFactionTemplateStore, dbcPath, "FactionTemplate.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sGameObjectDisplayInfoStore, dbcPath, "GameObjectDisplayInfo.dbc"); for (uint32 i = 0; i < sGameObjectDisplayInfoStore.GetNumRows(); ++i) { if (GameObjectDisplayInfoEntry const * info = sGameObjectDisplayInfoStore.LookupEntry(i)) { if (info->maxX < info->minX) std::swap(*(float*) (&info->maxX), *(float*) (&info->minX)); if (info->maxY < info->minY) std::swap(*(float*) (&info->maxY), *(float*) (&info->minY)); if (info->maxZ < info->minZ) std::swap(*(float*) (&info->maxZ), *(float*) (&info->minZ)); } } LoadDBC(availableDbcLocales, bad_dbc_files, sGemPropertiesStore, dbcPath, "GemProperties.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sGlyphPropertiesStore, dbcPath, "GlyphProperties.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sGlyphSlotStore, dbcPath, "GlyphSlot.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sGtBarberShopCostBaseStore, dbcPath, "gtBarberShopCostBase.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sGtCombatRatingsStore, dbcPath, "gtCombatRatings.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sGtChanceToMeleeCritBaseStore, dbcPath, "gtChanceToMeleeCritBase.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sGtChanceToMeleeCritStore, dbcPath, "gtChanceToMeleeCrit.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sGtChanceToSpellCritBaseStore, dbcPath, "gtChanceToSpellCritBase.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sGtChanceToSpellCritStore, dbcPath, "gtChanceToSpellCrit.dbc"); //LoadDBC(availableDbcLocales, bad_dbc_files, sGtOCTRegenHPStore, dbcPath, "gtOCTRegenHP.dbc"); //LoadDBC(availableDbcLocales, bad_dbc_files, sGtOCTRegenMPStore, dbcPath, "gtOCTRegenMP.dbc"); -- not used currently //LoadDBC(availableDbcLocales, bad_dbc_files, sGtRegenHPPerSptStore, dbcPath, "gtRegenHPPerSpt.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sGtRegenMPPerSptStore, dbcPath, "gtRegenMPPerSpt.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sGtSpellScalingStore, dbcPath, "gtSpellScaling.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sHolidaysStore, dbcPath, "Holidays.dbc"); //LoadDBC(availableDbcLocales, bad_dbc_files, sItemStore, dbcPath, "Item.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemBagFamilyStore, dbcPath, "ItemBagFamily.dbc"); //LoadDBC(availableDbcLocales, bad_dbc_files, sItemDisplayInfoStore, dbcPath, "ItemDisplayInfo.dbc"); -- not used currently //LoadDBC(availableDbcLocales, bad_dbc_files, sItemCondExtCostsStore, dbcPath, "ItemCondExtCosts.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemExtendedCostStore, dbcPath, "ItemExtendedCost.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemLimitCategoryStore, dbcPath, "ItemLimitCategory.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemRandomPropertiesStore, dbcPath, "ItemRandomProperties.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemRandomSuffixStore, dbcPath, "ItemRandomSuffix.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemSetStore, dbcPath, "ItemSet.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemArmorQualityStore, dbcPath, "ItemArmorQuality.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemArmorShieldStore, dbcPath, "ItemArmorShield.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemArmorTotalStore, dbcPath, "ItemArmorTotal.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemDamageAmmoStore, dbcPath, "ItemDamageAmmo.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemDamageOneHandStore, dbcPath, "ItemDamageOneHand.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemDamageOneHandCasterStore, dbcPath, "ItemDamageOneHandCaster.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemDamageRangedStore, dbcPath, "ItemDamageRanged.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemDamageThrownStore, dbcPath, "ItemDamageThrown.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemDamageTwoHandStore, dbcPath, "ItemDamageTwoHand.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemDamageTwoHandCasterStore, dbcPath, "ItemDamageTwoHandCaster.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemDamageWandStore, dbcPath, "ItemDamageWand.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sItemReforgeStore, dbcPath, "ItemReforge.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sLFGDungeonStore, dbcPath, "LFGDungeons.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sLockStore, dbcPath, "Lock.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sMailTemplateStore, dbcPath, "MailTemplate.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sMapStore, dbcPath, "Map.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sMapDifficultyStore, dbcPath, "MapDifficulty.dbc"); // fill data for (uint32 i = 1; i < sMapDifficultyStore.GetNumRows(); ++i) if (MapDifficultyEntry const* entry = sMapDifficultyStore.LookupEntry(i)) sMapDifficultyMap[MAKE_PAIR32(entry->MapId, entry->Difficulty)] = MapDifficulty(entry->resetTime, entry->maxPlayers, strlen(entry->areaTriggerText) > 0); sMapDifficultyStore.Clear(); LoadDBC(availableDbcLocales, bad_dbc_files, sMovieStore, dbcPath, "Movie.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sMountCapabilityStore, dbcPath, "MountCapability.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sMountTypeStore, dbcPath, "MountType.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sOverrideSpellDataStore, dbcPath, "OverrideSpellData.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sQuestSortStore, dbcPath, "QuestSort.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sPvPDifficultyStore, dbcPath, "PvpDifficulty.dbc"); for (uint32 i = 0; i < sPvPDifficultyStore.GetNumRows(); ++i) if (PvPDifficultyEntry const* entry = sPvPDifficultyStore.LookupEntry(i)) if (entry->bracketId > MAX_BATTLEGROUND_BRACKETS) ASSERT(false && "Need update MAX_BATTLEGROUND_BRACKETS by DBC data"); LoadDBC(availableDbcLocales, bad_dbc_files, sQuestXPStore, dbcPath, "QuestXP.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sQuestFactionRewardStore, dbcPath, "QuestFactionReward.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sRandomPropertiesPointsStore, dbcPath, "RandPropPoints.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sScalingStatDistributionStore, dbcPath, "ScalingStatDistribution.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sScalingStatValuesStore, dbcPath, "ScalingStatValues.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sSkillLineStore, dbcPath, "SkillLine.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sSkillLineAbilityStore, dbcPath, "SkillLineAbility.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sSoundEntriesStore, dbcPath, "SoundEntries.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellAuraOptionsStore, dbcPath, "SpellAuraOptions.dbc"/*, &CustomSpellAuraOptionsEntryfmt, &CustomSpellAuraOptionsEntryIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellAuraRestrictionsStore, dbcPath, "SpellAuraRestrictions.dbc"/*, &CustomSpellAuraRestrictionsEntryfmt, &CustomSpellAuraRestrictionsEntryIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellCastingRequirementsStore, dbcPath, "SpellCastingRequirements.dbc"/*, &CustomSpellCastingRequirementsEntryfmt, &CustomSpellCastingRequirementsEntryIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellCategoriesStore, dbcPath, "SpellCategories.dbc"/*, &CustomSpellCategoriesEntryfmt, &CustomSpellCategoriesEntryIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellClassOptionsStore, dbcPath, "SpellClassOptions.dbc"/*, &CustomSpellClassOptionsEntryfmt, &CustomSpellClassOptionsEntryIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellCooldownsStore, dbcPath, "SpellCooldowns.dbc"/*, &CustomSpellCooldownsEntryfmt, &CustomSpellCooldownsEntryIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellEffectStore, dbcPath, "SpellEffect.dbc"/*, &CustomSpellEffectEntryfmt, &CustomSpellEffectEntryIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellEquippedItemsStore, dbcPath, "SpellEquippedItems.dbc"/*, &CustomSpellEquippedItemsEntryfmt, &CustomSpellEquippedItemsEntryIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellInterruptsStore, dbcPath, "SpellInterrupts.dbc"/*, &CustomSpellInterruptsEntryfmt, &CustomSpellInterruptsEntryIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellLevelsStore, dbcPath, "SpellLevels.dbc"/*, &CustomSpellLevelsEntryfmt, &CustomSpellLevelsEntryIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellPowerStore, dbcPath, "SpellPower.dbc"/*, &CustomSpellPowerEntryfmt, &CustomSpellPowerEntryIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellReagentsStore, dbcPath, "SpellReagents.dbc"/*, &CustomSpellReagentsEntryfmt, &CustomSpellReagentsEntryIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellScalingStore, dbcPath, "SpellScaling.dbc"/*, &CustomSpellScalingEntryfmt, &CustomSpellScalingEntryIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellShapeshiftStore, dbcPath, "SpellShapeshift.dbc"/*, &CustomSpellShapeshiftEntryfmt, &CustomSpellShapeshiftEntryIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellTargetRestrictionsStore, dbcPath, "SpellTargetRestrictions.dbc"/*, &CustomSpellTargetRestrictionsEntryfmt, &CustomSpellTargetRestrictionsEntryIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellTotemsStore, dbcPath, "SpellTotems.dbc"/*, &CustomSpellTotemsEntryfmt, &CustomSpellTotemsEntryIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sTrueSpellStore, dbcPath, "Spell.dbc"/*, &CustomSpellEntryfmt, &CustomSpellEntryIndex*/); for (uint32 i = 1; i < sSpellEffectStore.GetNumRows(); ++i) { if (SpellEffectEntry const *spellEffect = sSpellEffectStore.LookupEntry(i)) sSpellEffectMap[spellEffect->EffectSpellId].effects[spellEffect->EffectIndex] = spellEffect; } sSpellStore.Clear(); sSpellStore.nCount = sTrueSpellStore.nCount; sSpellStore.fieldCount = strlen(sSpellStore.fmt); sSpellStore.indexTable = new SpellEntry*[sSpellStore.nCount]; for (uint32 i = 0; i < sTrueSpellStore.GetNumRows(); ++i) { SpellEntry_n* spell = sTrueSpellStore.LookupEntryNoConst(i); if (spell) { SpellEntry *newspell = new SpellEntry(spell); sSpellStore.SetEntry(i, newspell); if (newspell->Category) sSpellCategoryStore[newspell->Category].insert(i); } else { sSpellStore.indexTable[i] = NULL; } } for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j) { SkillLineAbilityEntry const *skillLine = sSkillLineAbilityStore.LookupEntry(j); if (!skillLine) continue; SpellEntry const* spellInfo = sSpellStore.LookupEntry(skillLine->spellId); if (spellInfo && IsPassiveSpell(spellInfo->Id)) { for (uint32 i = 1; i < sCreatureFamilyStore.GetNumRows(); ++i) { CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(i); if (!cFamily) continue; if (skillLine->skillId != cFamily->skillLine[0] && skillLine->skillId != cFamily->skillLine[1]) continue; if (spellInfo->spellLevel) continue; if (skillLine->learnOnGetSkill != ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL) continue; sPetFamilySpellsStore[i].insert(spellInfo->Id); } } } LoadDBC(availableDbcLocales, bad_dbc_files, sSpellCastTimesStore, dbcPath, "SpellCastTimes.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellDifficultyStore, dbcPath, "SpellDifficulty.dbc"/*, &CustomSpellDifficultyfmt, &CustomSpellDifficultyIndex*/); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellDurationStore, dbcPath, "SpellDuration.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellFocusObjectStore, dbcPath, "SpellFocusObject.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellItemEnchantmentStore, dbcPath, "SpellItemEnchantment.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellItemEnchantmentConditionStore, dbcPath, "SpellItemEnchantmentCondition.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellRadiusStore, dbcPath, "SpellRadius.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellRangeStore, dbcPath, "SpellRange.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellRuneCostStore, dbcPath, "SpellRuneCost.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sSpellShapeshiftFormStore, dbcPath, "SpellShapeshiftForm.dbc"); //LoadDBC(availableDbcLocales, bad_dbc_files, sStableSlotPricesStore, dbcPath, "StableSlotPrices.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sSummonPropertiesStore, dbcPath, "SummonProperties.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sTalentStore, dbcPath, "Talent.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sGuildPerksStore, dbcPath, "GuildPerkSpells.dbc"); // Create Spelldifficulty searcher for (uint32 i = 0; i < sSpellDifficultyStore.GetNumRows(); ++i) { SpellDifficultyEntry const *spellDiff = sSpellDifficultyStore.LookupEntry(i); if (!spellDiff) continue; SpellDifficultyEntry newEntry; memset(newEntry.SpellID, 0, 4 * sizeof(uint32)); for (int x = 0; x < MAX_DIFFICULTY; ++x) { if (spellDiff->SpellID[x] <= 0 || !sSpellStore.LookupEntry(spellDiff->SpellID[x])) { if (spellDiff->SpellID[x] > 0) //don't show error if spell is <= 0, not all modes have spells and there are unknown negative values sLog->outDebug(LOG_FILTER_NETWORKIO, "spelldifficulty_dbc: spell %i at field id:%u at spellid%i does not exist in SpellStore (spell.dbc), loaded as 0", spellDiff->SpellID[x], spellDiff->ID, x); newEntry.SpellID[x] = 0; //spell was <= 0 or invalid, set to 0 } else newEntry.SpellID[x] = spellDiff->SpellID[x]; } if (newEntry.SpellID[0] <= 0 || newEntry.SpellID[1] <= 0) //id0-1 must be always set! continue; for (int x = 0; x < MAX_DIFFICULTY; ++x) sSpellMgr->SetSpellDifficultyId(uint32(newEntry.SpellID[x]), spellDiff->ID); } // create talent spells set for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i) { TalentEntry const *talentInfo = sTalentStore.LookupEntry(i); if (!talentInfo) continue; for (int j = 0; j < MAX_TALENT_RANK; j++) if (talentInfo->RankID[j]) sTalentSpellPosMap[talentInfo->RankID[j]] = TalentSpellPos(i, j); } LoadDBC(availableDbcLocales, bad_dbc_files, sTalentTabStore, dbcPath, "TalentTab.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sTalentTreePrimarySpellsStore, dbcPath, "TalentTreePrimarySpells.dbc"); // prepare fast data access to bit pos of talent ranks for use at inspecting { // now have all max ranks (and then bit amount used for store talent ranks in inspect) for (uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId) { TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentTabId); if (!talentTabInfo) continue; // prevent memory corruption; otherwise cls will become 12 below if ((talentTabInfo->ClassMask & CLASSMASK_ALL_PLAYABLE) == 0) continue; // store class talent tab pages uint32 cls = 1; for (uint32 m = 1; !(m & talentTabInfo->ClassMask) && cls < MAX_CLASSES; m <<= 1, ++cls) {} sTalentTabPages[cls][talentTabInfo->tabpage] = talentTabId; } } LoadDBC(availableDbcLocales, bad_dbc_files, sTaxiNodesStore, dbcPath, "TaxiNodes.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sTaxiPathStore, dbcPath, "TaxiPath.dbc"); for (uint32 i = 1; i < sTaxiPathStore.GetNumRows(); ++i) if (TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(i)) sTaxiPathSetBySource[entry->from][entry->to] = TaxiPathBySourceAndDestination(entry->ID, entry->price); uint32 pathCount = sTaxiPathStore.GetNumRows(); //## TaxiPathNode.dbc ## Loaded only for initialization different structures LoadDBC(availableDbcLocales, bad_dbc_files, sTaxiPathNodeStore, dbcPath, "TaxiPathNode.dbc"); // Calculate path nodes count std::vector<uint32> pathLength; pathLength.resize(pathCount); // 0 and some other indexes not used for (uint32 i = 1; i < sTaxiPathNodeStore.GetNumRows(); ++i) if (TaxiPathNodeEntry const* entry = sTaxiPathNodeStore.LookupEntry(i)) { if (pathLength[entry->path] < entry->index + 1) pathLength[entry->path] = entry->index + 1; } // Set path length sTaxiPathNodesByPath.resize(pathCount); // 0 and some other indexes not used for (uint32 i = 1; i < sTaxiPathNodesByPath.size(); ++i) sTaxiPathNodesByPath[i].resize(pathLength[i]); // fill data for (uint32 i = 1; i < sTaxiPathNodeStore.GetNumRows(); ++i) if (TaxiPathNodeEntry const* entry = sTaxiPathNodeStore.LookupEntry(i)) sTaxiPathNodesByPath[entry->path].set(entry->index, entry); // Initialize global taxinodes mask // include existed nodes that have at least single not spell base (scripted) path { std::set<uint32> spellPaths; for (uint32 i = 1; i < sSpellStore.GetNumRows(); ++i) if (SpellEntry const* sInfo = sSpellStore.LookupEntry(i)) for (int j = 0; j < MAX_SPELL_EFFECTS; ++j) if (sInfo->Effect[j] == SPELL_EFFECT_SEND_TAXI) spellPaths.insert(sInfo->EffectMiscValue[j]); ASSERT(((sTaxiNodesStore.GetNumRows()-1)/32) < TaxiMaskSize && "TaxiMaskSize needs to be increased"); memset(sTaxiNodesMask, 0, sizeof(sTaxiNodesMask)); memset(sOldContinentsNodesMask, 0, sizeof(sOldContinentsNodesMask)); memset(sHordeTaxiNodesMask, 0, sizeof(sHordeTaxiNodesMask)); memset(sAllianceTaxiNodesMask, 0, sizeof(sAllianceTaxiNodesMask)); memset(sDeathKnightTaxiNodesMask, 0, sizeof(sDeathKnightTaxiNodesMask)); for (uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i) { TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i); if (!node) continue; TaxiPathSetBySource::const_iterator src_i = sTaxiPathSetBySource.find(i); if (src_i != sTaxiPathSetBySource.end() && !src_i->second.empty()) { bool ok = false; for (TaxiPathSetForSource::const_iterator dest_i = src_i->second.begin(); dest_i != src_i->second.end(); ++dest_i) { // not spell path if (spellPaths.find(dest_i->second.ID) == spellPaths.end()) { ok = true; break; } } if (!ok) continue; } // valid taxi network node uint8 field = (uint8) ((i - 1) / 32); uint32 submask = 1 << ((i - 1) % 32); sTaxiNodesMask[field] |= submask; if (node->MountCreatureID[0] && node->MountCreatureID[0] != 32981) sHordeTaxiNodesMask[field] |= submask; if (node->MountCreatureID[1] && node->MountCreatureID[1] != 32981) sAllianceTaxiNodesMask[field] |= submask; if (node->MountCreatureID[0] == 32981 || node->MountCreatureID[1] == 32981) sDeathKnightTaxiNodesMask[field] |= submask; // old continent node (+ nodes virtually at old continents, check explicitly to avoid loading map files for zone info) if (node->map_id < 2 || i == 82 || i == 83 || i == 93 || i == 94) sOldContinentsNodesMask[field] |= submask; // fix DK node at Ebon Hold if (i == 315) { ((TaxiNodesEntry*) node)->MountCreatureID[1] = 32981; } } } LoadDBC(availableDbcLocales, bad_dbc_files, sTotemCategoryStore, dbcPath, "TotemCategory.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sVehicleStore, dbcPath, "Vehicle.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sVehicleSeatStore, dbcPath, "VehicleSeat.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sWMOAreaTableStore, dbcPath, "WMOAreaTable.dbc"); for (uint32 i = 0; i < sWMOAreaTableStore.GetNumRows(); ++i) { if (WMOAreaTableEntry const* entry = sWMOAreaTableStore.LookupEntry(i)) { sWMOAreaInfoByTripple.insert(WMOAreaInfoByTripple::value_type(WMOAreaTableTripple(entry->rootId, entry->adtId, entry->groupId), entry)); } } LoadDBC(availableDbcLocales, bad_dbc_files, sWorldMapAreaStore, dbcPath, "WorldMapArea.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sWorldMapOverlayStore, dbcPath, "WorldMapOverlay.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sWorldSafeLocsStore, dbcPath, "WorldSafeLocs.dbc"); // error checks if (bad_dbc_files.size() >= DBCFileCount) { sLog->outError("\nIncorrect DataDir value in worldserver.conf or ALL required *.dbc files (%d) not found by path: %sdbc", DBCFileCount, dataPath.c_str()); exit(1); } else if (!bad_dbc_files.empty()) { std::string str; for (std::list<std::string>::iterator i = bad_dbc_files.begin(); i != bad_dbc_files.end(); ++i) str += *i + "\n"; sLog->outError("\nSome required *.dbc files (%u from %d) not found or not compatible:\n%s", (uint32) bad_dbc_files.size(), DBCFileCount, str.c_str()); exit(1); } // Check loaded DBC files proper version if (!sAreaStore.LookupEntry(4445) || // last area (areaflag) added in 4.0.6a !sCharTitlesStore.LookupEntry(229) || // last char title added in 4.0.6a !sGemPropertiesStore.LookupEntry(1858) || // last gem property added in 4.0.6a !sItemExtendedCostStore.LookupEntry(3400) || // last item extended cost added in 4.0.6a !sMapStore.LookupEntry(767) || // last map added in 4.0.6a !sSpellStore.LookupEntry(96539)) // last added spell in 4.0.6a { sLog->outError("\nYou have _outdated_ DBC files. Please extract correct versions from current using client."); exit(1); } sLog->outString(">> Initialized %d data stores in %u ms", DBCFileCount, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); } SimpleFactionsList const* GetFactionTeamList (uint32 faction) { FactionTeamMap::const_iterator itr = sFactionTeamMap.find(faction); if (itr != sFactionTeamMap.end()) return &itr->second; return NULL; } const char* GetPetName (uint32 petfamily) { if (!petfamily) return NULL; CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(petfamily); if (!pet_family) return NULL; return pet_family->Name ? pet_family->Name : NULL; } TalentSpellPos const* GetTalentSpellPos (uint32 spellId) { TalentSpellPosMap::const_iterator itr = sTalentSpellPosMap.find(spellId); if (itr == sTalentSpellPosMap.end()) return NULL; return &itr->second; } SpellEffectEntry const* GetSpellEffectEntry (uint32 spellId, uint32 effect) { SpellEffectMap::const_iterator itr = sSpellEffectMap.find(spellId); if (itr == sSpellEffectMap.end()) return NULL; return itr->second.effects[effect]; } uint32 GetTalentSpellCost (uint32 spellId) { if (TalentSpellPos const* pos = GetTalentSpellPos(spellId)) return pos->rank + 1; return 0; } int32 GetAreaFlagByAreaID (uint32 area_id) { AreaFlagByAreaID::iterator i = sAreaFlagByAreaID.find(area_id); if (i == sAreaFlagByAreaID.end()) return -1; return i->second; } WMOAreaTableEntry const* GetWMOAreaTableEntryByTripple (int32 rootid, int32 adtid, int32 groupid) { WMOAreaInfoByTripple::iterator i = sWMOAreaInfoByTripple.find(WMOAreaTableTripple(rootid, adtid, groupid)); if (i == sWMOAreaInfoByTripple.end()) return NULL; return i->second; } AreaTableEntry const* GetAreaEntryByAreaID (uint32 area_id) { int32 areaflag = GetAreaFlagByAreaID(area_id); if (areaflag < 0) return NULL; return sAreaStore.LookupEntry(areaflag); } AreaTableEntry const* GetAreaEntryByAreaFlagAndMap (uint32 area_flag, uint32 map_id) { if (area_flag) return sAreaStore.LookupEntry(area_flag); if (MapEntry const* mapEntry = sMapStore.LookupEntry(map_id)) return GetAreaEntryByAreaID(mapEntry->linked_zone); return NULL; } uint32 GetAreaFlagByMapId (uint32 mapid) { AreaFlagByMapID::iterator i = sAreaFlagByMapID.find(mapid); if (i == sAreaFlagByMapID.end()) return 0; else return i->second; } uint32 GetVirtualMapForMapAndZone (uint32 mapid, uint32 zoneId) { if (mapid != 530 && mapid != 571) // speed for most cases return mapid; if (WorldMapAreaEntry const* wma = sWorldMapAreaStore.LookupEntry(zoneId)) return wma->virtual_map_id >= 0 ? wma->virtual_map_id : wma->map_id; return mapid; } ContentLevels GetContentLevelsForMapAndZone (uint32 mapid, uint32 zoneId) { mapid = GetVirtualMapForMapAndZone(mapid, zoneId); if (mapid < 2 || mapid == 648 || mapid == 654 || mapid == 638 || mapid == 655 || mapid == 656 || mapid == 661 || mapid == 659) return CONTENT_1_60; if (zoneId == 5034 || zoneId == 4922 || zoneId == 616 || zoneId == 5146 || zoneId == 5042) return CONTENT_81_85; MapEntry const* mapEntry = sMapStore.LookupEntry(mapid); if (!mapEntry) return CONTENT_1_60; switch (mapEntry->Expansion()) { case 1: return CONTENT_61_70; case 2: return CONTENT_71_80; case 3: return CONTENT_81_85; default: return CONTENT_1_60; } } bool IsTotemCategoryCompatiableWith (uint32 itemTotemCategoryId, uint32 requiredTotemCategoryId) { if (requiredTotemCategoryId == 0) return true; if (itemTotemCategoryId == 0) return false; TotemCategoryEntry const* itemEntry = sTotemCategoryStore.LookupEntry(itemTotemCategoryId); if (!itemEntry) return false; TotemCategoryEntry const* reqEntry = sTotemCategoryStore.LookupEntry(requiredTotemCategoryId); if (!reqEntry) return false; if (itemEntry->categoryType != reqEntry->categoryType) return false; return (itemEntry->categoryMask & reqEntry->categoryMask) == reqEntry->categoryMask; } void Zone2MapCoordinates (float& x, float& y, uint32 zone) { WorldMapAreaEntry const* maEntry = sWorldMapAreaStore.LookupEntry(zone); // if not listed then map coordinates (instance) if (!maEntry) return; std::swap(x, y); // at client map coords swapped x = x * ((maEntry->x2 - maEntry->x1) / 100) + maEntry->x1; y = y * ((maEntry->y2 - maEntry->y1) / 100) + maEntry->y1; // client y coord from top to down } void Map2ZoneCoordinates (float& x, float& y, uint32 zone) { WorldMapAreaEntry const* maEntry = sWorldMapAreaStore.LookupEntry(zone); // if not listed then map coordinates (instance) if (!maEntry) return; x = (x - maEntry->x1) / ((maEntry->x2 - maEntry->x1) / 100); y = (y - maEntry->y1) / ((maEntry->y2 - maEntry->y1) / 100); // client y coord from top to down std::swap(x, y); // client have map coords swapped } MapDifficulty const* GetMapDifficultyData (uint32 mapId, Difficulty difficulty) { MapDifficultyMap::const_iterator itr = sMapDifficultyMap.find(MAKE_PAIR32(mapId, difficulty)); return itr != sMapDifficultyMap.end() ? &itr->second : NULL; } MapDifficulty const* GetDownscaledMapDifficultyData (uint32 mapId, Difficulty &difficulty) { uint32 tmpDiff = difficulty; MapDifficulty const* mapDiff = GetMapDifficultyData(mapId, Difficulty(tmpDiff)); if (!mapDiff) { if (tmpDiff > RAID_DIFFICULTY_25MAN_NORMAL) // heroic, downscale to normal tmpDiff -= 2; else tmpDiff -= 1; // any non-normal mode for raids like tbc (only one mode) // pull new data mapDiff = GetMapDifficultyData(mapId, Difficulty(tmpDiff)); // we are 10 normal or 25 normal if (!mapDiff) { tmpDiff -= 1; mapDiff = GetMapDifficultyData(mapId, Difficulty(tmpDiff)); // 10 normal } } difficulty = Difficulty(tmpDiff); return mapDiff; } PvPDifficultyEntry const* GetBattlegroundBracketByLevel (uint32 mapid, uint32 level) { PvPDifficultyEntry const* maxEntry = NULL; // used for level > max listed level case for (uint32 i = 0; i < sPvPDifficultyStore.GetNumRows(); ++i) { if (PvPDifficultyEntry const* entry = sPvPDifficultyStore.LookupEntry(i)) { // skip unrelated and too-high brackets if (entry->mapId != mapid || entry->minLevel > level) continue; // exactly fit if (entry->maxLevel >= level) return entry; // remember for possible out-of-range case (search higher from existed) if (!maxEntry || maxEntry->maxLevel < entry->maxLevel) maxEntry = entry; } } return maxEntry; } PvPDifficultyEntry const* GetBattlegroundBracketById (uint32 mapid, BattlegroundBracketId id) { for (uint32 i = 0; i < sPvPDifficultyStore.GetNumRows(); ++i) if (PvPDifficultyEntry const* entry = sPvPDifficultyStore.LookupEntry(i)) if (entry->mapId == mapid && entry->GetBracketId() == id) return entry; return NULL; } uint32 const* GetTalentTabPages (uint8 cls) { return sTalentTabPages[cls]; } float GetGtSpellScalingValue (int8 class_, uint8 level) { if (class_ == -1) class_ = MAX_CLASSES; // General distribution if (class_ == 0) return -1.0f; // shouldn't scale //They really wants that players reach level 100... in the 5th expansion. const gtSpellScaling * spellscaling = sGtSpellScalingStore.LookupEntry((class_ - 1) * 100 + level - 1); if (spellscaling) return spellscaling->coef; else return -1.0f; } // script support functions DBCStorage<SoundEntriesEntry> const* GetSoundEntriesStore () { return &sSoundEntriesStore; } DBCStorage<SpellEntry> const* GetSpellStore () { return &sSpellStore; } DBCStorage<SpellRangeEntry> const* GetSpellRangeStore () { return &sSpellRangeStore; } DBCStorage<FactionEntry> const* GetFactionStore () { return &sFactionStore; } DBCStorage<CreatureDisplayInfoEntry> const* GetCreatureDisplayStore () { return &sCreatureDisplayInfoStore; } DBCStorage<EmotesEntry> const* GetEmotesStore () { return &sEmotesStore; } DBCStorage<EmotesTextEntry> const* GetEmotesTextStore () { return &sEmotesTextStore; } DBCStorage<AchievementEntry> const* GetAchievementStore () { return &sAchievementStore; }
49.241447
236
0.737464
Arkania
d01f65514da65687d4aabcb70c42f4a1bbab3b63
14,869
cc
C++
src/utils/cocos2d_math_util.cc
pengdu/bubblefs
9b27e191a287b3a1d012adfd3bab6a30629a5f33
[ "BSD-3-Clause" ]
1
2021-01-11T14:19:51.000Z
2021-01-11T14:19:51.000Z
src/utils/cocos2d_math_util.cc
pengdu/bubblefs
9b27e191a287b3a1d012adfd3bab6a30629a5f33
[ "BSD-3-Clause" ]
null
null
null
src/utils/cocos2d_math_util.cc
pengdu/bubblefs
9b27e191a287b3a1d012adfd3bab6a30629a5f33
[ "BSD-3-Clause" ]
null
null
null
/** Copyright 2013 BlackBerry 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. Original file from GamePlay3D: http://gameplay3d.org This file was modified to fit the cocos2d-x project */ // cocos2d-x/cocos/math/MathUtilSSE.inl // cocos2d-x/cocos/math/MathUtil.inl // cocos2d-x/cocos/math/MathUtil.cpp #include "platform/cocos2d_macros.h" #include "utils/cocos2d_math_util.h" namespace bubblefs { namespace mycocos2d { #ifdef __SSE__ void MathUtil::addMatrix(const __m128 m[4], float scalar, __m128 dst[4]) { __m128 s = _mm_set1_ps(scalar); dst[0] = _mm_add_ps(m[0], s); dst[1] = _mm_add_ps(m[1], s); dst[2] = _mm_add_ps(m[2], s); dst[3] = _mm_add_ps(m[3], s); } void MathUtil::addMatrix(const __m128 m1[4], const __m128 m2[4], __m128 dst[4]) { dst[0] = _mm_add_ps(m1[0], m2[0]); dst[1] = _mm_add_ps(m1[1], m2[1]); dst[2] = _mm_add_ps(m1[2], m2[2]); dst[3] = _mm_add_ps(m1[3], m2[3]); } void MathUtil::subtractMatrix(const __m128 m1[4], const __m128 m2[4], __m128 dst[4]) { dst[0] = _mm_sub_ps(m1[0], m2[0]); dst[1] = _mm_sub_ps(m1[1], m2[1]); dst[2] = _mm_sub_ps(m1[2], m2[2]); dst[3] = _mm_sub_ps(m1[3], m2[3]); } void MathUtil::multiplyMatrix(const __m128 m[4], float scalar, __m128 dst[4]) { __m128 s = _mm_set1_ps(scalar); dst[0] = _mm_mul_ps(m[0], s); dst[1] = _mm_mul_ps(m[1], s); dst[2] = _mm_mul_ps(m[2], s); dst[3] = _mm_mul_ps(m[3], s); } void MathUtil::multiplyMatrix(const __m128 m1[4], const __m128 m2[4], __m128 dst[4]) { __m128 dst0, dst1, dst2, dst3; { __m128 e0 = _mm_shuffle_ps(m2[0], m2[0], _MM_SHUFFLE(0, 0, 0, 0)); __m128 e1 = _mm_shuffle_ps(m2[0], m2[0], _MM_SHUFFLE(1, 1, 1, 1)); __m128 e2 = _mm_shuffle_ps(m2[0], m2[0], _MM_SHUFFLE(2, 2, 2, 2)); __m128 e3 = _mm_shuffle_ps(m2[0], m2[0], _MM_SHUFFLE(3, 3, 3, 3)); __m128 v0 = _mm_mul_ps(m1[0], e0); __m128 v1 = _mm_mul_ps(m1[1], e1); __m128 v2 = _mm_mul_ps(m1[2], e2); __m128 v3 = _mm_mul_ps(m1[3], e3); __m128 a0 = _mm_add_ps(v0, v1); __m128 a1 = _mm_add_ps(v2, v3); __m128 a2 = _mm_add_ps(a0, a1); dst0 = a2; } { __m128 e0 = _mm_shuffle_ps(m2[1], m2[1], _MM_SHUFFLE(0, 0, 0, 0)); __m128 e1 = _mm_shuffle_ps(m2[1], m2[1], _MM_SHUFFLE(1, 1, 1, 1)); __m128 e2 = _mm_shuffle_ps(m2[1], m2[1], _MM_SHUFFLE(2, 2, 2, 2)); __m128 e3 = _mm_shuffle_ps(m2[1], m2[1], _MM_SHUFFLE(3, 3, 3, 3)); __m128 v0 = _mm_mul_ps(m1[0], e0); __m128 v1 = _mm_mul_ps(m1[1], e1); __m128 v2 = _mm_mul_ps(m1[2], e2); __m128 v3 = _mm_mul_ps(m1[3], e3); __m128 a0 = _mm_add_ps(v0, v1); __m128 a1 = _mm_add_ps(v2, v3); __m128 a2 = _mm_add_ps(a0, a1); dst1 = a2; } { __m128 e0 = _mm_shuffle_ps(m2[2], m2[2], _MM_SHUFFLE(0, 0, 0, 0)); __m128 e1 = _mm_shuffle_ps(m2[2], m2[2], _MM_SHUFFLE(1, 1, 1, 1)); __m128 e2 = _mm_shuffle_ps(m2[2], m2[2], _MM_SHUFFLE(2, 2, 2, 2)); __m128 e3 = _mm_shuffle_ps(m2[2], m2[2], _MM_SHUFFLE(3, 3, 3, 3)); __m128 v0 = _mm_mul_ps(m1[0], e0); __m128 v1 = _mm_mul_ps(m1[1], e1); __m128 v2 = _mm_mul_ps(m1[2], e2); __m128 v3 = _mm_mul_ps(m1[3], e3); __m128 a0 = _mm_add_ps(v0, v1); __m128 a1 = _mm_add_ps(v2, v3); __m128 a2 = _mm_add_ps(a0, a1); dst2 = a2; } { __m128 e0 = _mm_shuffle_ps(m2[3], m2[3], _MM_SHUFFLE(0, 0, 0, 0)); __m128 e1 = _mm_shuffle_ps(m2[3], m2[3], _MM_SHUFFLE(1, 1, 1, 1)); __m128 e2 = _mm_shuffle_ps(m2[3], m2[3], _MM_SHUFFLE(2, 2, 2, 2)); __m128 e3 = _mm_shuffle_ps(m2[3], m2[3], _MM_SHUFFLE(3, 3, 3, 3)); __m128 v0 = _mm_mul_ps(m1[0], e0); __m128 v1 = _mm_mul_ps(m1[1], e1); __m128 v2 = _mm_mul_ps(m1[2], e2); __m128 v3 = _mm_mul_ps(m1[3], e3); __m128 a0 = _mm_add_ps(v0, v1); __m128 a1 = _mm_add_ps(v2, v3); __m128 a2 = _mm_add_ps(a0, a1); dst3 = a2; } dst[0] = dst0; dst[1] = dst1; dst[2] = dst2; dst[3] = dst3; } void MathUtil::negateMatrix(const __m128 m[4], __m128 dst[4]) { __m128 z = _mm_setzero_ps(); dst[0] = _mm_sub_ps(z, m[0]); dst[1] = _mm_sub_ps(z, m[1]); dst[2] = _mm_sub_ps(z, m[2]); dst[3] = _mm_sub_ps(z, m[3]); } void MathUtil::transposeMatrix(const __m128 m[4], __m128 dst[4]) { __m128 tmp0 = _mm_shuffle_ps(m[0], m[1], 0x44); __m128 tmp2 = _mm_shuffle_ps(m[0], m[1], 0xEE); __m128 tmp1 = _mm_shuffle_ps(m[2], m[3], 0x44); __m128 tmp3 = _mm_shuffle_ps(m[2], m[3], 0xEE); dst[0] = _mm_shuffle_ps(tmp0, tmp1, 0x88); dst[1] = _mm_shuffle_ps(tmp0, tmp1, 0xDD); dst[2] = _mm_shuffle_ps(tmp2, tmp3, 0x88); dst[3] = _mm_shuffle_ps(tmp2, tmp3, 0xDD); } void MathUtil::transformVec4(const __m128 m[4], const __m128& v, __m128& dst) { __m128 col1 = _mm_shuffle_ps(v, v, _MM_SHUFFLE(0, 0, 0, 0)); __m128 col2 = _mm_shuffle_ps(v, v, _MM_SHUFFLE(1, 1, 1, 1)); __m128 col3 = _mm_shuffle_ps(v, v, _MM_SHUFFLE(2, 2, 2, 2)); __m128 col4 = _mm_shuffle_ps(v, v, _MM_SHUFFLE(3, 3, 3, 3)); dst = _mm_add_ps( _mm_add_ps(_mm_mul_ps(m[0], col1), _mm_mul_ps(m[1], col2)), _mm_add_ps(_mm_mul_ps(m[2], col3), _mm_mul_ps(m[3], col4)) ); } #endif // __SSE__ class MathUtilC { public: inline static void addMatrix(const float* m, float scalar, float* dst); inline static void addMatrix(const float* m1, const float* m2, float* dst); inline static void subtractMatrix(const float* m1, const float* m2, float* dst); inline static void multiplyMatrix(const float* m, float scalar, float* dst); inline static void multiplyMatrix(const float* m1, const float* m2, float* dst); inline static void negateMatrix(const float* m, float* dst); inline static void transposeMatrix(const float* m, float* dst); inline static void transformVec4(const float* m, float x, float y, float z, float w, float* dst); inline static void transformVec4(const float* m, const float* v, float* dst); inline static void crossVec3(const float* v1, const float* v2, float* dst); }; inline void MathUtilC::addMatrix(const float* m, float scalar, float* dst) { dst[0] = m[0] + scalar; dst[1] = m[1] + scalar; dst[2] = m[2] + scalar; dst[3] = m[3] + scalar; dst[4] = m[4] + scalar; dst[5] = m[5] + scalar; dst[6] = m[6] + scalar; dst[7] = m[7] + scalar; dst[8] = m[8] + scalar; dst[9] = m[9] + scalar; dst[10] = m[10] + scalar; dst[11] = m[11] + scalar; dst[12] = m[12] + scalar; dst[13] = m[13] + scalar; dst[14] = m[14] + scalar; dst[15] = m[15] + scalar; } inline void MathUtilC::addMatrix(const float* m1, const float* m2, float* dst) { dst[0] = m1[0] + m2[0]; dst[1] = m1[1] + m2[1]; dst[2] = m1[2] + m2[2]; dst[3] = m1[3] + m2[3]; dst[4] = m1[4] + m2[4]; dst[5] = m1[5] + m2[5]; dst[6] = m1[6] + m2[6]; dst[7] = m1[7] + m2[7]; dst[8] = m1[8] + m2[8]; dst[9] = m1[9] + m2[9]; dst[10] = m1[10] + m2[10]; dst[11] = m1[11] + m2[11]; dst[12] = m1[12] + m2[12]; dst[13] = m1[13] + m2[13]; dst[14] = m1[14] + m2[14]; dst[15] = m1[15] + m2[15]; } inline void MathUtilC::subtractMatrix(const float* m1, const float* m2, float* dst) { dst[0] = m1[0] - m2[0]; dst[1] = m1[1] - m2[1]; dst[2] = m1[2] - m2[2]; dst[3] = m1[3] - m2[3]; dst[4] = m1[4] - m2[4]; dst[5] = m1[5] - m2[5]; dst[6] = m1[6] - m2[6]; dst[7] = m1[7] - m2[7]; dst[8] = m1[8] - m2[8]; dst[9] = m1[9] - m2[9]; dst[10] = m1[10] - m2[10]; dst[11] = m1[11] - m2[11]; dst[12] = m1[12] - m2[12]; dst[13] = m1[13] - m2[13]; dst[14] = m1[14] - m2[14]; dst[15] = m1[15] - m2[15]; } inline void MathUtilC::multiplyMatrix(const float* m, float scalar, float* dst) { dst[0] = m[0] * scalar; dst[1] = m[1] * scalar; dst[2] = m[2] * scalar; dst[3] = m[3] * scalar; dst[4] = m[4] * scalar; dst[5] = m[5] * scalar; dst[6] = m[6] * scalar; dst[7] = m[7] * scalar; dst[8] = m[8] * scalar; dst[9] = m[9] * scalar; dst[10] = m[10] * scalar; dst[11] = m[11] * scalar; dst[12] = m[12] * scalar; dst[13] = m[13] * scalar; dst[14] = m[14] * scalar; dst[15] = m[15] * scalar; } inline void MathUtilC::multiplyMatrix(const float* m1, const float* m2, float* dst) { // Support the case where m1 or m2 is the same array as dst. float product[16]; product[0] = m1[0] * m2[0] + m1[4] * m2[1] + m1[8] * m2[2] + m1[12] * m2[3]; product[1] = m1[1] * m2[0] + m1[5] * m2[1] + m1[9] * m2[2] + m1[13] * m2[3]; product[2] = m1[2] * m2[0] + m1[6] * m2[1] + m1[10] * m2[2] + m1[14] * m2[3]; product[3] = m1[3] * m2[0] + m1[7] * m2[1] + m1[11] * m2[2] + m1[15] * m2[3]; product[4] = m1[0] * m2[4] + m1[4] * m2[5] + m1[8] * m2[6] + m1[12] * m2[7]; product[5] = m1[1] * m2[4] + m1[5] * m2[5] + m1[9] * m2[6] + m1[13] * m2[7]; product[6] = m1[2] * m2[4] + m1[6] * m2[5] + m1[10] * m2[6] + m1[14] * m2[7]; product[7] = m1[3] * m2[4] + m1[7] * m2[5] + m1[11] * m2[6] + m1[15] * m2[7]; product[8] = m1[0] * m2[8] + m1[4] * m2[9] + m1[8] * m2[10] + m1[12] * m2[11]; product[9] = m1[1] * m2[8] + m1[5] * m2[9] + m1[9] * m2[10] + m1[13] * m2[11]; product[10] = m1[2] * m2[8] + m1[6] * m2[9] + m1[10] * m2[10] + m1[14] * m2[11]; product[11] = m1[3] * m2[8] + m1[7] * m2[9] + m1[11] * m2[10] + m1[15] * m2[11]; product[12] = m1[0] * m2[12] + m1[4] * m2[13] + m1[8] * m2[14] + m1[12] * m2[15]; product[13] = m1[1] * m2[12] + m1[5] * m2[13] + m1[9] * m2[14] + m1[13] * m2[15]; product[14] = m1[2] * m2[12] + m1[6] * m2[13] + m1[10] * m2[14] + m1[14] * m2[15]; product[15] = m1[3] * m2[12] + m1[7] * m2[13] + m1[11] * m2[14] + m1[15] * m2[15]; memcpy(dst, product, MATRIX_SIZE); } inline void MathUtilC::negateMatrix(const float* m, float* dst) { dst[0] = -m[0]; dst[1] = -m[1]; dst[2] = -m[2]; dst[3] = -m[3]; dst[4] = -m[4]; dst[5] = -m[5]; dst[6] = -m[6]; dst[7] = -m[7]; dst[8] = -m[8]; dst[9] = -m[9]; dst[10] = -m[10]; dst[11] = -m[11]; dst[12] = -m[12]; dst[13] = -m[13]; dst[14] = -m[14]; dst[15] = -m[15]; } inline void MathUtilC::transposeMatrix(const float* m, float* dst) { float t[16] = { m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6], m[10], m[14], m[3], m[7], m[11], m[15] }; memcpy(dst, t, MATRIX_SIZE); } inline void MathUtilC::transformVec4(const float* m, float x, float y, float z, float w, float* dst) { dst[0] = x * m[0] + y * m[4] + z * m[8] + w * m[12]; dst[1] = x * m[1] + y * m[5] + z * m[9] + w * m[13]; dst[2] = x * m[2] + y * m[6] + z * m[10] + w * m[14]; } inline void MathUtilC::transformVec4(const float* m, const float* v, float* dst) { // Handle case where v == dst. float x = v[0] * m[0] + v[1] * m[4] + v[2] * m[8] + v[3] * m[12]; float y = v[0] * m[1] + v[1] * m[5] + v[2] * m[9] + v[3] * m[13]; float z = v[0] * m[2] + v[1] * m[6] + v[2] * m[10] + v[3] * m[14]; float w = v[0] * m[3] + v[1] * m[7] + v[2] * m[11] + v[3] * m[15]; dst[0] = x; dst[1] = y; dst[2] = z; dst[3] = w; } inline void MathUtilC::crossVec3(const float* v1, const float* v2, float* dst) { float x = (v1[1] * v2[2]) - (v1[2] * v2[1]); float y = (v1[2] * v2[0]) - (v1[0] * v2[2]); float z = (v1[0] * v2[1]) - (v1[1] * v2[0]); dst[0] = x; dst[1] = y; dst[2] = z; } void MathUtil::smooth(float* x, float target, float elapsedTime, float responseTime) { ASSERT(x); if (elapsedTime > 0) { *x += (target - *x) * elapsedTime / (elapsedTime + responseTime); } } void MathUtil::smooth(float* x, float target, float elapsedTime, float riseTime, float fallTime) { ASSERT(x); if (elapsedTime > 0) { float delta = target - *x; *x += delta * elapsedTime / (elapsedTime + (delta > 0 ? riseTime : fallTime)); } } float MathUtil::lerp(float from, float to, float alpha) { return from * (1.0f - alpha) + to * alpha; } bool MathUtil::isNeon32Enabled() { return false; } bool MathUtil::isNeon64Enabled() { return false; } void MathUtil::addMatrix(const float* m, float scalar, float* dst) { MathUtilC::addMatrix(m, scalar, dst); } void MathUtil::addMatrix(const float* m1, const float* m2, float* dst) { MathUtilC::addMatrix(m1, m2, dst); } void MathUtil::subtractMatrix(const float* m1, const float* m2, float* dst) { MathUtilC::subtractMatrix(m1, m2, dst); } void MathUtil::multiplyMatrix(const float* m, float scalar, float* dst) { MathUtilC::multiplyMatrix(m, scalar, dst); } void MathUtil::multiplyMatrix(const float* m1, const float* m2, float* dst) { MathUtilC::multiplyMatrix(m1, m2, dst); } void MathUtil::negateMatrix(const float* m, float* dst) { MathUtilC::negateMatrix(m, dst); } void MathUtil::transposeMatrix(const float* m, float* dst) { MathUtilC::transposeMatrix(m, dst); } void MathUtil::transformVec4(const float* m, float x, float y, float z, float w, float* dst) { MathUtilC::transformVec4(m, x, y, z, w, dst); } void MathUtil::transformVec4(const float* m, const float* v, float* dst) { MathUtilC::transformVec4(m, v, dst); } void MathUtil::crossVec3(const float* v1, const float* v2, float* dst) { MathUtilC::crossVec3(v1, v2, dst); } } // namespace mycocos2d } // namespace bubblefs
32.183983
101
0.530231
pengdu
d020d26d520901947aa4ab199623061fe35f83c3
449
cpp
C++
01-what-is-cpp/8-doctest/FactorialTest2.cpp
erelsgl-at-ariel/cpp-5780
181ae712a05031f85fe3f9f7b16c5e60350e1577
[ "MIT" ]
6
2020-03-19T13:49:17.000Z
2020-05-27T16:04:37.000Z
01-what-is-cpp/8-doctest/FactorialTest2.cpp
erelsgl-at-ariel/cpp-5780
181ae712a05031f85fe3f9f7b16c5e60350e1577
[ "MIT" ]
null
null
null
01-what-is-cpp/8-doctest/FactorialTest2.cpp
erelsgl-at-ariel/cpp-5780
181ae712a05031f85fe3f9f7b16c5e60350e1577
[ "MIT" ]
23
2020-03-12T13:21:29.000Z
2021-02-22T21:29:48.000Z
#include "doctest.h" #include "Factorial.hpp" #include <stdexcept> TEST_CASE("Factorials of negative numbers") { CHECK_THROWS(factorial(-1)); // check that some exception is thrown CHECK_THROWS_AS(factorial(-2), std::out_of_range); // check that a specific exception type is thrown CHECK_THROWS_AS(factorial(-2), std::exception); // check that a specific exception type (or a descendant) is thrown } /* add more test cases here */
37.416667
120
0.726058
erelsgl-at-ariel
d0214b7b943c4538bc3e1b117a67dd191104c3c6
7,468
cpp
C++
src/execution/operator/scan/physical_lookup.cpp
graindb/graindb-demonstration
be901b3e66fc991ea3ecfbcfabdcd07af82dd2d7
[ "MIT" ]
1
2021-08-30T16:08:17.000Z
2021-08-30T16:08:17.000Z
src/execution/operator/scan/physical_lookup.cpp
graindb/graindb-demonstration
be901b3e66fc991ea3ecfbcfabdcd07af82dd2d7
[ "MIT" ]
1
2021-12-12T03:36:02.000Z
2021-12-12T03:36:02.000Z
src/execution/operator/scan/physical_lookup.cpp
graindb/graindb-demonstration
be901b3e66fc991ea3ecfbcfabdcd07af82dd2d7
[ "MIT" ]
null
null
null
#include "duckdb/execution/operator/scan/physical_lookup.hpp" #include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/database.hpp" #include "duckdb/storage/buffer_manager.hpp" #include "duckdb/storage/numeric_segment.hpp" #include "duckdb/storage/storage_manager.hpp" #include "duckdb/storage/table/transient_segment.hpp" #include "duckdb/storage/uncompressed_segment.hpp" #include "duckdb/transaction/transaction.hpp" #include <iostream> using namespace duckdb; using namespace std; PhysicalLookup::PhysicalLookup(LogicalOperator &op, TableCatalogEntry &tableref, idx_t table_index, DataTable &table, vector<column_t> &column_ids, vector<unique_ptr<Expression>> filter, unordered_map<idx_t, vector<TableFilter>> table_filters) : PhysicalOperator(PhysicalOperatorType::LOOKUP, op.types), tableref(tableref), table_index(table_index), table(table), column_ids(column_ids), table_filters(move(table_filters)) { if (filter.size() > 1) { //! create a big AND out of the expressions auto conjunction = make_unique<BoundConjunctionExpression>(ExpressionType::CONJUNCTION_AND); for (auto &expr : filter) { conjunction->children.push_back(move(expr)); } expression = move(conjunction); } else if (filter.size() == 1) { expression = move(filter[0]); } for (column_t i = 0; i < column_ids.size(); i++) { unordered_map<idx_t, data_ptr_t> s_ptrs; segment_ptrs_map.push_back(s_ptrs); } } template <class T> void inline PhysicalLookup::Lookup(ClientContext &context, ColumnData &column, const row_t *row_ids, Vector &result, idx_t count, unordered_map<idx_t, data_ptr_t> &segment_ptrs, idx_t type_size) { auto result_data = FlatVector::GetData(result); idx_t s_size = column.data.nodes[0].node->count; for (idx_t i = 0; i < count; i++) { row_t row_id = row_ids[i]; idx_t s_index = row_id / s_size; idx_t s_offset = row_id % s_size; idx_t vector_index = s_offset / STANDARD_VECTOR_SIZE; idx_t id_in_vector = s_offset - vector_index * STANDARD_VECTOR_SIZE; if (segment_ptrs.find(s_index) == segment_ptrs.end()) { // get segment buffer auto transient_segment = (TransientSegment *)column.data.nodes[s_index].node; auto numeric_segment = (NumericSegment *)transient_segment->data.get(); assert(vector_index < numeric_segment->max_vector_count); auto block_entry = transient_segment->manager.blocks.find(numeric_segment->block_id); if (block_entry == transient_segment->manager.blocks.end()) { continue; } segment_ptrs[s_index] = block_entry->second->buffer->buffer; } auto s_data = segment_ptrs[s_index] + (vector_index * (sizeof(nullmask_t) + type_size * STANDARD_VECTOR_SIZE) + sizeof(nullmask_t)); memcpy(result_data + (i * type_size), s_data + (id_in_vector * type_size), type_size); } } void PhysicalLookup::GetChunkInternal(ClientContext &context, DataChunk &chunk, PhysicalOperatorState *state_, SelectionVector *sel, Vector *rid_vector, DataChunk *rai_chunk) { auto state = reinterpret_cast<PhysicalLookupOperatorState *>(state_); auto &transaction = context.ActiveTransaction(); auto reference_column_idx = rai_chunk->column_count() - 1; auto fetch_count = rai_chunk->size(); if (fetch_count == 0) { return; } // perform lookups auto row_ids = FlatVector::GetData<row_t>(*rid_vector); vector<column_t> rai_columns; chunk.SetCardinality(fetch_count); for (idx_t col_idx = 0; col_idx < column_ids.size(); col_idx++) { auto col = column_ids[col_idx]; if (col == COLUMN_IDENTIFIER_ROW_ID || col == table.types.size()) { chunk.data[col_idx].Reference(*rid_vector); } else if (col == table.types.size() + 2) { chunk.data[col_idx].Reference(rai_chunk->data[reference_column_idx]); } else { auto column = table.GetColumn(col); switch (column->type) { case TypeId::INT8: { Lookup<int8_t>(context, *column, row_ids, chunk.data[col_idx], fetch_count, segment_ptrs_map[col_idx]); break; } case TypeId::UINT8: { Lookup<uint8_t>(context, *column, row_ids, chunk.data[col_idx], fetch_count, segment_ptrs_map[col_idx]); break; } case TypeId::INT16: { Lookup<int16_t>(context, *column, row_ids, chunk.data[col_idx], fetch_count, segment_ptrs_map[col_idx]); break; } case TypeId::HASH: case TypeId::UINT16: { Lookup<uint16_t>(context, *column, row_ids, chunk.data[col_idx], fetch_count, segment_ptrs_map[col_idx]); break; } case TypeId::INT32: { Lookup<int32_t>(context, *column, row_ids, chunk.data[col_idx], fetch_count, segment_ptrs_map[col_idx]); break; } case TypeId::UINT32: { Lookup<uint32_t>(context, *column, row_ids, chunk.data[col_idx], fetch_count, segment_ptrs_map[col_idx]); break; } case TypeId::TIMESTAMP: case TypeId::INT64: { Lookup<int64_t>(context, *column, row_ids, chunk.data[col_idx], fetch_count, segment_ptrs_map[col_idx]); break; } case TypeId::UINT64: { Lookup<uint64_t>(context, *column, row_ids, chunk.data[col_idx], fetch_count, segment_ptrs_map[col_idx]); break; } case TypeId::FLOAT: { Lookup<float_t>(context, *column, row_ids, chunk.data[col_idx], fetch_count, segment_ptrs_map[col_idx]); break; } case TypeId::DOUBLE: { Lookup<double_t>(context, *column, row_ids, chunk.data[col_idx], fetch_count, segment_ptrs_map[col_idx]); break; } case TypeId::POINTER: { Lookup<uintptr_t>(context, *column, row_ids, chunk.data[col_idx], fetch_count, segment_ptrs_map[col_idx]); break; } default: { table.Fetch(transaction, chunk, column_ids, *rid_vector, fetch_count, state->index_state); } } } } // filter SelectionVector filter_sel(fetch_count); auto result_count = fetch_count; if (!table_filters.empty()) { result_count = state->executor.SelectExpression(chunk, filter_sel); } // reference // auto rai_column_idx = column_ids.size(); // for (auto &col : rai_columns) { // if (col == table.types.size()) { // chunk.data[rai_column_idx++].Reference(*rid_vector); // } // if (col == table.types.size() + 2) { // chunk.data[rai_column_idx++].Reference(rai_chunk->data[reference_column_idx]); // } // } if (result_count == fetch_count) { // nothing was filtered: skip adding any selection vectors return; } // slice chunk.Slice(filter_sel, result_count); // rai_chunk->Slice(filter_sel, result_count); auto sel_data = sel->Slice(filter_sel, result_count); sel->Initialize(move(sel_data)); } string PhysicalLookup::ExtraRenderInformation() const { string result; if (expression) { result += tableref.name + " " + expression->ToString(); } else { result += tableref.name; } result += "(" + to_string(table_index) + ")"; result += "["; for (auto &id : column_ids) { if (id == COLUMN_IDENTIFIER_ROW_ID) { result += "rowid,"; } else { result += tableref.columns[id].name + ","; } } result = result.substr(0, result.size() - 1); result += "]"; return result; } unique_ptr<PhysicalOperatorState> PhysicalLookup::GetOperatorState() { if (!table_filters.empty()) { return make_unique<PhysicalLookupOperatorState>(*expression); } return make_unique<PhysicalLookupOperatorState>(); }
37.154229
117
0.693224
graindb
d02376b328cf4f2fc99cccb96fad786b8643bb01
7,044
cpp
C++
src/rfx/graphics/ShaderCompiler.cpp
rfruesmer/rfx
96c15a11ee8e2192c9d2ff233924eee884835f17
[ "MIT" ]
null
null
null
src/rfx/graphics/ShaderCompiler.cpp
rfruesmer/rfx
96c15a11ee8e2192c9d2ff233924eee884835f17
[ "MIT" ]
null
null
null
src/rfx/graphics/ShaderCompiler.cpp
rfruesmer/rfx
96c15a11ee8e2192c9d2ff233924eee884835f17
[ "MIT" ]
null
null
null
#include "rfx/pch.h" #include "rfx/graphics/ShaderCompiler.h" #include "rfx/common/StringUtil.h" using namespace rfx; using namespace glslang; using namespace std; namespace rfx { // --------------------------------------------------------------------------------------------------------------------- EShLanguage findLanguage(VkShaderStageFlagBits shaderType); void initResources(TBuiltInResource& Resources); // --------------------------------------------------------------------------------------------------------------------- void GLSLtoSPV( const VkShaderStageFlagBits shaderType, const char* shaderString, vector<uint32_t>& spirv) { EShLanguage language = findLanguage(shaderType); TShader shader(language); TBuiltInResource resources = {}; initResources(resources); const char* shaderStrings[1]; shaderStrings[0] = shaderString; shader.setStrings(shaderStrings, 1); #ifdef _DEBUG auto messages = static_cast<EShMessages>(EShMsgDefault | EShMsgDebugInfo | EShMsgSpvRules | EShMsgVulkanRules); #else auto messages = static_cast<EShMessages>(EShMsgSpvRules | EShMsgVulkanRules); #endif if (!shader.parse(&resources, 450, false, messages)) { RFX_THROW(StringUtil::trimRight(string(shader.getInfoLog())) + "\nInfo Log: " + string(shader.getInfoDebugLog())); } TProgram program; program.addShader(&shader); if (!program.link(messages)) { RFX_THROW(StringUtil::trimRight(string(shader.getInfoLog())) + "\nInfo Log: " + string(shader.getInfoDebugLog())); } TIntermediate* pIntermediate = program.getIntermediate(language); GlslangToSpv(*pIntermediate, spirv); } // --------------------------------------------------------------------------------------------------------------------- EShLanguage findLanguage(const VkShaderStageFlagBits shaderType) { static const unordered_map<VkShaderStageFlagBits, EShLanguage> languageMap = { { VK_SHADER_STAGE_VERTEX_BIT, EShLangVertex }, { VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, EShLangTessControl }, { VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, EShLangTessEvaluation }, { VK_SHADER_STAGE_GEOMETRY_BIT, EShLangGeometry }, { VK_SHADER_STAGE_FRAGMENT_BIT, EShLangFragment }, { VK_SHADER_STAGE_COMPUTE_BIT, EShLangCompute } }; auto it = languageMap.find(shaderType); RFX_CHECK_ARGUMENT(it != languageMap.end()); return it != languageMap.end() ? it->second : EShLangVertex; } // --------------------------------------------------------------------------------------------------------------------- void initResources(TBuiltInResource& resources) { resources = { .maxLights = 32, .maxClipPlanes = 6, .maxTextureUnits = 32, .maxTextureCoords = 32, .maxVertexAttribs = 64, .maxVertexUniformComponents = 4096, .maxVaryingFloats = 64, .maxVertexTextureImageUnits = 32, .maxCombinedTextureImageUnits = 80, .maxTextureImageUnits = 32, .maxFragmentUniformComponents = 4096, .maxDrawBuffers = 32, .maxVertexUniformVectors = 128, .maxVaryingVectors = 8, .maxFragmentUniformVectors = 16, .maxVertexOutputVectors = 16, .maxFragmentInputVectors = 15, .minProgramTexelOffset = -8, .maxProgramTexelOffset = 7, .maxClipDistances = 8, .maxComputeWorkGroupCountX = 65535, .maxComputeWorkGroupCountY = 65535, .maxComputeWorkGroupCountZ = 65535, .maxComputeWorkGroupSizeX = 1024, .maxComputeWorkGroupSizeY = 1024, .maxComputeWorkGroupSizeZ = 64, .maxComputeUniformComponents = 1024, .maxComputeTextureImageUnits = 16, .maxComputeImageUniforms = 8, .maxComputeAtomicCounters = 8, .maxComputeAtomicCounterBuffers = 1, .maxVaryingComponents = 60, .maxVertexOutputComponents = 64, .maxGeometryInputComponents = 64, .maxGeometryOutputComponents = 128, .maxFragmentInputComponents = 128, .maxImageUnits = 8, .maxCombinedImageUnitsAndFragmentOutputs = 8, .maxCombinedShaderOutputResources = 8, .maxImageSamples = 0, .maxVertexImageUniforms = 0, .maxTessControlImageUniforms = 0, .maxTessEvaluationImageUniforms = 0, .maxGeometryImageUniforms = 0, .maxFragmentImageUniforms = 8, .maxCombinedImageUniforms = 8, .maxGeometryTextureImageUnits = 16, .maxGeometryOutputVertices = 256, .maxGeometryTotalOutputComponents = 1024, .maxGeometryUniformComponents = 1024, .maxGeometryVaryingComponents = 64, .maxTessControlInputComponents = 128, .maxTessControlOutputComponents = 128, .maxTessControlTextureImageUnits = 16, .maxTessControlUniformComponents = 1024, .maxTessControlTotalOutputComponents = 4096, .maxTessEvaluationInputComponents = 128, .maxTessEvaluationOutputComponents = 128, .maxTessEvaluationTextureImageUnits = 16, .maxTessEvaluationUniformComponents = 1024, .maxTessPatchComponents = 120, .maxPatchVertices = 32, .maxTessGenLevel = 64, .maxViewports = 16, .maxVertexAtomicCounters = 0, .maxTessControlAtomicCounters = 0, .maxTessEvaluationAtomicCounters = 0, .maxGeometryAtomicCounters = 0, .maxFragmentAtomicCounters = 8, .maxCombinedAtomicCounters = 8, .maxAtomicCounterBindings = 1, .maxVertexAtomicCounterBuffers = 0, .maxTessControlAtomicCounterBuffers = 0, .maxTessEvaluationAtomicCounterBuffers = 0, .maxGeometryAtomicCounterBuffers = 0, .maxFragmentAtomicCounterBuffers = 1, .maxCombinedAtomicCounterBuffers = 1, .maxAtomicCounterBufferSize = 16384, .maxTransformFeedbackBuffers = 4, .maxTransformFeedbackInterleavedComponents = 64, .maxCullDistances = 8, .maxCombinedClipAndCullDistances = 8, .maxSamples = 4, .maxMeshOutputVerticesNV = 256, .maxMeshOutputPrimitivesNV = 512, .maxMeshWorkGroupSizeX_NV = 32, .maxMeshWorkGroupSizeY_NV = 1, .maxMeshWorkGroupSizeZ_NV = 1, .maxTaskWorkGroupSizeX_NV = 32, .maxTaskWorkGroupSizeY_NV = 1, .maxTaskWorkGroupSizeZ_NV = 1, .maxMeshViewCountNV = 4, .limits = { .nonInductiveForLoops = true, .whileLoops = true, .doWhileLoops = true, .generalUniformIndexing = true, .generalAttributeMatrixVectorIndexing = true, .generalVaryingIndexing = true, .generalSamplerIndexing = true, .generalVariableIndexing = true, .generalConstantMatrixVectorIndexing = true } }; } // --------------------------------------------------------------------------------------------------------------------- } // namespace rfx
37.468085
120
0.615701
rfruesmer
d0237d5d9d8be67eead862f7a4432d4d40d43300
1,189
cpp
C++
tests/config/configurationfixture.cpp
DavidHamburg/mqtt-to-influxdb
5a306f1186433c7ee426959a53ea575c03d9a4a1
[ "MIT" ]
null
null
null
tests/config/configurationfixture.cpp
DavidHamburg/mqtt-to-influxdb
5a306f1186433c7ee426959a53ea575c03d9a4a1
[ "MIT" ]
null
null
null
tests/config/configurationfixture.cpp
DavidHamburg/mqtt-to-influxdb
5a306f1186433c7ee426959a53ea575c03d9a4a1
[ "MIT" ]
null
null
null
#include <catch2/catch.hpp> #include <string> #include <libmqtt-to-influxdb/config/configuration.hpp> class configurationfixture{}; TEST_CASE_METHOD(configurationfixture, "can load valid configuration") { auto sample = R"( settings: influxdb: database: iot thermostat: - topic: "zigbee2mqtt/0x00158d00053d224e" measurements: - name: "plug" fields: - name: "dbfield" value: "is_on" match: "on" data-type: "bool" )"; configuration sut{}; auto [result, document] = sut.load(sample); REQUIRE(result == true); } TEST_CASE_METHOD(configurationfixture, "load returns false for invalid input") { configuration sut{}; SECTION("empty input") { auto [result, _] = sut.load(""); REQUIRE(result == false); } SECTION("no device defined") { auto [result, _] = sut.load("<xml>"); REQUIRE(result == false); } SECTION("invalid device definition") { auto sample = R"( thermostat: - topic: "zigbee2mqtt/0x00158d00053d224e" )"; auto [result, _] = sut.load(sample); REQUIRE(result == false); } }
25.847826
80
0.590412
DavidHamburg
d028efd654f17238eecf7a697b7a41655aecab3e
3,578
cpp
C++
test/eventcollision.cpp
breakin/sednl
1003b55793b36dbf1d3e652e375d2990f31b3878
[ "Zlib" ]
9
2015-01-27T16:14:09.000Z
2016-11-10T00:12:35.000Z
test/eventcollision.cpp
breakin/sednl
1003b55793b36dbf1d3e652e375d2990f31b3878
[ "Zlib" ]
2
2016-01-26T13:36:51.000Z
2017-11-07T13:00:55.000Z
test/eventcollision.cpp
breakin/sednl
1003b55793b36dbf1d3e652e375d2990f31b3878
[ "Zlib" ]
4
2021-01-07T08:53:47.000Z
2022-03-10T00:28:00.000Z
// SEDNL - Copyright (c) 2013 Jeremy S. Cochoy // // 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. // Test cases, to check that event consumers dot not bind the same events before the producer's run #include "SEDNL/EventListener.hpp" #include "SEDNL/EventConsumer.hpp" #include <iostream> using namespace SedNL; #define ASSERT(exp, msg) {if (!(exp)) { std::cerr << msg << std::endl; return EXIT_FAILURE; }} int main() { //Test case 1 : Shouldn't throw { try { EventListener listener; EventConsumer consumer(listener); listener.on_connect().set_function([](Connection&){}); consumer.on_disconnect().set_function([](Connection&){}); consumer.on_server_disconnect().set_function([](TCPServer&){}); consumer.on_event().set_function([](Connection&, const Event&){}); consumer.bind("hellomsg").set_function([](Connection&, const Event&){}); listener.run(); listener.join(); } catch(Exception& e) { ASSERT(false, "Test case 1 failed: \n" << e.what()); } } #define TEST_THROW(n, slot, lambda) \ { \ try \ { \ EventListener listener; \ EventConsumer consumer1(listener); \ EventConsumer consumer2(listener); \ \ consumer1.slot.set_function(lambda); \ consumer2.slot.set_function(lambda); \ \ listener.run(); \ listener.join(); \ \ ASSERT(false, "Test case " n " failed: " \ "collision not detected."); \ } \ catch(Exception& e) \ {} \ } //Test cases 3-6 : Should throw TEST_THROW("3", on_disconnect(), [](Connection&){}); TEST_THROW("4", on_server_disconnect(), [](TCPServer&){}); TEST_THROW("5", on_event(), [](Connection&, const Event&){}); TEST_THROW("6", bind("hellomsg"), [](Connection&, const Event&){}); return EXIT_SUCCESS; }
41.126437
99
0.488262
breakin
d02ebb773afc3f29b9aec486947691c0b7af6aa6
11,285
cpp
C++
qt_float/qt_float_tool/qtfloattool.cpp
silas1037/qt_float_tool
58be7f489d0febddcf6a9272ad5363271e340a76
[ "Apache-2.0" ]
null
null
null
qt_float/qt_float_tool/qtfloattool.cpp
silas1037/qt_float_tool
58be7f489d0febddcf6a9272ad5363271e340a76
[ "Apache-2.0" ]
null
null
null
qt_float/qt_float_tool/qtfloattool.cpp
silas1037/qt_float_tool
58be7f489d0febddcf6a9272ad5363271e340a76
[ "Apache-2.0" ]
1
2020-11-03T06:03:05.000Z
2020-11-03T06:03:05.000Z
#include "qtfloattool.h" #include "ui_qtfloattool.h" #include <QDebug> #include <QValidator> #include <QRegExp> #include <float.h> #define UPDATE_OPTION_CHECKBOX 1 #define UPDATE_OPTION_USER_INPUT 2 #define UPDATE_OPTION_REAL_FLOAT 4 #define UPDATE_OPTION_HEX 8 #define UPDATE_OPTION_BITS 16 QtFloatTool::QtFloatTool(QWidget *parent) : QMainWindow(parent), ui(new Ui::QtFloatTool) { ui->setupUi(this); // 用户输入提示 ui->lineEdit->setPlaceholderText(tr("请输入浮点值, 范围[-FLT_MAX, FLT_MAX], 键入Enter结束")); // 用户输入框限定格式 QDoubleValidator *validtor = new QDoubleValidator(); validtor->setRange(-FLT_MAX, FLT_MAX, 22); ui->lineEdit->setValidator(validtor); // lineEdit设置固定大小 this->ui->lineEdit->setFixedSize(401, 38); this->ui->lineEdit_2->setFixedSize(401, 38); this->ui->lineEdit_3->setFixedSize(401, 38); this->ui->lineEdit_4->setFixedSize(401, 38); } QtFloatTool::~QtFloatTool() { delete ui; } void QtFloatTool::binary_changed_callback(int32_t nIndex, int32_t nValue) { uint32_t wValue = this->wBinValue; uint32_t wOpts = UPDATE_OPTION_USER_INPUT | UPDATE_OPTION_REAL_FLOAT | UPDATE_OPTION_HEX | UPDATE_OPTION_BITS; if (nValue) { wValue |= (1 << nIndex); } else { wValue &= (~(1 << nIndex)); } this->update_display(wValue, wOpts); } void QtFloatTool::on_lineEdit_returnPressed() { uint32_t wOpts = UPDATE_OPTION_CHECKBOX | UPDATE_OPTION_REAL_FLOAT | UPDATE_OPTION_HEX | UPDATE_OPTION_BITS | UPDATE_OPTION_USER_INPUT; union { uint32_t wValue; int32_t nValue; float fValue; } tUnionData; tUnionData.fValue = ui->lineEdit->text().toFloat(); this->update_display(tUnionData.wValue, wOpts); } void QtFloatTool::update_display(uint32_t wBinValue, uint32_t wOption) { union { uint32_t wValue; int32_t nValue; float fValue; } tUnionData; if (wBinValue == this->wBinValue) { qDebug() << "no change"; return; } // qDebug() << "bin value = " << wBinValue; tUnionData.wValue = this->wBinValue = wBinValue; if (wOption & UPDATE_OPTION_USER_INPUT) { QString val2 = QString("%1").arg(tUnionData.fValue, 0, 'G'); this->ui->lineEdit->setText(val2); } if (wOption & UPDATE_OPTION_REAL_FLOAT) { QString val = QString("%1").arg(tUnionData.fValue, 0, 'f', 23); this->ui->lineEdit_2->setText(val); } if (wOption & UPDATE_OPTION_HEX) { QString key = QString("0x%1").arg(tUnionData.wValue, 8, 16, QLatin1Char('0')); this->ui->lineEdit_3->setText(key); } if (wOption & UPDATE_OPTION_BITS) { QString binaryDisplay = ""; for (int32_t i = 31; i >= 0; --i) { if (this->wBinValue & (1 << i)) { binaryDisplay += '1'; } else { binaryDisplay += '0'; } } this->ui->lineEdit_4->setText(binaryDisplay); this->ui->label_13->setText(QString::number(this->tBinBits.bSign)); this->ui->label_14->setText(QString::number(this->tBinBits.bExponent)); this->ui->label_15->setText(QString::number(this->tBinBits.bMantissa)); } if (wOption & UPDATE_OPTION_CHECKBOX) { this->set_all_checkbox_value(wBinValue); } } void QtFloatTool::on_pushButton_clicked() { uint32_t wOpts = UPDATE_OPTION_USER_INPUT | UPDATE_OPTION_REAL_FLOAT | UPDATE_OPTION_HEX | UPDATE_OPTION_BITS | UPDATE_OPTION_CHECKBOX; this->update_display(0, wOpts); this->ui->lineEdit->clear(); } void QtFloatTool::on_checkBox_0_stateChanged(int arg1) { this->binary_changed_callback(0, arg1); } void QtFloatTool::on_checkBox_1_stateChanged(int arg1) { this->binary_changed_callback(1, arg1); } void QtFloatTool::on_checkBox_2_stateChanged(int arg1) { this->binary_changed_callback(2, arg1); } void QtFloatTool::on_checkBox_3_stateChanged(int arg1) { this->binary_changed_callback(3, arg1); } void QtFloatTool::on_checkBox_4_stateChanged(int arg1) { this->binary_changed_callback(4, arg1); } void QtFloatTool::on_checkBox_5_stateChanged(int arg1) { this->binary_changed_callback(5, arg1); } void QtFloatTool::on_checkBox_6_stateChanged(int arg1) { this->binary_changed_callback(6, arg1); } void QtFloatTool::on_checkBox_7_stateChanged(int arg1) { this->binary_changed_callback(7, arg1); } void QtFloatTool::on_checkBox_8_stateChanged(int arg1) { this->binary_changed_callback(8, arg1); } void QtFloatTool::on_checkBox_9_stateChanged(int arg1) { this->binary_changed_callback(9, arg1); } void QtFloatTool::on_checkBox_10_stateChanged(int arg1) { this->binary_changed_callback(10, arg1); } void QtFloatTool::on_checkBox_11_stateChanged(int arg1) { this->binary_changed_callback(11, arg1); } void QtFloatTool::on_checkBox_12_stateChanged(int arg1) { this->binary_changed_callback(12, arg1); } void QtFloatTool::on_checkBox_13_stateChanged(int arg1) { this->binary_changed_callback(13, arg1); } void QtFloatTool::on_checkBox_14_stateChanged(int arg1) { this->binary_changed_callback(14, arg1); } void QtFloatTool::on_checkBox_15_stateChanged(int arg1) { this->binary_changed_callback(15,arg1); } void QtFloatTool::on_checkBox_16_stateChanged(int arg1) { this->binary_changed_callback(16, arg1); } void QtFloatTool::on_checkBox_17_stateChanged(int arg1) { this->binary_changed_callback(17, arg1); } void QtFloatTool::on_checkBox_18_stateChanged(int arg1) { this->binary_changed_callback(18, arg1); } void QtFloatTool::on_checkBox_19_stateChanged(int arg1) { this->binary_changed_callback(19, arg1); } void QtFloatTool::on_checkBox_20_stateChanged(int arg1) { this->binary_changed_callback(20, arg1); } void QtFloatTool::on_checkBox_21_stateChanged(int arg1) { this->binary_changed_callback(21, arg1); } void QtFloatTool::on_checkBox_22_stateChanged(int arg1) { this->binary_changed_callback(22, arg1); } void QtFloatTool::on_checkBox_23_stateChanged(int arg1) { this->binary_changed_callback(23, arg1); }void QtFloatTool::on_checkBox_24_stateChanged(int arg1) { this->binary_changed_callback(24, arg1); } void QtFloatTool::on_checkBox_25_stateChanged(int arg1) { this->binary_changed_callback(25, arg1); } void QtFloatTool::on_checkBox_26_stateChanged(int arg1) { this->binary_changed_callback(26, arg1); } void QtFloatTool::on_checkBox_27_stateChanged(int arg1) { this->binary_changed_callback(27, arg1); } void QtFloatTool::on_checkBox_28_stateChanged(int arg1) { this->binary_changed_callback(28, arg1); } void QtFloatTool::on_checkBox_29_stateChanged(int arg1) { this->binary_changed_callback(29, arg1); } void QtFloatTool::on_checkBox_30_stateChanged(int arg1) { this->binary_changed_callback(30, arg1); } void QtFloatTool::on_checkBox_31_stateChanged(int arg1) { this->binary_changed_callback(31, arg1); } bool QtFloatTool::get_checkbox_value(int32_t nOffest) { switch (nOffest) { case 0: return ui->checkBox_0->isChecked(); case 1: return ui->checkBox_1->isChecked(); case 2: return ui->checkBox_2->isChecked(); case 3: return ui->checkBox_3->isChecked(); case 4: return ui->checkBox_4->isChecked(); case 5: return ui->checkBox_5->isChecked(); case 6: return ui->checkBox_6->isChecked(); case 7: return ui->checkBox_7->isChecked(); case 8: return ui->checkBox_8->isChecked(); case 9: return ui->checkBox_9->isChecked(); case 10: return ui->checkBox_10->isChecked(); case 11: return ui->checkBox_11->isChecked(); case 12: return ui->checkBox_12->isChecked(); case 13: return ui->checkBox_13->isChecked(); case 14: return ui->checkBox_14->isChecked(); case 15: return ui->checkBox_15->isChecked(); case 16: return ui->checkBox_16->isChecked(); case 17: return ui->checkBox_17->isChecked(); case 18: return ui->checkBox_18->isChecked(); case 19: return ui->checkBox_19->isChecked(); case 20: return ui->checkBox_20->isChecked(); case 21: return ui->checkBox_21->isChecked(); case 22: return ui->checkBox_22->isChecked(); case 23: return ui->checkBox_23->isChecked(); case 24: return ui->checkBox_24->isChecked(); case 25: return ui->checkBox_25->isChecked(); case 26: return ui->checkBox_26->isChecked(); case 27: return ui->checkBox_27->isChecked(); case 28: return ui->checkBox_28->isChecked(); case 29: return ui->checkBox_29->isChecked(); case 30: return ui->checkBox_30->isChecked(); case 31: return ui->checkBox_31->isChecked(); } return false; } void QtFloatTool::set_checkbox_value(int32_t nOffest, bool bValue) { switch (nOffest) { case 0: ui->checkBox_0->setChecked(bValue);break; case 1: ui->checkBox_1->setChecked(bValue);break; case 2: ui->checkBox_2->setChecked(bValue);break; case 3: ui->checkBox_3->setChecked(bValue);break; case 4: ui->checkBox_4->setChecked(bValue);break; case 5: ui->checkBox_5->setChecked(bValue);break; case 6: ui->checkBox_6->setChecked(bValue);break; case 7: ui->checkBox_7->setChecked(bValue);break; case 8: ui->checkBox_8->setChecked(bValue);break; case 9: ui->checkBox_9->setChecked(bValue);break; case 10: ui->checkBox_10->setChecked(bValue);break; case 11: ui->checkBox_11->setChecked(bValue);break; case 12: ui->checkBox_12->setChecked(bValue);break; case 13: ui->checkBox_13->setChecked(bValue);break; case 14: ui->checkBox_14->setChecked(bValue);break; case 15: ui->checkBox_15->setChecked(bValue);break; case 16: ui->checkBox_16->setChecked(bValue);break; case 17: ui->checkBox_17->setChecked(bValue);break; case 18: ui->checkBox_18->setChecked(bValue);break; case 19: ui->checkBox_19->setChecked(bValue);break; case 20: ui->checkBox_20->setChecked(bValue);break; case 21: ui->checkBox_21->setChecked(bValue);break; case 22: ui->checkBox_22->setChecked(bValue);break; case 23: ui->checkBox_23->setChecked(bValue);break; case 24: ui->checkBox_24->setChecked(bValue);break; case 25: ui->checkBox_25->setChecked(bValue);break; case 26: ui->checkBox_26->setChecked(bValue);break; case 27: ui->checkBox_27->setChecked(bValue);break; case 28: ui->checkBox_28->setChecked(bValue);break; case 29: ui->checkBox_29->setChecked(bValue);break; case 30: ui->checkBox_30->setChecked(bValue);break; case 31: ui->checkBox_31->setChecked(bValue);break; } } void QtFloatTool::set_all_checkbox_value(uint32_t nValue) { for (int32_t i = 0; i < 32; ++i) { this->set_checkbox_value(i, nValue & (1 << i)); } }
27.192771
86
0.663181
silas1037
d030caa59755374feab288f8e39bb2d841aa8689
9,104
cpp
C++
system-equipment-data/src/gpuinfo.cpp
Sytroxitz/sed
eb751ee51e9c7231f4a76e5906731fca55bee21e
[ "MIT" ]
1
2021-06-24T23:19:03.000Z
2021-06-24T23:19:03.000Z
system-equipment-data/src/gpuinfo.cpp
Sytroxitz/sed
eb751ee51e9c7231f4a76e5906731fca55bee21e
[ "MIT" ]
null
null
null
system-equipment-data/src/gpuinfo.cpp
Sytroxitz/sed
eb751ee51e9c7231f4a76e5906731fca55bee21e
[ "MIT" ]
null
null
null
#include "headers/gpuinfo.h" const std::string GPUInfo::NVIDIA_IDENTIFIER_STRING = "NVIDIA"; const std::string GPUInfo::INTEL_IDENTIFIER_STRING = "INTEL"; const std::string GPUInfo::AMD_IDENTIFIER_STRING = "AMD"; const std::string GPUInfo::NAME_IDENTIFIER_STRING = "Name="; const std::string GPUInfo::MANUFACTURER_IDENTIFIER_STRING = "AdapterCompatibility="; const std::string GPUInfo::ADAPTER_RAM_IDENTIFIER_STRING = "AdapterRAM="; const std::string GPUInfo::REFRESH_RATE_IDENTIFIER_STRING = "CurrentRefreshRate="; const std::string GPUInfo::DRIVER_VERSION_IDENTIFIER_STRING = "DriverVersion="; const std::string GPUInfo::VIDEO_ARCHITECTURE_IDENTIFIER_STRING = "VideoArchitecture="; const std::string GPUInfo::VIDEO_MEMORY_TYPE_IDENTIFIER_STRING = "VideoMemoryType"; const std::string GPUInfo::VIDEO_MODE_DESCRIPTION_IDENTIFIER_STRING = "VideoModeDescription="; const std::string GPUInfo::VIDEO_PROCESSOR_IDENTIFIER_STRING = "VideoProcessor="; const std::string GPUInfo::CAPTION_IDENTIFIER_STRING = "Caption="; GPUInfo::GPUInfo(const std::vector<std::string> &rawData, int gpuNumber) : _name{ "" }, _manufacturer{ "" }, _caption{ "" }, _adapterRAM{ "" }, _refreshRate{ "" }, _driverVersion{ "" }, _videoArchitecture{ "" }, _videoMemoryType{ "" }, _videoModeDescription{""}, _videoProcessor {""}, _gpuNumber{gpuNumber} { for (auto iter = rawData.begin(); iter != rawData.end(); iter++) { //Name if ((iter->find(NAME_IDENTIFIER_STRING) != std::string::npos) && (iter->find(NAME_IDENTIFIER_STRING) == 0)) { size_t foundPosition = iter->find(NAME_IDENTIFIER_STRING); this->_name = iter->substr(foundPosition + NAME_IDENTIFIER_STRING.length()); } //Manufacturer if ((iter->find(MANUFACTURER_IDENTIFIER_STRING) != std::string::npos) && (iter->find(MANUFACTURER_IDENTIFIER_STRING) == 0)) { size_t foundPosition = iter->find(MANUFACTURER_IDENTIFIER_STRING); this->_manufacturer = iter->substr(foundPosition + MANUFACTURER_IDENTIFIER_STRING.length()); } //Caption if ((iter->find(CAPTION_IDENTIFIER_STRING) != std::string::npos) && (iter->find(CAPTION_IDENTIFIER_STRING) == 0)) { size_t foundPosition = iter->find(CAPTION_IDENTIFIER_STRING); this->_caption = iter->substr(foundPosition + CAPTION_IDENTIFIER_STRING.length()); } //Adapter RAM if ((iter->find(ADAPTER_RAM_IDENTIFIER_STRING) != std::string::npos) && (iter->find(ADAPTER_RAM_IDENTIFIER_STRING) == 0)) { size_t foundPosition = iter->find(ADAPTER_RAM_IDENTIFIER_STRING); std::string capacityString = iter->substr(foundPosition + ADAPTER_RAM_IDENTIFIER_STRING.length()); long long int capacity{ 0 }; try { capacity = std::stoll(capacityString); this->_adapterRAM = toString(capacity / 1000000) + "MB (" + toString(capacity) + " Bytes)"; } catch (std::exception &e) { (void)e; this->_adapterRAM = capacityString + " Bytes"; } } //Refresh Rate if ((iter->find(REFRESH_RATE_IDENTIFIER_STRING) != std::string::npos) && (iter->find(REFRESH_RATE_IDENTIFIER_STRING) == 0)) { size_t foundPosition = iter->find(REFRESH_RATE_IDENTIFIER_STRING); this->_refreshRate = iter->substr(foundPosition + REFRESH_RATE_IDENTIFIER_STRING.length()) + "MHz"; if (this->_refreshRate == "MHz") { this->_refreshRate = ""; } } //Driver Version if ((iter->find(DRIVER_VERSION_IDENTIFIER_STRING) != std::string::npos) && (iter->find(DRIVER_VERSION_IDENTIFIER_STRING) == 0)) { size_t foundPosition = iter->find(DRIVER_VERSION_IDENTIFIER_STRING); this->_driverVersion = iter->substr(foundPosition + DRIVER_VERSION_IDENTIFIER_STRING.length()); } //Video Architecture if ((iter->find(VIDEO_ARCHITECTURE_IDENTIFIER_STRING) != std::string::npos) && (iter->find(VIDEO_ARCHITECTURE_IDENTIFIER_STRING) == 0)) { size_t foundPosition = iter->find(VIDEO_ARCHITECTURE_IDENTIFIER_STRING); std::string videoArchitectureString = iter->substr(foundPosition, VIDEO_ARCHITECTURE_IDENTIFIER_STRING.length()); this->_videoArchitecture = getVideoArchitecture(videoArchitectureString); } //Video Memory Type if ((iter->find(VIDEO_MEMORY_TYPE_IDENTIFIER_STRING) != std::string::npos) && (iter->find(VIDEO_MEMORY_TYPE_IDENTIFIER_STRING) == 0)) { size_t foundPosition = iter->find(VIDEO_MEMORY_TYPE_IDENTIFIER_STRING); std::string videoMemoryTypeString = iter->substr(foundPosition, VIDEO_MEMORY_TYPE_IDENTIFIER_STRING.length()); this->_videoMemoryType = getVideoMemoryType(videoMemoryTypeString); } //Video Mode Description if ((iter->find(VIDEO_MODE_DESCRIPTION_IDENTIFIER_STRING) != std::string::npos) && (iter->find(VIDEO_MODE_DESCRIPTION_IDENTIFIER_STRING) == 0)) { size_t foundPosition = iter->find(VIDEO_MODE_DESCRIPTION_IDENTIFIER_STRING); this->_videoModeDescription = iter->substr(foundPosition + VIDEO_MODE_DESCRIPTION_IDENTIFIER_STRING.length()); } //Video Processor if ((iter->find(VIDEO_PROCESSOR_IDENTIFIER_STRING) != std::string::npos) && (iter->find(VIDEO_PROCESSOR_IDENTIFIER_STRING) == 0)) { size_t foundPosition = iter->find(VIDEO_PROCESSOR_IDENTIFIER_STRING); this->_videoProcessor = iter->substr(foundPosition + VIDEO_PROCESSOR_IDENTIFIER_STRING.length()); } } //In case any of these values are missing or don't get assigned if (this->_name == "") { this->_name = "Unknown"; } if (this->_manufacturer == "") { this->_manufacturer = "Unknown"; } if (this->_caption == "") { this->_caption = "Unknown"; } if (this->_adapterRAM == "") { this->_adapterRAM = "Unknown"; } if (this->_refreshRate == "") { this->_refreshRate = "Unknown"; } if (this->_driverVersion == "") { this->_driverVersion = "Unknown"; } if (this->_videoArchitecture == "") { this->_videoArchitecture = "Unknown"; } if (this->_videoMemoryType == "") { this->_videoMemoryType = "Unknown"; } if (this->_videoModeDescription == "") { this->_videoModeDescription = "Unknown"; } if (this->_videoProcessor == "") { this->_videoProcessor = "Unknown"; } } std::string GPUInfo::getVideoArchitecture(const std::string &videoArchitectureString) const { int videoArch{2}; try { videoArch = std::stoi(videoArchitectureString); } catch (std::exception &e) { (void)e; videoArch = 2; } //As per https://msdn.microsoft.com/en-us/library/aa394512(v=vs.85).aspx switch (videoArch) { case 1: return "Other"; case 2: return "Unknown"; case 3: return "CGA"; case 4: return "EGA"; case 5: return "VGA"; case 6: return "SVGA"; case 7: return "MDA"; case 8: return "HGC"; case 9: return "MCGA"; case 10: return "8514A"; case 11: return "XGA"; case 12: return "Linear Frame Buffer"; case 160: return "PC - 98"; default: return "Unknown"; } } std::string GPUInfo::getVideoMemoryType(const std::string &videoMemoryTypeString) const { int videoMemoryType{2}; try { videoMemoryType = std::stoi(videoMemoryTypeString); } catch (std::exception &e) { (void)e; videoMemoryType = 2; } switch (videoMemoryType) { case 1: return "Other"; case 2: return "Unknown"; case 3: return "VRAM"; case 4: return "DRAM"; case 5: return "SRAM"; case 6: return "WRAM"; case 7: return "EDO_RAM"; case 8: return "Burst Synchronous DRAM"; case 9: return "Pipelined Burst SRAM"; case 10: return "CDRAM"; case 11: return "3DRAM"; case 12: return "SDRAM"; case 13: return "SGRAM"; default: return "Unknown"; } } std::string GPUInfo::name() const { return this->_name; } std::string GPUInfo::manufacturer() const { return this->_manufacturer; } std::string GPUInfo::caption() const { return this->_caption; } std::string GPUInfo::adapterRAM() const { return this->_adapterRAM; } std::string GPUInfo::refreshRate() const { return this->_refreshRate; } std::string GPUInfo::driverVersion() const { return this->_driverVersion; } std::string GPUInfo::videoArchitecture() const { return this->_videoArchitecture; } std::string GPUInfo::videoProcessor() const { return this->_videoProcessor; } std::string GPUInfo::videoMemoryType() const { return this->_videoMemoryType; } std::string GPUInfo::videoModeDescription() const { return this->_videoModeDescription; } int GPUInfo::gpuNumber() const { return this->_gpuNumber; }
36.8583
153
0.646309
Sytroxitz
d034a054c02450f67ae0f682c7b79be1de52947d
567
cpp
C++
module04/ex01/Enemy.cpp
M-Philippe/cpp_piscine
9584ebcb030c54ca522dbcf795bdcb13a0325f77
[ "MIT" ]
null
null
null
module04/ex01/Enemy.cpp
M-Philippe/cpp_piscine
9584ebcb030c54ca522dbcf795bdcb13a0325f77
[ "MIT" ]
null
null
null
module04/ex01/Enemy.cpp
M-Philippe/cpp_piscine
9584ebcb030c54ca522dbcf795bdcb13a0325f77
[ "MIT" ]
null
null
null
#include "Enemy.hpp" Enemy::Enemy() {} Enemy::Enemy(int hp, std::string const& type) { _hp = hp; _type = type; } Enemy::Enemy(const Enemy& org) { *this = org; } Enemy& Enemy::operator=(const Enemy& org) { _hp = org._hp; _type = org._type; return (*this); } Enemy::~Enemy() {} int Enemy::getHp() const { return (_hp); } std::string Enemy::getType() const { return (_type); } void Enemy::takeDamage(int atkDmg) { if (atkDmg > getHp()) return ; _hp -= atkDmg; } void Enemy::testClass() { std::cout << getType() << " " << getHp() << std::endl; }
14.921053
55
0.597884
M-Philippe
d03d0bd603fdfb5a67590c267e62338e6a2e3060
1,179
cpp
C++
umd/ddi/umd_ddi_deferredcontext.cpp
tnamet/Crystal
9fbce322a014547326ba690092e412d019f1ecb4
[ "MIT" ]
2
2021-07-09T19:41:39.000Z
2022-02-01T10:50:05.000Z
umd/ddi/umd_ddi_deferredcontext.cpp
tnamet/Crystal
9fbce322a014547326ba690092e412d019f1ecb4
[ "MIT" ]
1
2021-07-09T19:50:40.000Z
2021-07-10T09:01:38.000Z
umd/ddi/umd_ddi_deferredcontext.cpp
tnamet/Crystal
9fbce322a014547326ba690092e412d019f1ecb4
[ "MIT" ]
1
2022-02-01T10:50:08.000Z
2022-02-01T10:50:08.000Z
#include "pch.h" namespace Crystal { namespace UMD { namespace DDI { //////////////////////////////////////////////////////////////////////////////// VOID WINAPI CreateDeferredContext( D3D10DDI_HDEVICE hDevice, const D3D11DDIARG_CREATEDEFERREDCONTEXT* pCreateDeferredContext ) { LOG_DLL_ENTRY; } //////////////////////////////////////////////////////////////////////////////// HRESULT WINAPI RecycleCreateDeferredContext( D3D10DDI_HDEVICE hDevice, const D3D11DDIARG_CREATEDEFERREDCONTEXT* pCreateDeferredContext ) { LOG_DLL_ENTRY; return E_FAIL; } //////////////////////////////////////////////////////////////////////////////// SIZE_T WINAPI CalcDeferredContextHandleSize( D3D10DDI_HDEVICE hDevice, D3D11DDI_HANDLETYPE HandleType, void* pICObject ) { LOG_DLL_ENTRY; return 0; } //////////////////////////////////////////////////////////////////////////////// VOID WINAPI CheckDeferredContextHandleSizes( D3D10DDI_HDEVICE hDevice, UINT* pHSizes, D3D11DDI_HANDLESIZE* pHandleSize ) { LOG_DLL_ENTRY; } } // namespace DDI } // namespace UMD } // namespace Crystal
24.061224
81
0.518236
tnamet
d03d4743fa6bac993003ee16a2fb3c65ac5be83b
86
cpp
C++
src/hal/GPIO_base.cpp
suburbanembedded/emb_util
ded1f54e5c10ce962351416e6b6840dbedb112ba
[ "BSD-3-Clause" ]
null
null
null
src/hal/GPIO_base.cpp
suburbanembedded/emb_util
ded1f54e5c10ce962351416e6b6840dbedb112ba
[ "BSD-3-Clause" ]
null
null
null
src/hal/GPIO_base.cpp
suburbanembedded/emb_util
ded1f54e5c10ce962351416e6b6840dbedb112ba
[ "BSD-3-Clause" ]
null
null
null
#include "hal/GPIO_base.hpp" GPIO_base::GPIO_base() { } GPIO_base::~GPIO_base() { }
8.6
28
0.674419
suburbanembedded
d03d797fa13e4b039474557606e84c462d3b9c35
1,248
cpp
C++
RingedOrb/Graphics/roGPUContextManager.cpp
JohnCKangwa/RingedOrb
7aa8ab642e8938838c86a8d9951b589976f3ebd9
[ "MIT" ]
null
null
null
RingedOrb/Graphics/roGPUContextManager.cpp
JohnCKangwa/RingedOrb
7aa8ab642e8938838c86a8d9951b589976f3ebd9
[ "MIT" ]
null
null
null
RingedOrb/Graphics/roGPUContextManager.cpp
JohnCKangwa/RingedOrb
7aa8ab642e8938838c86a8d9951b589976f3ebd9
[ "MIT" ]
null
null
null
#include "roGPUContextManager.h" #include "roGPUContext12.h" #include "roCommandAllocator.h" #include "roCommandQueue.h" roGPUContext12* roGPUContextManager::GetGPUContext(std::string name) { std::lock_guard<std::mutex> lg(sm_GPUContexManagerMutex); roGPUContext12* gpuContext = nullptr; if (!sm_FreeGPUContextPool.empty()) { gpuContext = sm_FreeGPUContextPool.back(); gpuContext->Reset(name); sm_FreeGPUContextPool.pop_back(); return gpuContext; } std::unique_ptr<roGPUContext12> _gpuContext = std::make_unique<roGPUContext12>(name); gpuContext = _gpuContext.get(); sm_GpuContextPool.push_back(std::move(_gpuContext)); return gpuContext; } void roGPUContextManager::Shutdown() { sm_FreeGPUContextPool.clear(); for (int i = 0; i < sm_GpuContextPool.size(); i++) { sm_GpuContextPool[i].reset(); } } void roGPUContextManager::DiscardGPUContext(roGPUContext12* gpu_context) { std::lock_guard<std::mutex> lg(sm_GPUContexManagerMutex); sm_FreeGPUContextPool.push_back(gpu_context); } std::vector<std::unique_ptr<roGPUContext12>> roGPUContextManager:: sm_GpuContextPool; std::vector<roGPUContext12*> roGPUContextManager:: sm_FreeGPUContextPool; std::mutex roGPUContextManager:: sm_GPUContexManagerMutex;
28.363636
85
0.773237
JohnCKangwa
d03ec768e65c6cc702d2e1a2a3824cda3c74d951
786
cpp
C++
essentials/demos/ex-variants/main.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
16
2017-01-11T17:28:03.000Z
2021-09-27T16:12:01.000Z
essentials/demos/ex-variants/main.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
null
null
null
essentials/demos/ex-variants/main.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
4
2017-03-17T02:44:32.000Z
2021-01-22T07:57:34.000Z
/************************************************************************* * * Copyright (c) 2016 The Qt Company * All rights reserved. * * See the LICENSE.txt file shipped along with this file for the license. * *************************************************************************/ #include <QDebug> #include <QString> int main(int, char *[]) { QVariant variant(123); qDebug() << variant.typeName() << variant.userType(); // int 2 qDebug() << variant.toInt() << variant.value<int>(); // 123 123 variant = QVariant(QObject::tr("hello")); if (variant.canConvert<int>()) qDebug() << variant.toInt(); // 0 QString string = QStringLiteral("123"); variant = QVariant::fromValue<QString>(string); qDebug() << variant.toInt(); // 123 }
28.071429
75
0.503817
sfaure-witekio
d03f1774db2ae493d4e53fdfe507f6130ec37207
121
cpp
C++
src/app/kxlol/PlayerObject.cpp
wohaaitinciu/zpublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
50
2015-01-07T01:54:54.000Z
2021-01-15T00:41:48.000Z
src/app/kxlol/PlayerObject.cpp
sinmx/ZPublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
1
2015-05-26T07:40:19.000Z
2015-05-26T07:40:19.000Z
src/app/kxlol/PlayerObject.cpp
sinmx/ZPublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
39
2015-01-07T02:03:15.000Z
2021-01-15T00:41:50.000Z
#include "stdafx.h" #include "PlayerObject.h" CPlayerObject::CPlayerObject() { } CPlayerObject::~CPlayerObject() { }
9.307692
31
0.710744
wohaaitinciu
d0433bff624d617c7e6e0884e323f423bd599b9b
1,792
cpp
C++
solved/f-h/factovisors/factovisors.cpp
abuasifkhan/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-09-30T19:18:04.000Z
2021-06-26T21:11:30.000Z
solved/f-h/factovisors/factovisors.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
null
null
null
solved/f-h/factovisors/factovisors.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-01-04T09:49:54.000Z
2021-06-03T13:18:44.000Z
#include <cmath> #include <cstdio> #include <vector> using namespace std; #define cFor(t,v,c) for(t::const_iterator v=c.begin(); v != c.end(); ++v) typedef pair<int, int> II; typedef vector<int> IV; typedef vector<II> IIV; // // Number Theory // #define IsComp(n) (_c[n>>6]&(1<<((n>>1)&31))) #define SetComp(n) _c[n>>6]|=(1<<((n>>1)&31)) namespace Num { const int MAX = 1 << 16; // 2^16 const int LMT = 1 << 8; // sqrt(MAX) int _c[(MAX>>6)+1]; IV primes; void prime_sieve() { for (int i = 3; i <= LMT; i += 2) if (!IsComp(i)) for (int j = i*i; j <= MAX; j+=i+i) SetComp(j); primes.push_back(2); for (int i=3; i <= MAX; i+=2) if (!IsComp(i)) primes.push_back(i); } void prime_factorize(int n, IIV &f) { int sn = sqrt(n); cFor (IV, p, primes) { int prime = *p; if (prime > sn) break; if (n % prime) continue; int e = 0; for (; n % prime == 0; e++, n /= prime); f.push_back(II(prime, e)); sn = sqrt(n); } if (n > 1) f.push_back(II(n, 1)); } // Calculates the highest exponent of prime p that divides n! int pow_div_fact(int n, int p) { int sd = 0; for (int N=n; N; N /= p) sd += N % p; return (n-sd)/(p-1); } } using namespace Num; int n, m; bool solve() { if (m == 1) return true; if (m == 0) return false; IIV factors; prime_factorize(m, factors); cFor (IIV, f, factors) if (pow_div_fact(n, f->first) < f->second) return false; return true; } int main() { prime_sieve(); while (true) { if (scanf("%d%d", &n, &m) != 2) break; printf("%d %s %d!\n", m, solve() ? "divides" : "does not divide", n); } return 0; }
22.4
78
0.500558
abuasifkhan
d046ce315c7172e9ede50b16af15a29655ee076e
1,270
cpp
C++
School/Grade 10/01. Struct/exercise_3.cpp
slaweykow/School_CPP
d7dda3740f88eb4be925fe478305d8be30ff40fc
[ "MIT" ]
null
null
null
School/Grade 10/01. Struct/exercise_3.cpp
slaweykow/School_CPP
d7dda3740f88eb4be925fe478305d8be30ff40fc
[ "MIT" ]
null
null
null
School/Grade 10/01. Struct/exercise_3.cpp
slaweykow/School_CPP
d7dda3740f88eb4be925fe478305d8be30ff40fc
[ "MIT" ]
null
null
null
#include <cstdlib> #include <iostream> using namespace std; int main(int argc, char *argv[]) { int n, vazovBooks = 0, softPressBooks = 0; cout << "Enter a number: "; cin >> n; struct Book { char name[20]; char author[30]; char publisher[20]; int yearOfRelease; } books[n]; for(int i = 0; i < n; i++) { cout << "Enter name: "; cin >> books[i].name; cout << "Enter author: "; cin >> books[i].author; cout << "Enter publisher: "; cin >> books[i].publisher; cout << "Enter year of release: "; cin >> books[i].yearOfRelease; cout << "------------" << endl; } cout << "Books released after 2000:"; for (int i = 0; i < n; i++) { if (books[i].yearOfRelease >= 2000) { cout << books[i].name << " "; } } cout << endl; for (int i = 0; i < n; i++) { if (books[i].author == "Ivan Vazov") { vazovBooks++; } } cout << "Books released by Ivan Vazov: " << vazovBooks << endl; for (int i = 0; i < n; i++) { if (books[i].publisher == "SoftPress") { softPressBooks = 1; break; } } if (softPressBooks) { cout << "There are books published by SoftPress." << endl; } else { cout << "There aren't any books published by SoftPress." << endl; } system("pause"); return 0; }
16.075949
73
0.546457
slaweykow
d04747d9d8bf2af20046ce7ca83bb86c2007c451
4,061
cpp
C++
weightinit/Init3DGaussWeights.cpp
PetaVision/ObsoletePV
e99a42bf4292e944b252e144b5e07442b0715697
[ "MIT" ]
null
null
null
weightinit/Init3DGaussWeights.cpp
PetaVision/ObsoletePV
e99a42bf4292e944b252e144b5e07442b0715697
[ "MIT" ]
null
null
null
weightinit/Init3DGaussWeights.cpp
PetaVision/ObsoletePV
e99a42bf4292e944b252e144b5e07442b0715697
[ "MIT" ]
null
null
null
/* * Init3DGaussWeights.cpp * * Created on: Sep 6, 2011 * Author: kpeterson */ #include "Init3DGaussWeights.hpp" #include "Init3DGaussWeightsParams.hpp" namespace PV { Init3DGaussWeights::Init3DGaussWeights(HyPerConn * conn) { initialize_base(); initialize(conn); } Init3DGaussWeights::Init3DGaussWeights() { initialize_base(); } Init3DGaussWeights::~Init3DGaussWeights() { } int Init3DGaussWeights::initialize_base() { return PV_SUCCESS; } int Init3DGaussWeights::initialize(HyPerConn * conn) { int status = InitGauss2DWeights::initialize(conn); return status; } InitWeightsParams * Init3DGaussWeights::createNewWeightParams() { InitWeightsParams * tempPtr = new Init3DGaussWeightsParams(callingConn); return tempPtr; } int Init3DGaussWeights::calcWeights(/* PVPatch * patch */ pvdata_t * dataStart, int patchIndex, int arborId) { Init3DGaussWeightsParams *weightParamPtr = dynamic_cast<Init3DGaussWeightsParams*>(weightParams); if(weightParamPtr==NULL) { fprintf(stderr, "Failed to recast pointer to weightsParam! Exiting..."); exit(1); } weightParamPtr->calcOtherParams(patchIndex); weightParamPtr->setTime(arborId); gauss3DWeights(dataStart, weightParamPtr); return PV_SUCCESS; } /** * calculate temporal-spatial gaussian filter for use in optic flow detector */ int Init3DGaussWeights::gauss3DWeights(/* PVPatch * patch */ pvdata_t * w_tmp, Init3DGaussWeightsParams * weightParamPtr) { //load necessary params: int nfPatch_tmp = weightParamPtr->getnfPatch(); int nyPatch_tmp = weightParamPtr->getnyPatch(); int nxPatch_tmp = weightParamPtr->getnxPatch(); float taspect=weightParamPtr->getTAspect(); float yaspect=weightParamPtr->getYAspect(); float shift=weightParamPtr->getShift(); float shiftT=weightParamPtr->getShiftT(); int numFlanks=weightParamPtr->getNumFlanks(); float sigma=weightParamPtr->getSigma(); int sx_tmp=weightParamPtr->getsx(); int sy_tmp=weightParamPtr->getsy(); int sf_tmp=weightParamPtr->getsf(); double r2Max=weightParamPtr->getr2Max(); float time = (float)-weightParamPtr->getTime(); float thetaXT = weightParamPtr->getThetaXT(); // loop over all post-synaptic cells in temporary patch for (int fPost = 0; fPost < nfPatch_tmp; fPost++) { float thPost = weightParamPtr->calcThPost(fPost); //TODO: add additional weight factor for difference between thPre and thPost if(weightParamPtr->checkThetaDiff(thPost)) continue; for (int jPost = 0; jPost < nyPatch_tmp; jPost++) { float yDelta = weightParamPtr->calcYDelta(jPost); for (int iPost = 0; iPost < nxPatch_tmp; iPost++) { float xDelta = weightParamPtr->calcXDelta(iPost); if(weightParamPtr->isSameLocOrSelf(xDelta, yDelta, fPost)) continue; // rotate the reference frame by th (change sign of thPost?) float xp = +xDelta * cosf(thPost) + yDelta * sinf(thPost); float yp = -xDelta * sinf(thPost) + yDelta * cosf(thPost); if(weightParamPtr->checkBowtieAngle(yp, xp)) continue; float tp = +time * cosf(thetaXT) + yp * sinf(thetaXT); float ytp = -time * sinf(thetaXT) + yp * cosf(thetaXT); // include shift to flanks double d2 = xp * xp + (yaspect * (ytp - shift) * yaspect * (ytp - shift)) + (taspect * (tp-shiftT) * taspect * (tp-shiftT)); int index = iPost * sx_tmp + jPost * sy_tmp + fPost * sf_tmp; w_tmp[index] = 0; if (d2 <= r2Max) { w_tmp[index] += expf(-d2 / (2.0f * sigma * sigma)); } if (numFlanks > 1) { // shift in opposite direction d2 = xp * xp + (yaspect * (ytp + shift) * yaspect * (ytp + shift)) + (taspect * (tp-shiftT) * taspect * (tp-shiftT)); if (d2 <= r2Max) { w_tmp[index] += expf(-d2 / (2.0f * sigma * sigma)); } } } } } return PV_SUCCESS; } } /* namespace PV */
32.488
136
0.651071
PetaVision
d0496181f37b10eda56b1e0fe54a0a1361d3e139
1,020
cpp
C++
cmake/tests/cxx11_explicit_variadic_templates.cpp
bremerm31/hpx
a9d22b8eb2e443d2e95991da9b1a621f94d4ebaa
[ "BSL-1.0" ]
3
2017-04-06T16:36:38.000Z
2018-05-19T11:28:54.000Z
cmake/tests/cxx11_explicit_variadic_templates.cpp
bremerm31/hpx
a9d22b8eb2e443d2e95991da9b1a621f94d4ebaa
[ "BSL-1.0" ]
1
2018-08-13T17:42:55.000Z
2018-08-13T18:20:23.000Z
cmake/tests/cxx11_explicit_variadic_templates.cpp
biddisco/hpx
2d244e1e27c6e014189a6cd59c474643b31fad4b
[ "BSL-1.0" ]
2
2018-05-25T06:33:50.000Z
2019-02-25T20:09:13.000Z
// Copyright (C) 2016 Hartmut Kaiser // // 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) template <typename ... Ts> struct tuple { template <typename ... Args> tuple(Args && ...) {} }; struct tag1 {}; struct tag2 {}; struct tag3 {}; template <typename T> struct identity { typedef T type; }; template <typename Tag, typename T> struct tagged_type { typedef typename identity<Tag(T)>::type type; }; template <typename ... Tags, typename ... Ts> tuple<typename tagged_type<Tags, Ts>::type...> foo(Ts && ...) { return tuple<typename tagged_type<Tags, Ts>::type...>(); } template <typename ... Tags, typename ... Ts> tuple<typename tagged_type<Tags, Ts>::type...> foo(tuple<Ts...> && t) { return tuple<typename tagged_type<Tags, Ts>::type...>(); } int main() { auto t1 = foo<tag1, tag2, tag3>(42, 43, 44); auto t2 = foo<tag1, tag2, tag3>(tuple<int, int, int>(42, 43, 44)); }
20.816327
80
0.642157
bremerm31
d04a0edd2c69e258bbe3efc01adbf602b85a9e75
2,949
cpp
C++
amot/amot_pool.cpp
sartrey/cpp-memory-pool
2385ad6734e224524610bbef7430ded8b28c6cb4
[ "MIT" ]
3
2017-12-01T23:58:36.000Z
2021-12-31T09:14:30.000Z
amot/amot_pool.cpp
sartrey/cpp-memory-pool
2385ad6734e224524610bbef7430ded8b28c6cb4
[ "MIT" ]
null
null
null
amot/amot_pool.cpp
sartrey/cpp-memory-pool
2385ad6734e224524610bbef7430ded8b28c6cb4
[ "MIT" ]
null
null
null
#include "amot_pool.h" #include "amot_setting.h" #include "amot_factory.h" #include "amot_block.h" namespace amot { Pool::Pool(Setting* setting) { _Setting = (setting == null ? new Setting() : setting); _MaxBlockCount = _Setting->MaxBlockCount(); _MaxBlockSize = _Setting->MaxBlockSize(); _Factory = new amot::Factory(); _Blocks = new PBlock[_MaxBlockCount]; for (uint32 i = 0; i < _MaxBlockCount; i++) _Blocks[i] = null; } Pool::~Pool() { if (_Blocks != null) { for (uint32 i = 0; i < _Setting->MaxBlockCount(); i++) if (_Blocks[i] != null) delete _Blocks[i]; delete _Blocks; } if (_Factory != null) delete _Factory; if (_Setting != null) delete _Setting; } //----- ----- ----- ----- ----- ----- PBlock Pool::Search(raw data) { for (uint32 i = 0; i < _MaxBlockCount; i++) { PBlock block = _Blocks[i]; if (block == null || !block->Enclose(data)) continue; return block; } return null; } PBlock Pool::Expand(uint32 size) { for (uint32 i = 0; i < _MaxBlockCount; i++) { if (_Blocks[i] == null) { PBlock block = _Factory->CreateBlock( _Setting->BlockType(), size); _Blocks[i] = block; return block; } } return null; } PBlock Pool::Rebuild() { PBlock block = _Factory->CreateBlock( _Setting->BlockType(), 0); _Blocks[0] = block; return block; } //----- ----- ----- ----- ----- ----- raw Pool::Allocate(uint32 size) { if (size == 0 || size > _MaxBlockSize) return null; //1st : try to allocate memory for (uint32 i = 0; i < _MaxBlockCount; i++) { PBlock block = _Blocks[i]; if (block == null) continue; raw data = block->Allocate(size); if (data != null) return data; } //2nd : try to create block PBlock block = Expand(size); if (block != null) { raw data = block->Allocate(size); if (data == null) throw amot_err1; else return data; } return null; } void Pool::Free(raw data, bool clear) { PBlock block = Search(data); if (block != null) block->Free(data, clear); } void Pool::FreeAll() { for (uint32 i = 0; i < _MaxBlockCount; i++) { PBlock block = _Blocks[i]; if (block == null) continue; delete block; _Blocks[i] = null; } Rebuild(); } raw Pool::Resize(raw data, uint32 size) { PBlock block = Search(data); if (block != null) return block->Resize(data, size); return null; } //----- ----- ----- ----- ----- ----- Factory* Pool::Factory() { return _Factory; } void Pool::Mount(PBlock block) { for (uint32 i = 0; i < _MaxBlockCount; i++) { if (_Blocks[i] == null) { _Blocks[i] = block; return; } } } void Pool::Optimize() { for (uint32 i = 0; i < _MaxBlockCount; i++) { PBlock block = _Blocks[i]; if (block == null) continue; if (block->UsedSize() == 0) { delete block; _Blocks[i] = null; } else block->Optimize(); } } }
17.76506
57
0.56765
sartrey
d050bee744dfb370e0b69dd44b32809706162c4c
3,461
cpp
C++
plan_executor/src/plan_executor_node.cpp
faranik/home_service_robot
e0f88dd7dedd80632de8c9acdf747275caece991
[ "Unlicense" ]
null
null
null
plan_executor/src/plan_executor_node.cpp
faranik/home_service_robot
e0f88dd7dedd80632de8c9acdf747275caece991
[ "Unlicense" ]
null
null
null
plan_executor/src/plan_executor_node.cpp
faranik/home_service_robot
e0f88dd7dedd80632de8c9acdf747275caece991
[ "Unlicense" ]
null
null
null
#include <ros/ros.h> #include <mover/Move.h> #include <obj_manipulator/ObjManipulation.h> class SubscribeAndPublish { public: SubscribeAndPublish() { // Register as client of mover service. moverClient = n.serviceClient<mover::Move>("/robot_mover"); // Register as client of object manipulator service. objManipulatorClient = n.serviceClient<obj_manipulator::ObjManipulation>("/object_manipulator"); } void run() { MoverRequest requestsToMove[5] = {{4.0, -2.0, 1.0}, {4.0, -1.0, 1.0}, {4.0, 0.0, 1.0}, {4.0, 1.0, 1.0}, {4.0, 2.0, 1.0}}; ObjManipulationRequest requestsToManipulate[5] = {{0, 0, 4.0, -2.0}, {1, 0, 4.0, -1.0}, {2, 0, 4.0, 0.0}, {3, 0, 4.0, 1.0}, {4, 0, 4.0, 2.0}}; // Place some objects in the environment. for(int i = 0; i < 5; ++i) { obj_manipulator::ObjManipulation manipulationSrv; manipulationSrv.request.id = requestsToManipulate[i].id; manipulationSrv.request.command = requestsToManipulate[i].command; manipulationSrv.request.x = requestsToManipulate[i].x; manipulationSrv.request.y = requestsToManipulate[i].y; if(!objManipulatorClient.call(manipulationSrv)) { ROS_WARN("Object manipulation service has some problem to place object into environment."); } } // Start collecting the objects at the same place. float delta = 0.0; for(int i = 0; i < 5; ++i) { mover::Move moverSrv; moverSrv.request.x = requestsToMove[i].x; moverSrv.request.y = requestsToMove[i].y; moverSrv.request.theta = requestsToMove[i].theta; if(!moverClient.call(moverSrv)) { continue; } // Simulate a pick up object. obj_manipulator::ObjManipulation manipulationSrv; manipulationSrv.request.id = requestsToManipulate[i].id; manipulationSrv.request.command = 1; manipulationSrv.request.x = requestsToManipulate[i].x; manipulationSrv.request.y = requestsToManipulate[i].y; if(!objManipulatorClient.call(manipulationSrv)) { continue; } moverSrv.request.x = -4.0; moverSrv.request.y = -2.0 - delta; moverSrv.request.theta = requestsToMove[i].theta; if(!moverClient.call(moverSrv)) { continue; } // Simulate a drop off object. manipulationSrv.request.id = requestsToManipulate[i].id; manipulationSrv.request.command = requestsToManipulate[i].command; manipulationSrv.request.x = -4.0; manipulationSrv.request.y = -2.0 - delta; if(!objManipulatorClient.call(manipulationSrv)) { continue; } delta += 0.3; } } private: ros::NodeHandle n; ros::ServiceClient moverClient; ros::ServiceClient objManipulatorClient; struct MoverRequest { float x; float y; float theta; }; struct ObjManipulationRequest { int id; int command; float x; float y; }; }; int main(int argc, char **argv) { //Initiate ROS ros::init(argc, argv, "plan_executor"); if(ros::ok()) { //Create an object of class SubscribeAndPublish that will take care of everything SubscribeAndPublish sapObject; sapObject.run(); ros::spin(); } return 0; }
25.262774
100
0.598093
faranik
d054ba89132f662ee477ef3ba24c3b949b9aea00
619
cpp
C++
C++/minimize-product-sum-of-two-arrays.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/minimize-product-sum-of-two-arrays.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/minimize-product-sum-of-two-arrays.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(nlogn) // Space: O(1) // Same problem from https://codingcompetitions.withgoogle.com/codejam/round/00000000004330f6/0000000000432f33 class Solution { public: int minProductSum(vector<int>& nums1, vector<int>& nums2) { sort(begin(nums1), end(nums1)); sort(begin(nums2), end(nums2), greater<int>()); return inner_product(nums1, nums2); } private: int inner_product(const vector<int>& vec1, const vector<int>& vec2) { int result = 0; for (int i = 0; i < size(vec1); ++i) { result += vec1[i] * vec2[i]; } return result; } };
28.136364
110
0.602585
Priyansh2
d05664f8155c74396e3bad5f9d446f7cb3482518
3,476
cpp
C++
raygun/window.cpp
maggo007/Raygun
f6be537c835976a9d6cc356ebe187feba6592847
[ "MIT" ]
null
null
null
raygun/window.cpp
maggo007/Raygun
f6be537c835976a9d6cc356ebe187feba6592847
[ "MIT" ]
null
null
null
raygun/window.cpp
maggo007/Raygun
f6be537c835976a9d6cc356ebe187feba6592847
[ "MIT" ]
null
null
null
// The MIT License (MIT) // // Copyright (c) 2019,2020 The Raygun Authors. // // 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 "raygun/window.hpp" #include "raygun/config.hpp" #include "raygun/gpu/gpu_utils.hpp" #include "raygun/logging.hpp" #include "raygun/raygun.hpp" namespace raygun { Window::Window(string_view title) { const auto& config = RG().config(); int width = config.width; int height = config.height; auto monitor = glfwGetPrimaryMonitor(); auto mode = glfwGetVideoMode(monitor); switch(config.fullscreen) { case Config::Fullscreen::Fullscreen: break; case Config::Fullscreen::Borderless: width = mode->width; height = mode->height; glfwWindowHint(GLFW_AUTO_ICONIFY, GLFW_FALSE); glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); [[fallthrough]]; case Config::Fullscreen::Window: monitor = nullptr; break; } #ifdef _WIN32 // HACK: see https://github.com/glfw/glfw/issues/527 if(config.fullscreen == Config::Fullscreen::Borderless) { height++; } #endif glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); glfwWindowHint(GLFW_RED_BITS, mode->redBits); glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); m_window = glfwCreateWindow(width, height, title.data(), monitor, nullptr); if(m_window) { RAYGUN_INFO("Window initialized"); } else { RAYGUN_FATAL("Unable to initialize window"); } glfwSetWindowIcon(m_window, 1, &m_windowIcon.image); } Window::~Window() { glfwDestroyWindow(m_window); } vk::Extent2D Window::size() const { int w = 0, h = 0; glfwGetFramebufferSize(m_window, &w, &h); return {(uint32_t)w, (uint32_t)h}; } bool Window::minimized() const { return glfwGetWindowAttrib(m_window, GLFW_ICONIFIED); } vk::UniqueSurfaceKHR Window::createSurface(const vk::Instance& instance) const { VkSurfaceKHR surface; const auto result = glfwCreateWindowSurface(instance, m_window, nullptr, &surface); if(result != VK_SUCCESS) { RAYGUN_FATAL("Unable to create window surface: {}", glfwGetError(nullptr)); } return gpu::wrapUnique<vk::SurfaceKHR>(surface, instance); } void Window::handleEvents() { if(glfwWindowShouldClose(m_window)) { RG().quit(); } } } // namespace raygun
29.210084
87
0.70397
maggo007
d058b71a6258272b18705f1098ca96bc45d3dda2
2,839
cc
C++
src/arch/os2/fonts/bdf2fnt.cc
swingflip/C64_mini_VICE
7a6d9d41ae60409a2bb985bb8d6324a7269a0daa
[ "Apache-2.0" ]
2
2018-11-15T19:52:34.000Z
2022-01-17T19:45:01.000Z
src/arch/os2/fonts/bdf2fnt.cc
Classicmods/C64_mini_VICE
7a6d9d41ae60409a2bb985bb8d6324a7269a0daa
[ "Apache-2.0" ]
null
null
null
src/arch/os2/fonts/bdf2fnt.cc
Classicmods/C64_mini_VICE
7a6d9d41ae60409a2bb985bb8d6324a7269a0daa
[ "Apache-2.0" ]
3
2019-06-30T05:37:04.000Z
2021-12-04T17:12:35.000Z
#include <iostream.h> #include <fstream.h> #include <stdio.h> #include <string.h> #include <stdlib.h> /************************************************************** * * To create a header file: * create a font, with: * - fixed size * - width & height = 8 * - no empty characters * **************************************************************/ int CopyHeader(ofstream &fout) { ifstream fin("header.fnt", ios::binary); if (!fin) { cout << "File 'header.fnt' not found." << endl; return 1; } // header contains 1758 bytes const int len = 27 * 64 + 30; char c[len]; fin.read(c, len); fout.write(c, len); fout << flush; return 0; } int ReadBdf(char font[256][8]) { FILE *in = fopen("vice-cbm.bdf", "r"); if (!in) { cout << "File 'vice-cbm.bdf' not found." << endl; return 1; } int enc = 0; int charn = 0; int line = 0; char str[1024]; int h, dx, dy; while (!feof(in) && fscanf(in, "%s", str)) { if (!strcmp(str, "ENDFONT")) break; switch (enc) { case 0: if (!strcmp(str,"ENCODING")) { enc = 1; } break; case 1: charn = atoi(str); cout << charn << " "; enc = 2; break; case 2: if (!strcmp(str,"BBX")) { enc = 3; } break; case 3: enc = 4; break; case 4: h = atoi(str); enc = 5; break; case 5: dx = atoi(str); enc = 6; break; case 6: dy = atoi(str); enc = 7; break; case 7: if (!strcmp(str, "BITMAP")) { enc = 8; } break; case 8: if (!strcmp(str,"ENDCHAR")) { line = 0; enc = 0; } else { char *c; font[charn][8 - h - dy + line++] = strtol(str, &c, 16) >> dx; } break; } } fclose(in); return 0; } int main() { ofstream fout("vice-cbm.fnt", ios::binary); if (CopyHeader(fout)) { return 0; } char font[256][8]; if (ReadBdf(font)) { return 0; } for (int i = 0; i < 256; i++) { for (int j = 0; j < 8; j++) { fout << font[i][j]; } } fout << '\xff'; fout << '\xff'; fout << '\xff'; fout << '\xff'; fout << '\x08'; fout << '\0'; fout << '\0'; fout << '\0' << flush; }
21.02963
81
0.349771
swingflip
d05cb25d6fb6975e8a03a636d9fc58438d662120
5,298
cpp
C++
src/popnode-payments.cpp
POPChainFoundation/PopChain-Original
a99f5fbdf6ca96a281491482530c20a4c5915492
[ "MIT" ]
20
2018-04-28T06:38:05.000Z
2018-07-28T04:44:42.000Z
src/popnode-payments.cpp
POPChainFoundation/PopChain-Original
a99f5fbdf6ca96a281491482530c20a4c5915492
[ "MIT" ]
2
2018-05-15T15:14:36.000Z
2018-05-18T00:51:48.000Z
src/popnode-payments.cpp
POPChainFoundation/PopChain-Original
a99f5fbdf6ca96a281491482530c20a4c5915492
[ "MIT" ]
7
2018-05-15T12:28:19.000Z
2018-08-23T04:59:39.000Z
// Copyright (c) 2017-2018 The Popchain Core Developers #include "activepopnode.h" #include "popsend.h" #include "superblock.h" #include "popnode-payments.h" #include "popnode-sync.h" #include "popnodeman.h" #include "netfulfilledman.h" #include "fork.h" #include "util.h" #include <boost/lexical_cast.hpp> // Popchain DevTeam bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockReward, std::string &strErrorRet) { strErrorRet = ""; bool isBlockRewardValueMet = (block.vtx[0].GetValueOut() <= blockReward); if(fDebug) LogPrintf("block.vtx[0].GetValueOut() %lld <= blockReward %lld\n", block.vtx[0].GetValueOut(), blockReward); const Consensus::Params& consensusParams = Params().GetConsensus(); if(nBlockHeight < consensusParams.nSuperblockStartBlock) { if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d)", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } return isBlockRewardValueMet; } // superblocks started CAmount nSuperblockMaxValue = CSuperblock::GetPaymentsLimit(nBlockHeight); bool isSuperblockMaxValueMet = (block.vtx[0].GetValueOut() <= nSuperblockMaxValue); if(CSuperblock::IsValidBlockHeight(nBlockHeight)) { if(CSuperblock::IsFounderValid( block.vtx[0], nBlockHeight, blockReward )==false) { return false; } } LogPrint("gobject", "block.vtx[0].GetValueOut() %lld <= nSuperblockMaxValue %lld\n", block.vtx[0].GetValueOut(), nSuperblockMaxValue); if(!popnodeSync.IsSynced()) { // not enough data but at least it must NOT exceed superblock max value if(CSuperblock::IsValidBlockHeight(nBlockHeight)) { if(fDebug) LogPrintf("IsBlockPayeeValid -- WARNING: Client not synced, checking superblock max bounds only\n"); if(!isSuperblockMaxValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded superblock max value", nBlockHeight, block.vtx[0].GetValueOut(), nSuperblockMaxValue); } return isSuperblockMaxValueMet; } if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, only regular blocks are allowed at this height", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } // it MUST be a regular block otherwise return isBlockRewardValueMet; } // we are synced, let's try to check as much data as we can if(forkManager.IsForkActive(FORK_9_SUPERBLOCKS_ENABLED)) { LogPrint("gobject", "IsBlockValueValid -- No triggered superblock detected at height %d\n", nBlockHeight); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, no triggered superblock detected", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } } else { // should NOT allow superblocks at all, when superblocks are disabled LogPrint("gobject", "IsBlockValueValid -- Superblocks are disabled, no superblocks allowed\n"); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, superblocks are disabled", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } } // it MUST be a regular block return isBlockRewardValueMet; } // Popchain DevTeam bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward) { if(!popnodeSync.IsSynced()) { if(fDebug) LogPrintf("IsBlockPayeeValid -- WARNING: Client not synced, skipping block payee checks\n"); return true; } const Consensus::Params& consensusParams = Params().GetConsensus(); if(nBlockHeight < consensusParams.nSuperblockStartBlock) { return true; } // superblocks started // SEE IF THIS IS A VALID SUPERBLOCK if(forkManager.IsForkActive(FORK_9_SUPERBLOCKS_ENABLED)) { LogPrint("gobject", "IsBlockPayeeValid -- No triggered superblock detected at height %d\n", nBlockHeight); } else { // should NOT allow superblocks at all, when superblocks are disabled LogPrint("gobject", "IsBlockPayeeValid -- Superblocks are disabled, no superblocks allowed\n"); } return true; } // Popchain DevTeam void FillBlockPayments(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutFound) { // only create superblocks if fork is enabled AND if superblock is actually triggered // (height should be validated inside) if(forkManager.IsForkActive(FORK_9_SUPERBLOCKS_ENABLED) && CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { LogPrintf("FillBlockPayments -- triggered superblock creation at height %d\n", nBlockHeight); CSuperblockManager::CreateSuperblock(txNew, nBlockHeight, txoutFound); return; } }
42.725806
169
0.671763
POPChainFoundation
d0602212038a7f84a9d844517c89923af79b09d2
653
cpp
C++
leetcode/problems/easy/171-excel-sheet-column-number.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/easy/171-excel-sheet-column-number.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/easy/171-excel-sheet-column-number.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Excel Sheet Column Number Given a column title as appear in an Excel sheet, return its corresponding column number. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... Example 1: Input: "A" Output: 1 Example 2: Input: "AB" Output: 28 Example 3: Input: "ZY" Output: 701 Constraints: 1 <= s.length <= 7 s consists only of uppercase English letters. s is between "A" and "FXSHRXW". */ class Solution { public: int titleToNumber(string columnTitle) { int ans = 0, n = columnTitle.size(); for(auto x : columnTitle) ans = ans * 26 + (x - 'A' + 1); return ans; } };
14.840909
89
0.586524
wingkwong
d065e7190a94e25235fdc4c1eed0d6899d3398ef
624
cpp
C++
functions/tests/test_matrix_polynomial.cpp
GuylainGreer/manifolds
96f996f67fc523c726f2edbc9705125c212bedae
[ "MIT" ]
null
null
null
functions/tests/test_matrix_polynomial.cpp
GuylainGreer/manifolds
96f996f67fc523c726f2edbc9705125c212bedae
[ "MIT" ]
null
null
null
functions/tests/test_matrix_polynomial.cpp
GuylainGreer/manifolds
96f996f67fc523c726f2edbc9705125c212bedae
[ "MIT" ]
null
null
null
#include "functions/integral_polynomial.hh" #include "functions/polynomial.hh" #include "functions/operators.hh" #include <boost/test/unit_test.hpp> #include <complex> #include "functions/std_functions.hh" #include "functions/all_simplifications.hh" #include "data/matrix.hh" BOOST_AUTO_TEST_CASE(matrix_polynomial_test) { using namespace manifolds; auto m = GetMatrix<2, 2>(1.0, 0.0, 0.0, 1.0); auto p = GetPolynomial(m, m * 2); BOOST_CHECK_EQUAL(p(2), 5 * m); BOOST_CHECK_EQUAL(p(m), 3 * m); auto p2 = p * p + 2_c * p; auto p2_check = GetPolynomial(3 * m, 8 * m, 4 * m); BOOST_CHECK(p2 == p2_check); }
27.130435
53
0.700321
GuylainGreer
d0695d8829baa159a8e0ee1176b9b1e7e50ee294
16,093
cpp
C++
ie/src/v20200304/model/VideoInfo.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
ie/src/v20200304/model/VideoInfo.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
ie/src/v20200304/model/VideoInfo.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/ie/v20200304/model/VideoInfo.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Ie::V20200304::Model; using namespace std; VideoInfo::VideoInfo() : m_fpsHasBeenSet(false), m_widthHasBeenSet(false), m_heightHasBeenSet(false), m_longSideHasBeenSet(false), m_shortSideHasBeenSet(false), m_bitrateHasBeenSet(false), m_gopHasBeenSet(false), m_videoCodecHasBeenSet(false), m_picMarkInfoHasBeenSet(false), m_darInfoHasBeenSet(false), m_hdrHasBeenSet(false), m_videoEnhanceHasBeenSet(false), m_hiddenMarkInfoHasBeenSet(false), m_textMarkInfoHasBeenSet(false) { } CoreInternalOutcome VideoInfo::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Fps") && !value["Fps"].IsNull()) { if (!value["Fps"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `VideoInfo.Fps` IsInt64=false incorrectly").SetRequestId(requestId)); } m_fps = value["Fps"].GetInt64(); m_fpsHasBeenSet = true; } if (value.HasMember("Width") && !value["Width"].IsNull()) { if (!value["Width"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `VideoInfo.Width` IsInt64=false incorrectly").SetRequestId(requestId)); } m_width = value["Width"].GetInt64(); m_widthHasBeenSet = true; } if (value.HasMember("Height") && !value["Height"].IsNull()) { if (!value["Height"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `VideoInfo.Height` IsInt64=false incorrectly").SetRequestId(requestId)); } m_height = value["Height"].GetInt64(); m_heightHasBeenSet = true; } if (value.HasMember("LongSide") && !value["LongSide"].IsNull()) { if (!value["LongSide"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `VideoInfo.LongSide` IsInt64=false incorrectly").SetRequestId(requestId)); } m_longSide = value["LongSide"].GetInt64(); m_longSideHasBeenSet = true; } if (value.HasMember("ShortSide") && !value["ShortSide"].IsNull()) { if (!value["ShortSide"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `VideoInfo.ShortSide` IsInt64=false incorrectly").SetRequestId(requestId)); } m_shortSide = value["ShortSide"].GetInt64(); m_shortSideHasBeenSet = true; } if (value.HasMember("Bitrate") && !value["Bitrate"].IsNull()) { if (!value["Bitrate"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `VideoInfo.Bitrate` IsInt64=false incorrectly").SetRequestId(requestId)); } m_bitrate = value["Bitrate"].GetInt64(); m_bitrateHasBeenSet = true; } if (value.HasMember("Gop") && !value["Gop"].IsNull()) { if (!value["Gop"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `VideoInfo.Gop` IsInt64=false incorrectly").SetRequestId(requestId)); } m_gop = value["Gop"].GetInt64(); m_gopHasBeenSet = true; } if (value.HasMember("VideoCodec") && !value["VideoCodec"].IsNull()) { if (!value["VideoCodec"].IsString()) { return CoreInternalOutcome(Core::Error("response `VideoInfo.VideoCodec` IsString=false incorrectly").SetRequestId(requestId)); } m_videoCodec = string(value["VideoCodec"].GetString()); m_videoCodecHasBeenSet = true; } if (value.HasMember("PicMarkInfo") && !value["PicMarkInfo"].IsNull()) { if (!value["PicMarkInfo"].IsArray()) return CoreInternalOutcome(Core::Error("response `VideoInfo.PicMarkInfo` is not array type")); const rapidjson::Value &tmpValue = value["PicMarkInfo"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { PicMarkInfoItem item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_picMarkInfo.push_back(item); } m_picMarkInfoHasBeenSet = true; } if (value.HasMember("DarInfo") && !value["DarInfo"].IsNull()) { if (!value["DarInfo"].IsObject()) { return CoreInternalOutcome(Core::Error("response `VideoInfo.DarInfo` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_darInfo.Deserialize(value["DarInfo"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_darInfoHasBeenSet = true; } if (value.HasMember("Hdr") && !value["Hdr"].IsNull()) { if (!value["Hdr"].IsString()) { return CoreInternalOutcome(Core::Error("response `VideoInfo.Hdr` IsString=false incorrectly").SetRequestId(requestId)); } m_hdr = string(value["Hdr"].GetString()); m_hdrHasBeenSet = true; } if (value.HasMember("VideoEnhance") && !value["VideoEnhance"].IsNull()) { if (!value["VideoEnhance"].IsObject()) { return CoreInternalOutcome(Core::Error("response `VideoInfo.VideoEnhance` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_videoEnhance.Deserialize(value["VideoEnhance"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_videoEnhanceHasBeenSet = true; } if (value.HasMember("HiddenMarkInfo") && !value["HiddenMarkInfo"].IsNull()) { if (!value["HiddenMarkInfo"].IsObject()) { return CoreInternalOutcome(Core::Error("response `VideoInfo.HiddenMarkInfo` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_hiddenMarkInfo.Deserialize(value["HiddenMarkInfo"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_hiddenMarkInfoHasBeenSet = true; } if (value.HasMember("TextMarkInfo") && !value["TextMarkInfo"].IsNull()) { if (!value["TextMarkInfo"].IsArray()) return CoreInternalOutcome(Core::Error("response `VideoInfo.TextMarkInfo` is not array type")); const rapidjson::Value &tmpValue = value["TextMarkInfo"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { TextMarkInfoItem item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_textMarkInfo.push_back(item); } m_textMarkInfoHasBeenSet = true; } return CoreInternalOutcome(true); } void VideoInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { 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_widthHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Width"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_width, 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_longSideHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "LongSide"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_longSide, allocator); } if (m_shortSideHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ShortSide"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_shortSide, allocator); } 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_gopHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Gop"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_gop, allocator); } if (m_videoCodecHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "VideoCodec"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_videoCodec.c_str(), allocator).Move(), allocator); } if (m_picMarkInfoHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PicMarkInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_picMarkInfo.begin(); itr != m_picMarkInfo.end(); ++itr, ++i) { value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } if (m_darInfoHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DarInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_darInfo.ToJsonObject(value[key.c_str()], allocator); } if (m_hdrHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Hdr"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_hdr.c_str(), allocator).Move(), allocator); } if (m_videoEnhanceHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "VideoEnhance"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_videoEnhance.ToJsonObject(value[key.c_str()], allocator); } if (m_hiddenMarkInfoHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "HiddenMarkInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_hiddenMarkInfo.ToJsonObject(value[key.c_str()], allocator); } if (m_textMarkInfoHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TextMarkInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_textMarkInfo.begin(); itr != m_textMarkInfo.end(); ++itr, ++i) { value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } } int64_t VideoInfo::GetFps() const { return m_fps; } void VideoInfo::SetFps(const int64_t& _fps) { m_fps = _fps; m_fpsHasBeenSet = true; } bool VideoInfo::FpsHasBeenSet() const { return m_fpsHasBeenSet; } int64_t VideoInfo::GetWidth() const { return m_width; } void VideoInfo::SetWidth(const int64_t& _width) { m_width = _width; m_widthHasBeenSet = true; } bool VideoInfo::WidthHasBeenSet() const { return m_widthHasBeenSet; } int64_t VideoInfo::GetHeight() const { return m_height; } void VideoInfo::SetHeight(const int64_t& _height) { m_height = _height; m_heightHasBeenSet = true; } bool VideoInfo::HeightHasBeenSet() const { return m_heightHasBeenSet; } int64_t VideoInfo::GetLongSide() const { return m_longSide; } void VideoInfo::SetLongSide(const int64_t& _longSide) { m_longSide = _longSide; m_longSideHasBeenSet = true; } bool VideoInfo::LongSideHasBeenSet() const { return m_longSideHasBeenSet; } int64_t VideoInfo::GetShortSide() const { return m_shortSide; } void VideoInfo::SetShortSide(const int64_t& _shortSide) { m_shortSide = _shortSide; m_shortSideHasBeenSet = true; } bool VideoInfo::ShortSideHasBeenSet() const { return m_shortSideHasBeenSet; } int64_t VideoInfo::GetBitrate() const { return m_bitrate; } void VideoInfo::SetBitrate(const int64_t& _bitrate) { m_bitrate = _bitrate; m_bitrateHasBeenSet = true; } bool VideoInfo::BitrateHasBeenSet() const { return m_bitrateHasBeenSet; } int64_t VideoInfo::GetGop() const { return m_gop; } void VideoInfo::SetGop(const int64_t& _gop) { m_gop = _gop; m_gopHasBeenSet = true; } bool VideoInfo::GopHasBeenSet() const { return m_gopHasBeenSet; } string VideoInfo::GetVideoCodec() const { return m_videoCodec; } void VideoInfo::SetVideoCodec(const string& _videoCodec) { m_videoCodec = _videoCodec; m_videoCodecHasBeenSet = true; } bool VideoInfo::VideoCodecHasBeenSet() const { return m_videoCodecHasBeenSet; } vector<PicMarkInfoItem> VideoInfo::GetPicMarkInfo() const { return m_picMarkInfo; } void VideoInfo::SetPicMarkInfo(const vector<PicMarkInfoItem>& _picMarkInfo) { m_picMarkInfo = _picMarkInfo; m_picMarkInfoHasBeenSet = true; } bool VideoInfo::PicMarkInfoHasBeenSet() const { return m_picMarkInfoHasBeenSet; } DarInfo VideoInfo::GetDarInfo() const { return m_darInfo; } void VideoInfo::SetDarInfo(const DarInfo& _darInfo) { m_darInfo = _darInfo; m_darInfoHasBeenSet = true; } bool VideoInfo::DarInfoHasBeenSet() const { return m_darInfoHasBeenSet; } string VideoInfo::GetHdr() const { return m_hdr; } void VideoInfo::SetHdr(const string& _hdr) { m_hdr = _hdr; m_hdrHasBeenSet = true; } bool VideoInfo::HdrHasBeenSet() const { return m_hdrHasBeenSet; } VideoEnhance VideoInfo::GetVideoEnhance() const { return m_videoEnhance; } void VideoInfo::SetVideoEnhance(const VideoEnhance& _videoEnhance) { m_videoEnhance = _videoEnhance; m_videoEnhanceHasBeenSet = true; } bool VideoInfo::VideoEnhanceHasBeenSet() const { return m_videoEnhanceHasBeenSet; } HiddenMarkInfo VideoInfo::GetHiddenMarkInfo() const { return m_hiddenMarkInfo; } void VideoInfo::SetHiddenMarkInfo(const HiddenMarkInfo& _hiddenMarkInfo) { m_hiddenMarkInfo = _hiddenMarkInfo; m_hiddenMarkInfoHasBeenSet = true; } bool VideoInfo::HiddenMarkInfoHasBeenSet() const { return m_hiddenMarkInfoHasBeenSet; } vector<TextMarkInfoItem> VideoInfo::GetTextMarkInfo() const { return m_textMarkInfo; } void VideoInfo::SetTextMarkInfo(const vector<TextMarkInfoItem>& _textMarkInfo) { m_textMarkInfo = _textMarkInfo; m_textMarkInfoHasBeenSet = true; } bool VideoInfo::TextMarkInfoHasBeenSet() const { return m_textMarkInfoHasBeenSet; }
27.276271
138
0.650531
suluner
d06a32013ce8c96441c19e00767beda7a8842d24
4,461
hpp
C++
library/L1_Peripheral/can.hpp
WilliamMajor/SJSU-Dev2
8c9f0a0791448d0f6b7ce161e597cf41ca3119a0
[ "Apache-2.0" ]
null
null
null
library/L1_Peripheral/can.hpp
WilliamMajor/SJSU-Dev2
8c9f0a0791448d0f6b7ce161e597cf41ca3119a0
[ "Apache-2.0" ]
null
null
null
library/L1_Peripheral/can.hpp
WilliamMajor/SJSU-Dev2
8c9f0a0791448d0f6b7ce161e597cf41ca3119a0
[ "Apache-2.0" ]
null
null
null
#pragma once #include <algorithm> #include <array> #include <cstddef> #include <cstdint> #include <initializer_list> #include <span> #include "module.hpp" #include "utility/error_handling.hpp" namespace sjsu { /// The common interface for the CANBUS peripherals. /// @ingroup l1_peripheral class Can : public Module { public: // =========================================================================== // Interface Defintions // =========================================================================== /// This struct represents a transmit message based on the BOSCH CAN /// spec 2.0B. struct Message_t { /// The format of the can message enum class Format { /// Use 11-bit ID message kStandard = 0, /// Use 29-bit ID message kExtended = 1, kNumberOfFormats, }; /// CAN message ID uint32_t id; /// Length of the payload uint8_t length = 0; /// Container of the payload contents std::array<uint8_t, 8> payload; /// ID format Format format = Format::kStandard; /// Is this message a remote request message. If so the contents of payload /// are ignored. Length shall have the length of requested data to get back /// from the device responsible for message id. bool is_remote_request = false; void SetPayload(std::span<const uint8_t> data) { std::copy_n( data.begin(), std::min(payload.size(), data.size()), payload.begin()); } }; /// Standard baud rate for most CANBUS networks static constexpr units::frequency::hertz_t kStandardBaudRate = 100'000_Hz; // =========================================================================== // Interface Methods // =========================================================================== // --------------------------------------------------------------------------- // Configuration Methods // --------------------------------------------------------------------------- /// @param baud - baud rate to configure the CANBUS to virtual void ConfigureBaudRate( units::frequency::hertz_t baud = kStandardBaudRate) = 0; // --------------------------------------------------------------------------- // Usage Methods // --------------------------------------------------------------------------- /// Send a message via CANBUS to the designated device with the supplied ID /// /// @param message - Message containing the CANBUS contents. virtual void Send(const Message_t & message) = 0; /// Receive data via CANBUS /// /// @return retrieved can message. Will return with length field = 0 if no /// messages exist. virtual Message_t Receive() = 0; /// Checks if there is a message available for this channel. /// /// @returns true a message was received. virtual bool HasData() = 0; /// Determine if you can communicate over the bus. /// /// @param id - device you want to ping to determine if you can communicate on /// the bus. /// @return true - on success /// @return false - on failure virtual bool SelfTest(uint32_t id) = 0; /// @return true - if the device is "bus Off" /// @return false - if the device is NOT "bus off" virtual bool IsBusOff() = 0; // =========================================================================== // Utility Methods // =========================================================================== /// Send a message via CANBUS to the designated device with the supplied ID /// /// @param id - ID to send the data to. /// @param payload - array literal payload to send to the device with ID /// @return true - on success /// @return false - on failure void Send(uint32_t id, std::initializer_list<uint8_t> payload) { Message_t message; message.id = id; message.length = static_cast<uint8_t>(payload.size()); message.SetPayload(payload); return Send(message); } /// Send a message via CANBUS to the designated device with the supplied ID /// /// @param id - ID to send the data to. /// @param payload - uint8_t span payload to send to the device with ID /// @return true - on success /// @return false - on failure void Send(uint32_t id, std::span<const uint8_t> payload) { Message_t message; message.id = id; message.length = static_cast<uint8_t>(payload.size()); message.SetPayload(payload); return Send(message); } }; } // namespace sjsu
30.979167
80
0.541134
WilliamMajor
d06e64e56865d0d82cde4d50ad23a0a47a38fe24
2,327
cpp
C++
src/loop053.cpp
TannerRogalsky/Demoloops
13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5
[ "MIT" ]
4
2016-11-07T12:50:14.000Z
2020-04-30T19:48:05.000Z
src/loop053.cpp
TannerRogalsky/Demoloops
13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5
[ "MIT" ]
1
2017-04-17T12:00:16.000Z
2017-04-17T12:00:16.000Z
src/loop053.cpp
TannerRogalsky/Demoloops
13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5
[ "MIT" ]
null
null
null
#include "demoloop.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/rotate_vector.hpp> #include "graphics/shader.h" using namespace std; using namespace demoloop; const uint32_t CYCLE_LENGTH = 10; const static std::string shaderCode = R"===( uniform mediump float cycle_ratio; #define DEMOLOOP_M_PI 3.14159265359 #define DEMOLOOP_TWO_PI 6.28318530718 #ifdef VERTEX vec4 position(mat4 transform_proj, mat4 model, vec4 vertpos) { return transform_proj * model * vertpos; } #endif #ifdef PIXEL vec3 hsv2rgb(vec3 c) { vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); } float polygon(vec2 st, float numVertices) { // st.x += cos(cycle_ratio * DEMOLOOP_TWO_PI); // st.y += sin(cycle_ratio * DEMOLOOP_TWO_PI); // Angle and radius from the current pixel // float a = atan(st.x - cos(cycle_ratio * DEMOLOOP_TWO_PI) * 2.0, st.y + sin(cycle_ratio * DEMOLOOP_TWO_PI) * 2.0)+DEMOLOOP_M_PI; float r = DEMOLOOP_TWO_PI / float(numVertices); float a = atan(st.x, st.y) + DEMOLOOP_M_PI + cycle_ratio * r; // Shaping function that modulate the distance // float d = cos(floor(a/r)*r-a)*length(st); float c = 0.0; float d = cos( (fract(a/r)-c)*r) * length(st); return d; } vec4 effect(vec4 color, Image texture, vec2 st, vec2 screen_coords) { float t = cycle_ratio; vec3 c = vec3(0.0); float d = 0.0; // Remap the space to -1. to 1. st = st * 2. - 1.; st.x *= demoloop_ScreenSize.x/demoloop_ScreenSize.y; d = polygon(st, 5.0); float f = mod(fract(d * 7.0) + cycle_ratio * 2.0, 1.0); d = smoothstep(0.0, f, d); // c = vec3(d); c = hsv2rgb(vec3(mod(d + t + (1.0 - length(st) / 4.0), 1.0), 1.0, 0.9)); c = mix(c, vec3(0, 0, 0), dot(st, st) * 0.15); return vec4(c,1.0); } #endif )==="; class Geometric : public Demoloop { public: Geometric() : Demoloop(CYCLE_LENGTH, 150, 150, 150), shader({shaderCode, shaderCode}) { } void Update() { const float cycle_ratio = getCycleRatio(); shader.attach(); shader.sendFloat("cycle_ratio", 1, &cycle_ratio, 1); renderTexture(gl.getDefaultTexture(), 0, 0, width, height); shader.detach(); } private: Shader shader; }; int main(int, char**){ Geometric test; test.Run(); return 0; }
24.494737
132
0.647185
TannerRogalsky
d072bf8e980a2e0ac029242b4a64e4fb5df6e8ee
5,214
cc
C++
src/lib/dhcpsrv/logging.cc
sebschrader/debian-pkg-isc-kea
1bdb18f90c48dd9674374fb8454d0efb846656bc
[ "Apache-2.0" ]
1
2017-08-24T19:55:21.000Z
2017-08-24T19:55:21.000Z
src/lib/dhcpsrv/logging.cc
sebschrader/debian-pkg-isc-kea
1bdb18f90c48dd9674374fb8454d0efb846656bc
[ "Apache-2.0" ]
null
null
null
src/lib/dhcpsrv/logging.cc
sebschrader/debian-pkg-isc-kea
1bdb18f90c48dd9674374fb8454d0efb846656bc
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2014-2015 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <cc/data.h> #include <dhcpsrv/logging.h> #include <boost/foreach.hpp> #include <boost/lexical_cast.hpp> #include <log/logger_specification.h> #include <log/logger_support.h> #include <log/logger_manager.h> #include <log/logger_name.h> using namespace isc::data; using namespace isc::log; namespace isc { namespace dhcp { LogConfigParser::LogConfigParser(const SrvConfigPtr& storage) :config_(storage), verbose_(false) { if (!storage) { isc_throw(BadValue, "LogConfigParser needs a pointer to the " "configuration, so parsed data can be stored there"); } } void LogConfigParser::parseConfiguration(const isc::data::ConstElementPtr& loggers, bool verbose) { verbose_ = verbose; // Iterate over all entries in "Logging/loggers" list BOOST_FOREACH(ConstElementPtr logger, loggers->listValue()) { parseConfigEntry(logger); } } void LogConfigParser::parseConfigEntry(isc::data::ConstElementPtr entry) { if (!entry) { // This should not happen, but let's be on the safe side and check return; } if (!config_) { isc_throw(BadValue, "configuration storage not set, can't parse logger config."); } LoggingInfo info; // Remove default destinations as we are going to replace them. info.clearDestinations(); // Get a name isc::data::ConstElementPtr name_ptr = entry->get("name"); if (!name_ptr) { isc_throw(BadValue, "loggers entry does not have a mandatory 'name' " "element (" << entry->getPosition() << ")"); } info.name_ = name_ptr->stringValue(); // Get severity isc::data::ConstElementPtr severity_ptr = entry->get("severity"); if (!name_ptr) { isc_throw(BadValue, "loggers entry does not have a mandatory " "'severity' element (" << entry->getPosition() << ")"); } try { info.severity_ = isc::log::getSeverity(severity_ptr->stringValue().c_str()); } catch (const std::exception&) { isc_throw(BadValue, "Unsupported severity value '" << severity_ptr->stringValue() << "' (" << severity_ptr->getPosition() << ")"); } // Get debug logging level info.debuglevel_ = 0; isc::data::ConstElementPtr debuglevel_ptr = entry->get("debuglevel"); // It's ok to not have debuglevel, we'll just assume its least verbose // (0) level. if (debuglevel_ptr) { try { info.debuglevel_ = boost::lexical_cast<int>(debuglevel_ptr->str()); if ( (info.debuglevel_ < 0) || (info.debuglevel_ > 99) ) { // Comment doesn't matter, it is caught several lines below isc_throw(BadValue, ""); } } catch (...) { isc_throw(BadValue, "Unsupported debuglevel value '" << debuglevel_ptr->stringValue() << "', expected 0-99 (" << debuglevel_ptr->getPosition() << ")"); } } // We want to follow the normal path, so it could catch parsing errors even // when verbose mode is enabled. If it is, just override whatever was parsed // in the config file. if (verbose_) { info.severity_ = isc::log::DEBUG; info.debuglevel_ = 99; } isc::data::ConstElementPtr output_options = entry->get("output_options"); if (output_options) { parseOutputOptions(info.destinations_, output_options); } config_->addLoggingInfo(info); } void LogConfigParser::parseOutputOptions(std::vector<LoggingDestination>& destination, isc::data::ConstElementPtr output_options) { if (!output_options) { isc_throw(BadValue, "Missing 'output_options' structure in 'loggers'"); } BOOST_FOREACH(ConstElementPtr output_option, output_options->listValue()) { LoggingDestination dest; isc::data::ConstElementPtr output = output_option->get("output"); if (!output) { isc_throw(BadValue, "output_options entry does not have a mandatory 'output' " "element (" << output_option->getPosition() << ")"); } dest.output_ = output->stringValue(); isc::data::ConstElementPtr maxver_ptr = output_option->get("maxver"); if (maxver_ptr) { dest.maxver_ = boost::lexical_cast<int>(maxver_ptr->str()); } isc::data::ConstElementPtr maxsize_ptr = output_option->get("maxsize"); if (maxsize_ptr) { dest.maxsize_ = boost::lexical_cast<uint64_t>(maxsize_ptr->str()); } isc::data::ConstElementPtr flush_ptr = output_option->get("flush"); if (flush_ptr) { dest.flush_ = flush_ptr->boolValue(); } destination.push_back(dest); } } } // namespace isc::dhcp } // namespace isc
34.078431
90
0.614308
sebschrader
4edc0a48fc07cea0a6389c1b9d6a866cc57a209b
10,801
hh
C++
src/FractalStruct/misc_class.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/FractalStruct/misc_class.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/FractalStruct/misc_class.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
#ifndef _Misc_Defined_ #define _Misc_Defined_ #include <vector> #include <fstream> namespace FractalSpace { class Misc { bool debug; public: Group* p_group_0; int zoom; int grid_multiply; static int dim0; static int dim1; static int dim2; Misc() { assert(this); debug=false; } ~Misc() { } bool get_debug() const; void set_debug(bool& d); static int coordinate(std::vector <int>& pos,std::vector <int>& Box,int spacing) { int nx=pos[0]-Box[0]; int ny=pos[1]-Box[2]; int nz=pos[2]-Box[4]; int nxt=(Box[1]-Box[0]+1)/spacing; int nyt=(Box[3]-Box[2]+1)/spacing; return (nx+nxt*(ny+nz*nyt))/spacing; } template <class T> void plus(const std::vector <T>& vin,T addit,std::vector <T>& vout) { vout=vin; plus(vout,addit); } template <class T> static void plus(std::vector <T>& vect,T add) { for(auto &v : vect) v+=add; } template <class T> static void times(const std::vector <T>& vin,const T mult,std::vector <T>& vout) { vout=vin; times(vout,mult); } template <class T> static void times(std::vector <T>& vect,const T mult) { for(auto &v : vect) v*=mult; } template <class T> static void divide(const std::vector <T>& vin,const T divisor,std::vector <T>& vout) { vout=vin; divide(vout,divisor); } template <class T> static void divide(std::vector <T>& vect,const T divisor) { for(auto &v : vect) v/=divisor; } template <class T> static T nr(const T& i,const T& j,const T& k, const T&m) { return i+(j+k*m)*m; } static int pow(const int&x,const int& y) { assert(y >= 0); int i=1; for(int ii=0;ii < y;++ii) i*=x; return i; } template <class T> static T pow2(const T& x) { return x*x; } template <class T> static T pow3(const T& x) { return x*x*x; } template <class T> static void add_dens(std::vector <T>& dens,const T& dm, T& d_x, T& d_y, T& d_z) { // assert(abs(d_x-0.5) <= 0.5); // assert(abs(d_y-0.5) <= 0.5); // assert(abs(d_z-0.5) <= 0.5); if(abs(d_x-0.5) >= 0.5) { std::cout << "dx error " << abs(d_x-0.5)-0.5 << "\n"; if(d_x > 1.0) d_x=0.9999999; else d_x=1.0e-6; } if(abs(d_y-0.5) >= 0.5) { std::cout << "dy error " << abs(d_y-0.5)-0.5 << "\n"; if(d_y > 1.0) d_y=0.9999999; else d_y=1.0e-6; } if(abs(d_z-0.5) >= 0.5) { std::cout << "dz error " << abs(d_z-0.5)-0.5 << "\n"; if(d_z > 1.0) d_z=0.9999999; else d_z=1.0e-6; } T d_1=(1.0-d_x)*(1.0-d_y); T d_2=d_x*(1.0-d_y); T d_3=(1.0-d_x)*d_y; T d_4=d_x*d_y; T d_z_1_dm=(1.0-d_z)*dm; T d_z_dm=d_z*dm; // dens[0]+=d_1*d_z_1_dm; dens[1]+=d_2*d_z_1_dm; dens[2]+=d_3*d_z_1_dm; dens[3]+=d_4*d_z_1_dm; dens[4]+=d_1*d_z_dm; dens[5]+=d_2*d_z_dm; dens[6]+=d_3*d_z_dm; dens[7]+=d_4*d_z_dm; } template <class T> static T sum_prod(const int& n1,const int& n2,const int& n3, std::vector <T>& x, std::vector <T>& y) { T sum=0.0; for (int n=n1 ; n <= n2; n+=n3) { sum+=x[n]*y[n]; } return sum; } template <class T> static void sum_prod(const int& n1,const int& n2,const int& n3, std::vector <T>& sum_4,std::vector <T>& x, std::vector <T>& a, std::vector <T>& b, std::vector <T>& c, std::vector <T>& d) { sum_4[0]=0.0; sum_4[1]=0.0; sum_4[2]=0.0; sum_4[3]=0.0; for (int n=n1 ; n <= n2; n+=n3) { sum_4[0]+=x[n]*a[n]; sum_4[1]+=x[n]*b[n]; sum_4[2]+=x[n]*c[n]; sum_4[3]+=x[n]*d[n]; } } template <class T> static void sum_prod(const int& n1,const int& n2,const int& n3, std::vector <T>& sum_4,std::vector <T>& x, std::vector <T>& a, std::vector <T>& b, std::vector <T>& c, std::vector <T>& d, std::vector <T>& e, std::vector <T>& f) { sum_4[0]=0.0; sum_4[1]=0.0; sum_4[2]=0.0; sum_4[3]=0.0; sum_4[4]=0.0; sum_4[5]=0.0; for (int n=n1 ; n <= n2; n+=n3) { sum_4[0]+=x[n]*a[n]; sum_4[1]+=x[n]*b[n]; sum_4[2]+=x[n]*c[n]; sum_4[3]+=x[n]*d[n]; sum_4[4]+=x[n]*e[n]; sum_4[5]+=x[n]*f[n]; } } template <class T> static void sum_prod_p_sharp(const int& n1,const int& n2,const int& n3, std::vector <T>& sum_4, std::vector <T>& w_p,std::vector <T>& w_x,std::vector <T>& w_y,std::vector <T>& w_z, std::vector <T>& a) { sum_4[0]=0.0; sum_4[1]=0.0; sum_4[2]=0.0; sum_4[3]=0.0; for (int n=n1 ; n <= n2; n+=n3) { sum_4[0]+=w_p[n]*a[n]; sum_4[1]+=w_x[n]*a[n]; sum_4[2]+=w_y[n]*a[n]; sum_4[3]+=w_z[n]*a[n]; } } template <class T> static void set_weights(std::vector <T>& weights,const T& d_x,const T& d_y,const T& d_z) { T d_z_1=1.0-d_z; weights[0]=(1.0-d_x)*(1.0-d_y); weights[1]=d_x*(1.0-d_y); weights[2]=(1.0-d_x)*d_y; weights[3]=d_x*d_y; weights[4]=weights[0]*d_z; weights[5]=weights[1]*d_z; weights[6]=weights[2]*d_z; weights[7]=weights[3]*d_z; weights[0]*=d_z_1; weights[1]*=d_z_1; weights[2]*=d_z_1; weights[3]*=d_z_1; } template <class T> static void set_weights(std::vector <T>& weights_p,std::vector <T>& weights_x, std::vector <T>& weights_y,std::vector <T>& weights_z, const T& d_x,const T& d_y,const T& d_z) { T d_z_1=1.0-d_z; weights_p[0]=(1.0-d_x)*(1.0-d_y); weights_p[1]=d_x*(1.0-d_y); weights_p[2]=(1.0-d_x)*d_y; weights_p[3]=d_x*d_y; weights_p[4]=weights_p[0]*d_z; weights_p[5]=weights_p[1]*d_z; weights_p[6]=weights_p[2]*d_z; weights_p[7]=weights_p[3]*d_z; weights_p[0]*=d_z_1; weights_p[1]*=d_z_1; weights_p[2]*=d_z_1; weights_p[3]*=d_z_1; weights_x[0]=(weights_p[0]+weights_p[1]); weights_x[1]=-weights_x[0]; weights_x[2]=(weights_p[2]+weights_p[3]); weights_x[3]=-weights_x[2]; weights_x[4]=(weights_p[4]+weights_p[5]); weights_x[5]=-weights_x[4]; weights_x[6]=(weights_p[6]+weights_p[7]); weights_x[7]=-weights_x[6]; weights_y[0]=(weights_p[0]+weights_p[2]); weights_y[2]=-weights_y[0]; weights_y[1]=(weights_p[1]+weights_p[3]); weights_y[3]=-weights_y[1]; weights_y[4]=(weights_p[4]+weights_p[6]); weights_y[6]=-weights_y[4]; weights_y[5]=(weights_p[5]+weights_p[7]); weights_y[7]=-weights_y[5]; weights_z[0]=(weights_p[0]+weights_p[4]); weights_z[4]=-weights_z[0]; weights_z[1]=(weights_p[1]+weights_p[5]); weights_z[5]=-weights_z[1]; weights_z[2]=(weights_p[2]+weights_p[6]); weights_z[6]=-weights_z[2]; weights_z[3]=(weights_p[3]+weights_p[7]); weights_z[7]=-weights_z[3]; } template <class T> static T sinc_2(const T& x) { if(abs(x) > 0.0001) { T s=sin(x)/x; return s*s; } return 1.0-x*x/3.0; } template <class T> static T square_filter(const T& x) { if(abs(x) > 0.0001) { T s=3.0*(sin(x)-x*cos(x))/(x*x*x); return s*s; } return 1.0-x*x*0.2; } template <class T> static void my_assign(std::vector <T>& vector1,const int& itr1_begin ,const int& itr1_d,const T& value) { for(int itr1=itr1_begin;itr1<itr1_begin+itr1_d;itr1++) { vector1[itr1]=value; } } template <class T> void per_box(std::vector <T>& box,const T& length) { unsigned int bs=box.size(); if(bs == 6) { for(int ni2=0;ni2<6;ni2+=2) { int db=box[ni2+1]-box[ni2]; box[ni2]=(box[ni2]+length) % length; box[ni2+1]=box[ni2]+db; } } else if(bs == 3) { box[0]=(box[0]+length) % length; box[1]=(box[1]+length) % length; box[2]=(box[2]+length) % length; } else assert(0); } template <class T> void per_box(std::vector <T>& posa,std::vector <T>& posb,const T& length) { unsigned int ps=posa.size(); assert(ps == posb.size()); T dp; for(unsigned int ni=0;ni<ps;ni++) { dp=posb[ni]-posa[ni]; posa[ni]=(posa[ni]+length) % length; posb[ni]=posa[ni]+dp; } } template <class T> static void copy_vector(int& itr1,std::vector <T>& vector1,const std::vector <T>& vector2,const int& itr2_begin ,const int& itr2_d) { for(int i=itr2_begin;i<itr2_begin+itr2_d;i++) { vector1[itr1]=vector2[i]; itr1++; } } template <class T> static void copy_vector_non_zero(int& itr1,std::vector <T>& vector1,const std::vector <T>& vector2,const int& itr2_begin ,const int& itr2_d) { for(int itr2=itr2_begin;itr2<itr2_begin+itr2_d;itr2++) { if(vector2[itr2] != 0) { vector1[itr1]=vector2[itr2]; itr1++; } } } template <class T> static void vector_print(const std::vector <T>& vec,std::ofstream& FILE) { int j=vec.size(); for(int i=0;i<j;i++) FILE << vec[i] << " " ; FILE << "\n"; } template <class T> static void vector_print(const std::vector <T>& veca,const std::vector <T>& vecb,std::ofstream& FILE) { int j=veca.size(); for(int i=0;i<j;i++) FILE << veca[i] << " " ; j=vecb.size(); for(int i=0;i<j;i++) FILE << vecb[i] << " " ; FILE << "\n"; } template <class T> static void vector_print(const std::vector <T>& veca,const std::vector <T>& vecb,const std::vector <T>& vecc,std::ofstream& FILE) { int j=veca.size(); for(int i=0;i<j;i++) FILE << veca[i] << " " ; j=vecb.size(); for(int i=0;i<j;i++) FILE << vecb[i] << " " ; j=vecc.size(); for(int i=0;i<j;i++) FILE << vecc[i] << " " ; FILE << "\n"; } template <class T> static void sum_up(T& sum,std::vector <T>& values,int first,int last,const int stride) { sum=0; if((last-first)*stride <= 0) return; while(first < last) { sum+=values[first]; first+=stride; } return; } // template <class T> void zero_shrink_std::vector(std::vector <T>& vec,int size) // { // vec.clear(); // vec.resize(size); // vec.shrink_to_fit(); // } // template <class T> void shrink_std::vectors(std::vector <std::vector <T> >& vec) // { // vec.shrink_to_fit(); // for(std::vector <T> v : vec) // v.shrink_to_fit(); // } template <class T> struct count_up { bool operator()(const T A,const T B) const { return A < B; } }; template <class T> struct count_down { bool operator()(const T A,const T B) const { return A > B; } }; }; } #endif
26.868159
163
0.535321
jmikeowen
4ee2c7138c8c781c8b3996d4ab39a98f9f204452
1,316
cpp
C++
src/materialsystem/stdshaders/viewalpha.cpp
DeadZoneLuna/csso-src
6c978ea304ee2df3796bc9c0d2916bac550050d5
[ "Unlicense" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
src/materialsystem/stdshaders/viewalpha.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
null
null
null
src/materialsystem/stdshaders/viewalpha.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $Header: $ // $NoKeywords: $ //===========================================================================// #include "shaderlib/cshader.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" BEGIN_SHADER_FLAGS( ViewAlpha, "Help for ViewAlpha", SHADER_NOT_EDITABLE ) BEGIN_SHADER_PARAMS END_SHADER_PARAMS SHADER_INIT { LoadTexture( BASETEXTURE ); } SHADER_DRAW { SHADOW_STATE { pShaderShadow->EnableTexture( SHADER_SAMPLER0, true ); pShaderShadow->EnableCustomPixelPipe( true ); pShaderShadow->CustomTextureStages( 1 ); pShaderShadow->CustomTextureOperation( SHADER_TEXTURE_STAGE0, SHADER_TEXCHANNEL_COLOR, SHADER_TEXOP_SELECTARG1, SHADER_TEXARG_TEXTUREALPHA, SHADER_TEXARG_CONSTANTCOLOR ); pShaderShadow->CustomTextureOperation( SHADER_TEXTURE_STAGE0, SHADER_TEXCHANNEL_ALPHA, SHADER_TEXOP_SELECTARG1, SHADER_TEXARG_TEXTURE, SHADER_TEXARG_VERTEXCOLOR ); pShaderShadow->DrawFlags( SHADER_DRAW_POSITION | SHADER_DRAW_TEXCOORD0 ); } DYNAMIC_STATE { BindTexture( SHADER_SAMPLER0, BASETEXTURE, FRAME ); SetFixedFunctionTextureTransform( MATERIAL_TEXTURE0, BASETEXTURETRANSFORM ); } Draw( ); } END_SHADER
26.857143
79
0.703647
DeadZoneLuna
4ee4dd0412257db61f5f79339226297cd5c50c6e
4,710
hpp
C++
INCLUDE/Vcl/ClxSprigs.hpp
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
1
2022-01-13T01:03:55.000Z
2022-01-13T01:03:55.000Z
INCLUDE/Vcl/ClxSprigs.hpp
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
null
null
null
INCLUDE/Vcl/ClxSprigs.hpp
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
null
null
null
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'ClxSprigs.pas' rev: 6.00 #ifndef ClxSprigsHPP #define ClxSprigsHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <TreeIntf.hpp> // Pascal unit #include <Contnrs.hpp> // Pascal unit #include <TypInfo.hpp> // Pascal unit #include <DesignEditors.hpp> // Pascal unit #include <DesignIntf.hpp> // Pascal unit #include <QForms.hpp> // Pascal unit #include <QControls.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <Messages.hpp> // Pascal unit #include <Windows.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Clxsprigs { //-- type declarations ------------------------------------------------------- class DELPHICLASS TControlSprig; class PASCALIMPLEMENTATION TControlSprig : public Treeintf::TComponentSprig { typedef Treeintf::TComponentSprig inherited; public: __fastcall virtual TControlSprig(Classes::TPersistent* AItem)/* overload */; /* virtual class method */ virtual bool __fastcall PaletteOverTo(TMetaClass* vmt, Treeintf::TSprig* AParent, TMetaClass* AClass); virtual bool __fastcall DragOverTo(Treeintf::TSprig* AParent); virtual bool __fastcall DragDropTo(Treeintf::TSprig* AParent); public: #pragma option push -w-inl /* TSprig.Destroy */ inline __fastcall virtual ~TControlSprig(void) { } #pragma option pop }; class DELPHICLASS TWidgetControlSprig; class PASCALIMPLEMENTATION TWidgetControlSprig : public TControlSprig { typedef TControlSprig inherited; public: __fastcall virtual TWidgetControlSprig(Classes::TPersistent* AItem)/* overload */; virtual bool __fastcall DragOver(Treeintf::TSprig* AItem); virtual bool __fastcall DragDrop(Treeintf::TSprig* AItem); virtual bool __fastcall PaletteOver(TMetaClass* ASprigClass, TMetaClass* AClass); public: #pragma option push -w-inl /* TSprig.Destroy */ inline __fastcall virtual ~TWidgetControlSprig(void) { } #pragma option pop }; class DELPHICLASS TFrameSprig; class PASCALIMPLEMENTATION TFrameSprig : public TWidgetControlSprig { typedef TWidgetControlSprig inherited; public: __fastcall virtual TFrameSprig(Classes::TPersistent* AItem)/* overload */; virtual void __fastcall FigureChildren(void); public: #pragma option push -w-inl /* TSprig.Destroy */ inline __fastcall virtual ~TFrameSprig(void) { } #pragma option pop }; class DELPHICLASS TWidgetControlRootSprig; class PASCALIMPLEMENTATION TWidgetControlRootSprig : public Treeintf::TRootSprig { typedef Treeintf::TRootSprig inherited; public: __fastcall virtual TWidgetControlRootSprig(Classes::TPersistent* AItem)/* overload */; virtual bool __fastcall DragOver(Treeintf::TSprig* AItem); virtual bool __fastcall DragDrop(Treeintf::TSprig* AItem); virtual bool __fastcall PaletteOver(TMetaClass* ASprigClass, TMetaClass* AClass); public: #pragma option push -w-inl /* TRootSprig.Destroy */ inline __fastcall virtual ~TWidgetControlRootSprig(void) { } #pragma option pop }; class DELPHICLASS TCustomFormRootSprig; class PASCALIMPLEMENTATION TCustomFormRootSprig : public TWidgetControlRootSprig { typedef TWidgetControlRootSprig inherited; public: __fastcall virtual TCustomFormRootSprig(Classes::TPersistent* AItem)/* overload */; public: #pragma option push -w-inl /* TRootSprig.Destroy */ inline __fastcall virtual ~TCustomFormRootSprig(void) { } #pragma option pop }; class DELPHICLASS TDataModuleRootSprig; class PASCALIMPLEMENTATION TDataModuleRootSprig : public Treeintf::TRootSprig { typedef Treeintf::TRootSprig inherited; public: __fastcall virtual TDataModuleRootSprig(Classes::TPersistent* AItem)/* overload */; virtual bool __fastcall DragOver(Treeintf::TSprig* AItem); virtual bool __fastcall PaletteOver(TMetaClass* ASprigClass, TMetaClass* AClass); virtual bool __fastcall AcceptsClass(TMetaClass* AClass); public: #pragma option push -w-inl /* TRootSprig.Destroy */ inline __fastcall virtual ~TDataModuleRootSprig(void) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- } /* namespace Clxsprigs */ using namespace Clxsprigs; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // ClxSprigs
32.482759
131
0.712527
earthsiege2
4eeb93e160da13cf980f0e9e184f807dce735f0c
9,864
cpp
C++
TitaniumRose/src/Platform/D3D12/D3D12DeviceResources.cpp
Zinadore/Hazel-D3D12
084cf9a473b6c66a2890f107667f687d6c7ed0a0
[ "Apache-2.0" ]
null
null
null
TitaniumRose/src/Platform/D3D12/D3D12DeviceResources.cpp
Zinadore/Hazel-D3D12
084cf9a473b6c66a2890f107667f687d6c7ed0a0
[ "Apache-2.0" ]
null
null
null
TitaniumRose/src/Platform/D3D12/D3D12DeviceResources.cpp
Zinadore/Hazel-D3D12
084cf9a473b6c66a2890f107667f687d6c7ed0a0
[ "Apache-2.0" ]
null
null
null
#include "trpch.h" #include "D3D12DeviceResources.h" #include "D3D12Helpers.h" namespace Roses { D3D12DeviceResources::D3D12DeviceResources(UINT bufferCount) { if (bufferCount < 2) { HZ_CORE_ERROR("Buffer count cannot be less than 2. Was give {0}", bufferCount); bufferCount = 2; } SwapChainBufferCount = bufferCount; BackBuffers.resize(SwapChainBufferCount); } D3D12DeviceResources::~D3D12DeviceResources() { } void D3D12DeviceResources::EnableDebugLayer() { #if defined(HZ_DEBUG) && !defined(HZ_NO_D3D12_DEBUG_LAYER) TComPtr<ID3D12Debug> debugInterface; D3D12::ThrowIfFailed(D3D12GetDebugInterface(IID_PPV_ARGS(&debugInterface))); debugInterface->EnableDebugLayer(); #endif } TComPtr<IDXGIAdapter4> D3D12DeviceResources::GetAdapter(bool useWarp, D3D12::VendorID preferedVendor) { TComPtr<IDXGIFactory4> dxgiFactory; UINT factoryFlags = 0; #if defined(HZ_DEBUG) && !defined(HZ_NO_D3D12_DEBUG_LAYER) factoryFlags |= DXGI_CREATE_FACTORY_DEBUG; #endif D3D12::ThrowIfFailed(CreateDXGIFactory2( factoryFlags, IID_PPV_ARGS(&dxgiFactory) )); TComPtr<IDXGIAdapter1> dxgiAdapter1; TComPtr<IDXGIAdapter4> dxgiAdapter4; if (useWarp) { D3D12::ThrowIfFailed(dxgiFactory->EnumWarpAdapter(IID_PPV_ARGS(&dxgiAdapter1))); D3D12::ThrowIfFailed(dxgiAdapter1.As(&dxgiAdapter4)); } else { // We grab the adapter with the highest VRAM. It "should" be the most performant one. SIZE_T maxDedicatedVideoMemory = 0; for (UINT i = 0; DXGI_ERROR_NOT_FOUND != dxgiFactory->EnumAdapters1(i, &dxgiAdapter1); ++i) { DXGI_ADAPTER_DESC1 dxgiAdapterDesc1; dxgiAdapter1->GetDesc1(&dxgiAdapterDesc1); if (dxgiAdapterDesc1.DedicatedVideoMemory > maxDedicatedVideoMemory) { D3D12::ThrowIfFailed(D3D12CreateDevice(dxgiAdapter1.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device2), nullptr)); maxDedicatedVideoMemory = dxgiAdapterDesc1.DedicatedVideoMemory; D3D12::ThrowIfFailed(dxgiAdapter1.As(&dxgiAdapter4)); } } } return dxgiAdapter4; } TComPtr<ID3D12Device2> D3D12DeviceResources::CreateDevice(TComPtr<IDXGIAdapter4> adapter) { TComPtr<ID3D12Device2> d3d12Device2; D3D12::ThrowIfFailed(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&d3d12Device2))); #if defined(HZ_DEBUG) // Add some message suppression in debug mode TComPtr<ID3D12InfoQueue> pInfoQueue; if (SUCCEEDED(d3d12Device2.As(&pInfoQueue))) { pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, TRUE); pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, TRUE); pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, TRUE); // Suppress whole categories of messages //D3D12_MESSAGE_CATEGORY Categories[] = {}; // Suppress messages based on their severity level D3D12_MESSAGE_SEVERITY Severities[] = { D3D12_MESSAGE_SEVERITY_INFO }; // Suppress individual messages by their ID D3D12_MESSAGE_ID DenyIds[] = { D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE, // I'm really not sure how to avoid this message. D3D12_MESSAGE_ID_MAP_INVALID_NULLRANGE, // This warning occurs when using capture frame while graphics debugging. D3D12_MESSAGE_ID_UNMAP_INVALID_NULLRANGE, // This warning occurs when using capture frame while graphics debugging. D3D12_MESSAGE_ID_RESOLVE_QUERY_INVALID_QUERY_STATE, // For the marking of invalid timestamps in our profiler (D3D12_MESSAGE_ID)1008 // RESOURCE_BARRIER_DUPLICATE_SUBRESOURCE_TRANSITIONS }; D3D12_INFO_QUEUE_FILTER NewFilter = {}; //NewFilter.DenyList.NumCategories = _countof(Categories); //NewFilter.DenyList.pCategoryList = Categories; NewFilter.DenyList.NumSeverities = _countof(Severities); NewFilter.DenyList.pSeverityList = Severities; NewFilter.DenyList.NumIDs = _countof(DenyIds); NewFilter.DenyList.pIDList = DenyIds; D3D12::ThrowIfFailed(pInfoQueue->PushStorageFilter(&NewFilter)); } #endif return d3d12Device2; } TComPtr<ID3D12CommandQueue> D3D12DeviceResources::CreateCommandQueue(TComPtr<ID3D12Device2> device, D3D12_COMMAND_LIST_TYPE type) { TComPtr<ID3D12CommandQueue> d3d12CommandQueue; D3D12_COMMAND_QUEUE_DESC desc = {}; desc.Type = type; desc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL; desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; // NOTE: For multi adapter this needs to have 1 bit set for the adapter we wanna use. // also setting this to 1 would still work the exact same way for 1 GPU systems, but // we are going with what the documentation says now. desc.NodeMask = 0; D3D12::ThrowIfFailed(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&d3d12CommandQueue))); return d3d12CommandQueue; } TComPtr<ID3D12CommandAllocator> D3D12DeviceResources::CreateCommandAllocator(TComPtr<ID3D12Device2> device, D3D12_COMMAND_LIST_TYPE type) { TComPtr<ID3D12CommandAllocator> commandAllocator; D3D12::ThrowIfFailed(device->CreateCommandAllocator(type, IID_PPV_ARGS(&commandAllocator))); return commandAllocator; } TComPtr<ID3D12GraphicsCommandList> D3D12DeviceResources::CreateCommandList(TComPtr<ID3D12Device2> device, TComPtr<ID3D12CommandAllocator> commandAllocator, D3D12_COMMAND_LIST_TYPE type, bool closeList) { TComPtr<ID3D12GraphicsCommandList> commandList; D3D12::ThrowIfFailed(device->CreateCommandList(0, type, commandAllocator.Get(), nullptr, IID_PPV_ARGS(&commandList))); if (closeList) { D3D12::ThrowIfFailed(commandList->Close()); } return commandList; } TComPtr<IDXGISwapChain4> D3D12DeviceResources::CreateSwapChain(SwapChainCreationOptions& opts, ID3D12CommandQueue* commandQueue) { TComPtr<IDXGISwapChain4> dxgiSwapChain4; TComPtr<IDXGIFactory4> dxgiFactory4; UINT createFactoryFlags = 0; #if defined(HZ_DEBUG) && !defined(HZ_NO_D3D12_DEBUG_LAYER) createFactoryFlags |= DXGI_CREATE_FACTORY_DEBUG; #endif D3D12::ThrowIfFailed(CreateDXGIFactory2(createFactoryFlags, IID_PPV_ARGS(&dxgiFactory4))); DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {}; swapChainDesc.Width = opts.Width; swapChainDesc.Height = opts.Height; swapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.Stereo = FALSE; swapChainDesc.SampleDesc = { 1, 0 }; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = opts.BufferCount; swapChainDesc.Scaling = DXGI_SCALING_NONE; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; // TODO: It is recommended to always allow tearing if tearing support is available. swapChainDesc.Flags = opts.TearingSupported ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0; TComPtr<IDXGISwapChain1> swapChain1; D3D12::ThrowIfFailed(dxgiFactory4->CreateSwapChainForHwnd( commandQueue, opts.Handle, &swapChainDesc, nullptr, nullptr, &swapChain1)); // Disable the Alt+Enter fullscreen toggle feature. Switching to fullscreen // will be handled manually. D3D12::ThrowIfFailed(dxgiFactory4->MakeWindowAssociation(opts.Handle, DXGI_MWA_NO_ALT_ENTER)); D3D12::ThrowIfFailed(swapChain1.As(&dxgiSwapChain4)); return dxgiSwapChain4; } TComPtr<ID3D12DescriptorHeap> D3D12DeviceResources::CreateDescriptorHeap(TComPtr<ID3D12Device2> device, D3D12_DESCRIPTOR_HEAP_TYPE type, uint32_t numDescriptors, D3D12_DESCRIPTOR_HEAP_FLAGS flags /*= D3D12_DESCRIPTOR_HEAP_FLAG_NONE*/) { TComPtr<ID3D12DescriptorHeap> descriptorHeap; D3D12_DESCRIPTOR_HEAP_DESC desc = {}; desc.NumDescriptors = numDescriptors; desc.Type = type; desc.Flags = flags; D3D12::ThrowIfFailed(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&descriptorHeap))); return descriptorHeap; } TComPtr<ID3D12Fence> D3D12DeviceResources::CreateFence(TComPtr<ID3D12Device2> device) { TComPtr<ID3D12Fence> fence; D3D12::ThrowIfFailed(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))); return fence; } #if 0 uint64_t D3D12DeviceResources::Signal(TComPtr<ID3D12CommandQueue> commandQueue, TComPtr<ID3D12Fence> fence, uint64_t fenceValue) { uint64_t val = ++fenceValue; D3D12::ThrowIfFailed(commandQueue->Signal(fence.Get(), val)); return val; } void D3D12DeviceResources::WaitForFenceValue(TComPtr<ID3D12Fence> fence, uint64_t fenceValue, UINT duration) { if (fence->GetCompletedValue() < fenceValue) { HANDLE evt = ::CreateEventEx(nullptr, false, false, EVENT_ALL_ACCESS); D3D12::ThrowIfFailed(fence->SetEventOnCompletion(fenceValue, evt)); ::WaitForSingleObject(evt, duration); ::CloseHandle(evt); } } #endif }
40.261224
238
0.679136
Zinadore
4eec55e37180c62ea9113fecfc1feb071b46e1cf
1,541
hpp
C++
Acid/include/acid/Events/Observer.hpp
Equilibrium-Games/Acid-Sharp
7b079a052e3e03f90fd4a4190184f1fbe765ca58
[ "MIT" ]
3
2018-10-19T23:33:37.000Z
2019-04-07T11:46:44.000Z
Sources/Events/Observer.hpp
sum01/Acid
d921472e062fc26b87c0163918aab553ac20739a
[ "MIT" ]
null
null
null
Sources/Events/Observer.hpp
sum01/Acid
d921472e062fc26b87c0163918aab553ac20739a
[ "MIT" ]
null
null
null
#pragma once #include <functional> #include <vector> #include "Engine/Exports.hpp" namespace acid { /// <summary> /// A class that holds a array of subscribed event callbacks. /// </summary> template<typename ...Args> class Observer { private: std::vector<std::function<void(Args...)>> m_subscribed; public: /// <summary> /// Creates a new callback observer. /// </summary> Observer() : m_subscribed(std::vector<std::function<void(Args...)>>()) { } /// <summary> /// Run when a event has occurred. /// </summary> /// <param name="args"> The args to pass to the functions. </param> void OnEvent(Args ...args) const { for (auto &function : m_subscribed) { function(std::forward<Args>(args)...); } } /// <summary> /// Subscribes a function to this observer. /// </summary> /// <param name="function"> The function to subscribe to this observer. </param> void Subscribe(const std::function<void(Args...)> &function) { m_subscribed.emplace_back(function); } /// <summary> /// Unsubscribes a function to this observer. /// </summary> /// <param name="function"> The function to unsubscribe to this observer. </param> /// <returns> If the function was unsubscribed. </returns> bool Unsubscribe(const std::function<void(Args...)> &function) { for (auto it = --m_subscribed.end(); it != m_subscribed.begin(); --it) { if ((*it).get() != function) { continue; } m_subscribed.erase(it); return true; } return false; } }; }
22.333333
84
0.622972
Equilibrium-Games
4eed2954463a514c143da9a5834d85f615748ed3
3,752
hpp
C++
include/codegen/include/GlobalNamespace/HowToPlayViewController.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/GlobalNamespace/HowToPlayViewController.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/GlobalNamespace/HowToPlayViewController.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: HMUI.ViewController #include "HMUI/ViewController.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::UI namespace UnityEngine::UI { // Forward declaring type: Button class Button; } // Forward declaring namespace: HMUI namespace HMUI { // Forward declaring type: TextSegmentedControl class TextSegmentedControl; // Forward declaring type: SegmentedControl class SegmentedControl; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: GameObject class GameObject; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action class Action; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Autogenerated type: HowToPlayViewController class HowToPlayViewController : public HMUI::ViewController { public: // private UnityEngine.UI.Button _tutorialButton // Offset: 0x68 UnityEngine::UI::Button* tutorialButton; // private HMUI.TextSegmentedControl _selectionSegmentedControl // Offset: 0x70 HMUI::TextSegmentedControl* selectionSegmentedControl; // private UnityEngine.GameObject[] _panels // Offset: 0x78 ::Array<UnityEngine::GameObject*>* panels; // private System.Action didPressTutorialButtonEvent // Offset: 0x80 System::Action* didPressTutorialButtonEvent; // public System.Void add_didPressTutorialButtonEvent(System.Action value) // Offset: 0xB44D24 void add_didPressTutorialButtonEvent(System::Action* value); // public System.Void remove_didPressTutorialButtonEvent(System.Action value) // Offset: 0xB44DC8 void remove_didPressTutorialButtonEvent(System::Action* value); // public System.Void Setup(System.Boolean showTutorialButton) // Offset: 0xB44E6C void Setup(bool showTutorialButton); // private System.Void HandleSelectionSegmentedControlDidSelectCell(HMUI.SegmentedControl segmentedControl, System.Int32 cellIdx) // Offset: 0xB45114 void HandleSelectionSegmentedControlDidSelectCell(HMUI::SegmentedControl* segmentedControl, int cellIdx); // private System.Void SetActivePanel(System.Int32 panelIdx) // Offset: 0xB45094 void SetActivePanel(int panelIdx); // private System.Void <DidActivate>b__7_0() // Offset: 0xB45124 void $DidActivate$b__7_0(); // protected override System.Void DidActivate(System.Boolean firstActivation, HMUI.ViewController/ActivationType activationType) // Offset: 0xB44EA8 // Implemented from: HMUI.ViewController // Base method: System.Void ViewController::DidActivate(System.Boolean firstActivation, HMUI.ViewController/ActivationType activationType) void DidActivate(bool firstActivation, HMUI::ViewController::ActivationType activationType); // public System.Void .ctor() // Offset: 0xB4511C // Implemented from: HMUI.ViewController // Base method: System.Void ViewController::.ctor() // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static HowToPlayViewController* New_ctor(); }; // HowToPlayViewController } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::HowToPlayViewController*, "", "HowToPlayViewController"); #pragma pack(pop)
41.688889
142
0.74307
Futuremappermydud
4eed9f47912298bee34b66e0dde1049d76534c9c
46,516
cpp
C++
test/unittest_uart.cpp
NewJapanRadio/NJU9103_eva_mcu
f5eaef3e2ff8dcde9e7334f40ae8ab2fcec13fbc
[ "MIT" ]
1
2018-03-20T08:31:57.000Z
2018-03-20T08:31:57.000Z
test/unittest_uart.cpp
NewJapanRadio/NJU9103_eva_mcu
f5eaef3e2ff8dcde9e7334f40ae8ab2fcec13fbc
[ "MIT" ]
null
null
null
test/unittest_uart.cpp
NewJapanRadio/NJU9103_eva_mcu
f5eaef3e2ff8dcde9e7334f40ae8ab2fcec13fbc
[ "MIT" ]
null
null
null
#include <limits.h> #define private public #include "nju9103.h" #undef private #include "gtest/gtest.h" #include <stdio.h> using namespace ::testing; extern Packet rxPacket; extern ReceiveDataStatus receiveDataStatus; extern Command command; extern NewJapanRadio::Serial uart; extern NewJapanRadio::Timer packetWatchTimer; extern NewJapanRadio::Dispatcher dispatcher; extern NewJapanRadio::ADCDataBuffer adcDataBuffer; extern void (*fpIsrRx)(void); extern void _attach(void (*fp)(void), NewJapanRadio::Serial::IrqType type); TEST(UART, SPIReset) { EXPECT_CALL(packetWatchTimer, attach(_, _)).Times(AnyNumber()); EXPECT_CALL(uart, attach(_, NewJapanRadio::Serial::RxIrq)) .WillRepeatedly(Invoke(_attach)); { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, readable()) .Times(Exactly(2)) .WillOnce(Return(1)) .WillOnce(Return(0)); } } { InSequence s; EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x7F)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0xFF)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0xFF)); } uint8_t cmd[] = { 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEF }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd[i])); } } uint8_t res[] = { 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDF }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)); } } setup(); for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } EXPECT_EQ(0x2, receiveDataStatus); isrPacketWatch(); EXPECT_EQ(0x0, receiveDataStatus); EXPECT_EQ(0x1000, command); loop(); } TEST(UART, RegisterWrite8Bit) { EXPECT_CALL(packetWatchTimer, attach(_, _)).Times(AnyNumber()); EXPECT_CALL(uart, attach(_, NewJapanRadio::Serial::RxIrq)) .WillRepeatedly(Invoke(_attach)); { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, readable()) .Times(Exactly(2)) .WillOnce(Return(1)) .WillOnce(Return(0)); } } { InSequence s; EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x50)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x12)); } uint8_t cmd[] = { 0x10, 0x10, 0x05, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC8 }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd[i])); } } uint8_t res[] = { 0x20, 0x10, 0x05, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB8 }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)); } } setup(); for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } EXPECT_EQ(0x2, receiveDataStatus); isrPacketWatch(); EXPECT_EQ(0x0, receiveDataStatus); EXPECT_EQ(0x0001, command); loop(); } TEST(UART, RegisterRead8Bit) { EXPECT_CALL(packetWatchTimer, attach(_, _)).Times(AnyNumber()); EXPECT_CALL(uart, attach(_, NewJapanRadio::Serial::RxIrq)) .WillRepeatedly(Invoke(_attach)); { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, readable()) .Times(Exactly(2)) .WillOnce(Return(1)) .WillOnce(Return(0)); } } { InSequence s; EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x38)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) .WillOnce(Return(0x45)); } uint8_t cmd[] = { 0x10, 0x20, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xCC }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd[i])); } } uint8_t res[] = { 0x20, 0x20, 0x03, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, 0x77 }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)); } } setup(); for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } EXPECT_EQ(0x2, receiveDataStatus); isrPacketWatch(); EXPECT_EQ(0x0, receiveDataStatus); EXPECT_EQ(0x0002, command); loop(); } TEST(UART, RegisterWrite16Bit) { EXPECT_CALL(packetWatchTimer, attach(_, _)).Times(AnyNumber()); EXPECT_CALL(uart, attach(_, NewJapanRadio::Serial::RxIrq)) .WillRepeatedly(Invoke(_attach)); { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, readable()) .Times(Exactly(2)) .WillOnce(Return(1)) .WillOnce(Return(0)); } } { InSequence s; EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0xA4)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x2F)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x59)); } uint8_t cmd[] = { 0x10, 0x30, 0x0A, 0x2F, 0x59, 0x00, 0x00, 0x00, 0x00, 0x2D }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd[i])); } } uint8_t res[] = { 0x20, 0x30, 0x0A, 0x2F, 0x59, 0x00, 0x00, 0x00, 0x00, 0x1D }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)); } } setup(); for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } EXPECT_EQ(0x2, receiveDataStatus); isrPacketWatch(); EXPECT_EQ(0x0, receiveDataStatus); EXPECT_EQ(0x0004, command); loop(); } TEST(UART, RegisterRead16Bit) { EXPECT_CALL(packetWatchTimer, attach(_, _)).Times(AnyNumber()); EXPECT_CALL(uart, attach(_, NewJapanRadio::Serial::RxIrq)) .WillRepeatedly(Invoke(_attach)); { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, readable()) .Times(Exactly(2)) .WillOnce(Return(1)) .WillOnce(Return(0)); } } { InSequence s; EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x5C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) .WillOnce(Return(0x67)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) .WillOnce(Return(0x89)); } uint8_t cmd[] = { 0x10, 0x40, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAA }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd[i])); } } uint8_t res[] = { 0x20, 0x40, 0x05, 0x67, 0x89, 0x00, 0x00, 0x00, 0x00, 0xAA }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)); } } setup(); for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } EXPECT_EQ(0x2, receiveDataStatus); isrPacketWatch(); EXPECT_EQ(0x0, receiveDataStatus); EXPECT_EQ(0x0008, command); loop(); } TEST(UART, StartSingleConversion) { EXPECT_CALL(packetWatchTimer, attach(_, _)).Times(AnyNumber()); EXPECT_CALL(uart, attach(_, NewJapanRadio::Serial::RxIrq)) .WillRepeatedly(Invoke(_attach)); { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, readable()) .Times(Exactly(2)) .WillOnce(Return(1)) .WillOnce(Return(0)); } } EXPECT_CALL(*(dispatcher.spiCommand)->rdyb, read()) .Times(AtLeast(3)) .WillOnce(Return(1)) .WillOnce(Return(1)) .WillOnce(Return(0)); { InSequence s; EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)); // CTRL Register Address EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x02)); // { chsel, mode } EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); // ADCDATA0 Register Address EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) .Times(Exactly(2)) .WillOnce(Return(0xAB)) // ADCDATA0 Register Value .WillOnce(Return(0xCD)); // ADCDATA1 Register Value } uint8_t cmd[] = { 0x10, 0x50, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9D }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd[i])); } } uint8_t res[] = { 0x20, 0x50, 0x02, 0xAB, 0xCD, 0x00, 0x00, 0x00, 0x00, 0x15 }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)); } } setup(); for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } EXPECT_EQ(0x2, receiveDataStatus); isrPacketWatch(); EXPECT_EQ(0x0, receiveDataStatus); EXPECT_EQ(0x0010, command); loop(); } TEST(UART, StartContinuousConversion) { EXPECT_CALL(packetWatchTimer, attach(_, _)).Times(AnyNumber()); EXPECT_CALL(uart, attach(_, NewJapanRadio::Serial::RxIrq)) .WillRepeatedly(Invoke(_attach)); { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, readable()) .Times(Exactly(2)) .WillOnce(Return(1)) .WillOnce(Return(0)); } } EXPECT_CALL(*(dispatcher.spiCommand)->rdyb, read()) .Times(Exactly(15)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)); { InSequence s; EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)); // CTRL Register Address EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x02)); // { chsel, mode } EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) .Times(Exactly(2)) .WillOnce(Return(0x12)) .WillOnce(Return(0x34)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) .Times(Exactly(2)) .WillOnce(Return(0x56)) .WillOnce(Return(0x78)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) .Times(Exactly(2)) .WillOnce(Return(0x9A)) .WillOnce(Return(0xBC)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) .Times(Exactly(2)) .WillOnce(Return(0xDE)) .WillOnce(Return(0xF1)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) .Times(Exactly(2)) .WillOnce(Return(0x23)) .WillOnce(Return(0x45)); // Stop Continuous Conversion `RegisterWrite(ADDR_CTRL, 0xF0 & { chsel, mode })` EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)); } uint8_t cmd[] = { 0x10, 0x60, 0x02, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x89 }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd[i])); } } uint8_t res[] = { 0x20, 0x60, 0x02, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x79 }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)); } } setup(); for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } EXPECT_EQ(0x2, receiveDataStatus); isrPacketWatch(); EXPECT_EQ(0x0, receiveDataStatus); EXPECT_EQ(0x0020, command); loop(); EXPECT_EQ(8, adcDataBuffer.allocatedSize); EXPECT_EQ(0x1234, adcDataBuffer.adcDataBuffer[0]); EXPECT_EQ(0x5678, adcDataBuffer.adcDataBuffer[1]); EXPECT_EQ(0x9ABC, adcDataBuffer.adcDataBuffer[2]); EXPECT_EQ(0xDEF1, adcDataBuffer.adcDataBuffer[3]); EXPECT_EQ(0x2345, adcDataBuffer.adcDataBuffer[4]); EXPECT_EQ(0x0000, adcDataBuffer.adcDataBuffer[5]); } TEST(UART, StartIntermittentConversion) { EXPECT_CALL(packetWatchTimer, attach(_, _)).Times(AnyNumber()); EXPECT_CALL(uart, attach(_, NewJapanRadio::Serial::RxIrq)) .WillRepeatedly(Invoke(_attach)); EXPECT_CALL(*(dispatcher.spiCommand)->sleep, sleep(_)) .Times(AnyNumber()); EXPECT_CALL(*(dispatcher.spiCommand)->sleep, sleepMillisecond(_)) .Times(AnyNumber()); EXPECT_CALL(*(dispatcher.spiCommand)->sleep, sleepMicrosecond(_)) .Times(AnyNumber()); EXPECT_CALL(*(dispatcher.spiCommand)->stopwatch, start()) .Times(AnyNumber()); EXPECT_CALL(*(dispatcher.spiCommand)->stopwatch, stop()) .Times(AnyNumber()); EXPECT_CALL(*(dispatcher.spiCommand)->stopwatch, read()) .Times(AnyNumber()) .WillRepeatedly(Return(100)); EXPECT_CALL(*(dispatcher.spiCommand)->stopwatch, readMillisecond()) .Times(AnyNumber()) .WillRepeatedly(Return(100)); EXPECT_CALL(*(dispatcher.spiCommand)->stopwatch, readMicrosecond()) .Times(AnyNumber()) .WillRepeatedly(Return(100)); { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, readable()) .Times(Exactly(2)) .WillOnce(Return(1)) .WillOnce(Return(0)); } } EXPECT_CALL(*(dispatcher.spiCommand)->rdyb, read()) .Times(Exactly(15)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)); { InSequence s; // data pattern is same as test of StartIntermittentConversion for (int i = 0x12; i <= 0xBC; i = i + 0x44) { EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x02)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(_)) .Times(Exactly(2)) .WillOnce(Return(i)) .WillOnce(Return(i+0x22)); } EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x02)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(_)) .Times(Exactly(2)) .WillOnce(Return(0xDE)) .WillOnce(Return(0xF1)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x02)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(_)) .Times(Exactly(2)) .WillOnce(Return(0x23)) .WillOnce(Return(0x45)); } uint8_t cmd[] = { 0x10, 0x70, 0x02, 0x00, 0x04, 0x00, 0x0F, 0x42, 0x40, 0xE8 }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd[i])); } } uint8_t res[] = { 0x20, 0x70, 0x02, 0x00, 0x04, 0x00, 0x0F, 0x42, 0x40, 0xD8 }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)); } } setup(); for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } EXPECT_EQ(0x2, receiveDataStatus); isrPacketWatch(); EXPECT_EQ(0x0, receiveDataStatus); EXPECT_EQ(0x0040, command); loop(); EXPECT_EQ(8, adcDataBuffer.allocatedSize); EXPECT_EQ(0x1234, adcDataBuffer.adcDataBuffer[0]); EXPECT_EQ(0x5678, adcDataBuffer.adcDataBuffer[1]); EXPECT_EQ(0x9ABC, adcDataBuffer.adcDataBuffer[2]); EXPECT_EQ(0xDEF1, adcDataBuffer.adcDataBuffer[3]); EXPECT_EQ(0x2345, adcDataBuffer.adcDataBuffer[4]); EXPECT_EQ(0x0000, adcDataBuffer.adcDataBuffer[5]); } TEST(UART, StartADCDataDump) { EXPECT_CALL(packetWatchTimer, attach(_, _)).Times(AnyNumber()); EXPECT_CALL(uart, attach(_, NewJapanRadio::Serial::RxIrq)) .WillRepeatedly(Invoke(_attach)); adcDataBuffer.SetDataLength(5); adcDataBuffer.allocatedSize = 8; adcDataBuffer.adcDataBuffer[0] = 0x1234; adcDataBuffer.adcDataBuffer[1] = 0x5678; adcDataBuffer.adcDataBuffer[2] = 0x9ABC; adcDataBuffer.adcDataBuffer[3] = 0xDEF1; adcDataBuffer.adcDataBuffer[4] = 0x2345; adcDataBuffer.adcDataBuffer[5] = 0x0000; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, readable()) .Times(Exactly(2)) .WillOnce(Return(1)) .WillOnce(Return(0)); } } uint8_t cmd[] = { 0x10, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6F }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd[i])); } } uint8_t res[] = { 0x20, 0x80, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x5B, 0x30, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF1, 0x96, 0x30, 0x23, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x67 }; { InSequence s; for (int i = 0; i < (PACKET_SIZE+1)*3; i++) { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)); } } setup(); for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } EXPECT_EQ(0x2, receiveDataStatus); isrPacketWatch(); EXPECT_EQ(0x0, receiveDataStatus); EXPECT_EQ(0x0080, command); loop(); } void StopSingleConversion() { for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } isrPacketWatch(); } TEST(UART, StopSingleConversion) { EXPECT_CALL(packetWatchTimer, attach(_, _)).Times(AnyNumber()); EXPECT_CALL(uart, attach(_, NewJapanRadio::Serial::RxIrq)) .WillRepeatedly(Invoke(_attach)); { InSequence s; for (int i = 0; i < (PACKET_SIZE+1)*2; i++) { EXPECT_CALL(uart, readable()) .Times(Exactly(2)) .WillOnce(Return(1)) .WillOnce(Return(0)); } } EXPECT_CALL(*(dispatcher.spiCommand)->rdyb, read()) .WillOnce(Return(1)) .WillOnce(DoAll(InvokeWithoutArgs(StopSingleConversion), Return(1))) .WillRepeatedly(Return(1)); { InSequence s; EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)); // CTRL Register Address EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x02)); // { chsel, mode } } uint8_t cmd1[] = { 0x10, 0x50, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9D }; uint8_t cmd2[] = { 0x10, 0x51, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9E }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd1[i])); } for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd2[i])); } } uint8_t res[] = { 0x20, 0x51, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8E }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)); } } setup(); for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } EXPECT_EQ(0x2, receiveDataStatus); isrPacketWatch(); EXPECT_EQ(0x0, receiveDataStatus); EXPECT_EQ(0x0010, command); // start single conversion loop(); // abort loop(); } TEST(UART, StopSingleConversion_By_SPIReset) { EXPECT_CALL(packetWatchTimer, attach(_, _)).Times(AnyNumber()); EXPECT_CALL(uart, attach(_, NewJapanRadio::Serial::RxIrq)) .WillRepeatedly(Invoke(_attach)); { InSequence s; for (int i = 0; i < (PACKET_SIZE+1)*2; i++) { EXPECT_CALL(uart, readable()) .Times(Exactly(2)) .WillOnce(Return(1)) .WillOnce(Return(0)); } } EXPECT_CALL(*(dispatcher.spiCommand)->rdyb, read()) .WillOnce(Return(1)) .WillOnce(DoAll(InvokeWithoutArgs(StopSingleConversion), Return(1))) .WillRepeatedly(Return(1)); { InSequence s; EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)); // CTRL Register Address EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x02)); // { chsel, mode } EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x7F)); // SPIResetCommand 0 EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0xFF)); // SPIResetCommand 1 EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0xFF)); // SPIResetCommand 2 } uint8_t cmd1[] = { 0x10, 0x50, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9D }; uint8_t cmd2[] = { 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEF }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd1[i])); } for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd2[i])); } } uint8_t res[] = { 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDF }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)); } } setup(); for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } EXPECT_EQ(0x2, receiveDataStatus); isrPacketWatch(); EXPECT_EQ(0x0, receiveDataStatus); EXPECT_EQ(0x0010, command); // start single conversion loop(); // abort loop(); } void StopContinuousConversion() { for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } isrPacketWatch(); } TEST(UART, StopContinuousConversion) { EXPECT_CALL(packetWatchTimer, attach(_, _)).Times(AnyNumber()); EXPECT_CALL(uart, attach(_, NewJapanRadio::Serial::RxIrq)) .WillRepeatedly(Invoke(_attach)); { InSequence s; for (int i = 0; i < (PACKET_SIZE+1)*2; i++) { EXPECT_CALL(uart, readable()) .Times(Exactly(2)) .WillOnce(Return(1)) .WillOnce(Return(0)); } } EXPECT_CALL(*(dispatcher.spiCommand)->rdyb, read()) .Times(Exactly(15)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(DoAll(InvokeWithoutArgs(StopContinuousConversion), Return(1))); { InSequence s; EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)); // CTRL Register Address EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x02)); // { chsel, mode } EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) .Times(Exactly(2)) .WillOnce(Return(0x12)) .WillOnce(Return(0x34)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) .Times(Exactly(2)) .WillOnce(Return(0x56)) .WillOnce(Return(0x78)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) .Times(Exactly(2)) .WillOnce(Return(0x9A)) .WillOnce(Return(0xBC)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) .Times(Exactly(2)) .WillOnce(Return(0xDE)) .WillOnce(Return(0xF1)); // This transaction will be aborted // EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); // EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) // .Times(Exactly(2)) // .WillOnce(Return(0x23)) // .WillOnce(Return(0x45)); } uint8_t cmd1[] = { 0x10, 0x60, 0x02, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x89 }; uint8_t cmd2[] = { 0x10, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8E }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd1[i])); } for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd2[i])); } } uint8_t res[] = { 0x20, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)); } } setup(); for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } EXPECT_EQ(0x2, receiveDataStatus); isrPacketWatch(); EXPECT_EQ(0x0, receiveDataStatus); EXPECT_EQ(0x0020, command); loop(); loop(); EXPECT_EQ(8, adcDataBuffer.allocatedSize); EXPECT_EQ(0x1234, adcDataBuffer.adcDataBuffer[0]); EXPECT_EQ(0x5678, adcDataBuffer.adcDataBuffer[1]); EXPECT_EQ(0x9ABC, adcDataBuffer.adcDataBuffer[2]); EXPECT_EQ(0xDEF1, adcDataBuffer.adcDataBuffer[3]); EXPECT_EQ(0x0000, adcDataBuffer.adcDataBuffer[4]); EXPECT_EQ(0x0000, adcDataBuffer.adcDataBuffer[5]); } TEST(UART, StopContinuousConversion_By_SPIReset) { EXPECT_CALL(packetWatchTimer, attach(_, _)).Times(AnyNumber()); EXPECT_CALL(uart, attach(_, NewJapanRadio::Serial::RxIrq)) .WillRepeatedly(Invoke(_attach)); { InSequence s; for (int i = 0; i < (PACKET_SIZE+1)*2; i++) { EXPECT_CALL(uart, readable()) .Times(Exactly(2)) .WillOnce(Return(1)) .WillOnce(Return(0)); } } EXPECT_CALL(*(dispatcher.spiCommand)->rdyb, read()) .Times(Exactly(15)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(DoAll(InvokeWithoutArgs(StopContinuousConversion), Return(1))); { InSequence s; EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)); // CTRL Register Address EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x02)); // { chsel, mode } EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) .Times(Exactly(2)) .WillOnce(Return(0x12)) .WillOnce(Return(0x34)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) .Times(Exactly(2)) .WillOnce(Return(0x56)) .WillOnce(Return(0x78)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) .Times(Exactly(2)) .WillOnce(Return(0x9A)) .WillOnce(Return(0xBC)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) .Times(Exactly(2)) .WillOnce(Return(0xDE)) .WillOnce(Return(0xF1)); // This transaction will be aborted // EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); // EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)) // .Times(Exactly(2)) // .WillOnce(Return(0x23)) // .WillOnce(Return(0x45)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x7F)); // SPIResetCommand 0 EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0xFF)); // SPIResetCommand 1 EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0xFF)); // SPIResetCommand 2 } uint8_t cmd1[] = { 0x10, 0x60, 0x02, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x89 }; uint8_t cmd2[] = { 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEF }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd1[i])); } for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd2[i])); } } uint8_t res[] = { 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDF }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)); } } setup(); for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } EXPECT_EQ(0x2, receiveDataStatus); isrPacketWatch(); EXPECT_EQ(0x0, receiveDataStatus); EXPECT_EQ(0x0020, command); loop(); loop(); EXPECT_EQ(8, adcDataBuffer.allocatedSize); EXPECT_EQ(0x1234, adcDataBuffer.adcDataBuffer[0]); EXPECT_EQ(0x5678, adcDataBuffer.adcDataBuffer[1]); EXPECT_EQ(0x9ABC, adcDataBuffer.adcDataBuffer[2]); EXPECT_EQ(0xDEF1, adcDataBuffer.adcDataBuffer[3]); EXPECT_EQ(0x0000, adcDataBuffer.adcDataBuffer[4]); EXPECT_EQ(0x0000, adcDataBuffer.adcDataBuffer[5]); } void StopIntermittentConversion() { for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } isrPacketWatch(); } TEST(UART, StopIntermittentConversion) { EXPECT_CALL(packetWatchTimer, attach(_, _)).Times(AnyNumber()); EXPECT_CALL(uart, attach(_, NewJapanRadio::Serial::RxIrq)) .WillRepeatedly(Invoke(_attach)); EXPECT_CALL(*(dispatcher.spiCommand)->sleep, sleep(_)) .Times(AnyNumber()); EXPECT_CALL(*(dispatcher.spiCommand)->sleep, sleepMillisecond(_)) .Times(AnyNumber()); EXPECT_CALL(*(dispatcher.spiCommand)->sleep, sleepMicrosecond(_)) .Times(AnyNumber()); EXPECT_CALL(*(dispatcher.spiCommand)->stopwatch, start()) .Times(AnyNumber()); EXPECT_CALL(*(dispatcher.spiCommand)->stopwatch, stop()) .Times(AnyNumber()); EXPECT_CALL(*(dispatcher.spiCommand)->stopwatch, read()) .Times(AnyNumber()) .WillRepeatedly(Return(100)); EXPECT_CALL(*(dispatcher.spiCommand)->stopwatch, readMillisecond()) .Times(AnyNumber()) .WillRepeatedly(Return(100)); EXPECT_CALL(*(dispatcher.spiCommand)->stopwatch, readMicrosecond()) .Times(AnyNumber()) .WillRepeatedly(Return(100)); { InSequence s; for (int i = 0; i < (PACKET_SIZE+1)*2; i++) { EXPECT_CALL(uart, readable()) .Times(Exactly(2)) .WillOnce(Return(1)) .WillOnce(Return(0)); } } EXPECT_CALL(*(dispatcher.spiCommand)->rdyb, read()) .Times(Exactly(15)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(DoAll(InvokeWithoutArgs(StopIntermittentConversion), Return(1))); { InSequence s; // data pattern is same as test of StartIntermittentConversion for (int i = 0x12; i <= 0xBC; i = i + 0x44) { EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x02)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(_)) .Times(Exactly(2)) .WillOnce(Return(i)) .WillOnce(Return(i+0x22)); } EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x02)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(_)) .Times(Exactly(2)) .WillOnce(Return(0xDE)) .WillOnce(Return(0xF1)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x02)); // EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); // EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(_)) // .Times(Exactly(2)) // .WillOnce(Return(0x23)) // .WillOnce(Return(0x45)); } uint8_t cmd1[] = { 0x10, 0x70, 0x02, 0x00, 0x04, 0x00, 0x0F, 0x42, 0x40, 0xE8 }; uint8_t cmd2[] = { 0x10, 0x71, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd1[i])); } for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd2[i])); } } uint8_t res[] = { 0x20, 0x71, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6E }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)); } } setup(); for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } EXPECT_EQ(0x2, receiveDataStatus); isrPacketWatch(); EXPECT_EQ(0x0, receiveDataStatus); EXPECT_EQ(0x0040, command); loop(); loop(); EXPECT_EQ(8, adcDataBuffer.allocatedSize); EXPECT_EQ(0x1234, adcDataBuffer.adcDataBuffer[0]); EXPECT_EQ(0x5678, adcDataBuffer.adcDataBuffer[1]); EXPECT_EQ(0x9ABC, adcDataBuffer.adcDataBuffer[2]); EXPECT_EQ(0xDEF1, adcDataBuffer.adcDataBuffer[3]); EXPECT_EQ(0x0000, adcDataBuffer.adcDataBuffer[4]); EXPECT_EQ(0x0000, adcDataBuffer.adcDataBuffer[5]); } TEST(UART, StopIntermittentConversion_By_SPIReset) { EXPECT_CALL(packetWatchTimer, attach(_, _)).Times(AnyNumber()); EXPECT_CALL(uart, attach(_, NewJapanRadio::Serial::RxIrq)) .WillRepeatedly(Invoke(_attach)); EXPECT_CALL(*(dispatcher.spiCommand)->sleep, sleep(_)) .Times(AnyNumber()); EXPECT_CALL(*(dispatcher.spiCommand)->sleep, sleepMillisecond(_)) .Times(AnyNumber()); EXPECT_CALL(*(dispatcher.spiCommand)->sleep, sleepMicrosecond(_)) .Times(AnyNumber()); EXPECT_CALL(*(dispatcher.spiCommand)->stopwatch, start()) .Times(AnyNumber()); EXPECT_CALL(*(dispatcher.spiCommand)->stopwatch, stop()) .Times(AnyNumber()); EXPECT_CALL(*(dispatcher.spiCommand)->stopwatch, read()) .Times(AnyNumber()) .WillRepeatedly(Return(100)); EXPECT_CALL(*(dispatcher.spiCommand)->stopwatch, readMillisecond()) .Times(AnyNumber()) .WillRepeatedly(Return(100)); EXPECT_CALL(*(dispatcher.spiCommand)->stopwatch, readMicrosecond()) .Times(AnyNumber()) .WillRepeatedly(Return(100)); { InSequence s; for (int i = 0; i < (PACKET_SIZE+1)*2; i++) { EXPECT_CALL(uart, readable()) .Times(Exactly(2)) .WillOnce(Return(1)) .WillOnce(Return(0)); } } EXPECT_CALL(*(dispatcher.spiCommand)->rdyb, read()) .Times(Exactly(15)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(Return(0)) .WillOnce(Return(1)).WillOnce(Return(1)).WillOnce(DoAll(InvokeWithoutArgs(StopIntermittentConversion), Return(1))); { InSequence s; // data pattern is same as test of StartIntermittentConversion for (int i = 0x12; i <= 0xBC; i = i + 0x44) { EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x02)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(_)) .Times(Exactly(2)) .WillOnce(Return(i)) .WillOnce(Return(i+0x22)); } EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x02)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(_)) .Times(Exactly(2)) .WillOnce(Return(0xDE)) .WillOnce(Return(0xF1)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x00)); EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x02)); // EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x1C)); // EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(_)) // .Times(Exactly(2)) // .WillOnce(Return(0x23)) // .WillOnce(Return(0x45)); // EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x7F)); // SPIResetCommand 0 EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0xFF)); // SPIResetCommand 1 EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0xFF)); // SPIResetCommand 2 } uint8_t cmd1[] = { 0x10, 0x70, 0x02, 0x00, 0x04, 0x00, 0x0F, 0x42, 0x40, 0xE8 }; uint8_t cmd2[] = { 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEF }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd1[i])); } for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd2[i])); } } uint8_t res[] = { 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDF }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)); } } setup(); for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } EXPECT_EQ(0x2, receiveDataStatus); isrPacketWatch(); EXPECT_EQ(0x0, receiveDataStatus); EXPECT_EQ(0x0040, command); loop(); loop(); EXPECT_EQ(8, adcDataBuffer.allocatedSize); EXPECT_EQ(0x1234, adcDataBuffer.adcDataBuffer[0]); EXPECT_EQ(0x5678, adcDataBuffer.adcDataBuffer[1]); EXPECT_EQ(0x9ABC, adcDataBuffer.adcDataBuffer[2]); EXPECT_EQ(0xDEF1, adcDataBuffer.adcDataBuffer[3]); EXPECT_EQ(0x0000, adcDataBuffer.adcDataBuffer[4]); EXPECT_EQ(0x0000, adcDataBuffer.adcDataBuffer[5]); } void StopADCDataDump() { for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } isrPacketWatch(); } TEST(UART, StopADCDataDump) { EXPECT_CALL(packetWatchTimer, attach(_, _)).Times(AnyNumber()); EXPECT_CALL(uart, attach(_, NewJapanRadio::Serial::RxIrq)) .WillRepeatedly(Invoke(_attach)); adcDataBuffer.SetDataLength(16); adcDataBuffer.allocatedSize = 16; adcDataBuffer.adcDataBuffer[0] = 0x1234; adcDataBuffer.adcDataBuffer[1] = 0x5678; adcDataBuffer.adcDataBuffer[2] = 0x9ABC; adcDataBuffer.adcDataBuffer[3] = 0xDEF1; adcDataBuffer.adcDataBuffer[4] = 0x1234; adcDataBuffer.adcDataBuffer[5] = 0x5678; adcDataBuffer.adcDataBuffer[6] = 0x9ABC; adcDataBuffer.adcDataBuffer[7] = 0xDEF1; adcDataBuffer.adcDataBuffer[8] = 0x1234; adcDataBuffer.adcDataBuffer[9] = 0x5678; adcDataBuffer.adcDataBuffer[10] = 0x9ABC; adcDataBuffer.adcDataBuffer[11] = 0xDEF1; adcDataBuffer.adcDataBuffer[12] = 0x1234; adcDataBuffer.adcDataBuffer[13] = 0x5678; adcDataBuffer.adcDataBuffer[14] = 0x9ABC; adcDataBuffer.adcDataBuffer[15] = 0xDEF1; { InSequence s; for (int i = 0; i < (PACKET_SIZE+1)*2; i++) { EXPECT_CALL(uart, readable()) .Times(Exactly(2)) .WillOnce(Return(1)) .WillOnce(Return(0)); } } uint8_t cmd1[] = { 0x10, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6F }; uint8_t cmd2[] = { 0x10, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6E }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd1[i])); } for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd2[i])); } } uint8_t res[] = { 0x20, 0x80, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x50, 0x30, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF1, 0x96, 0x30, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF1, 0x96, 0x20, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5E }; { InSequence s; for (int i = 0; i < (PACKET_SIZE+1)*4; i++) { if (i == 20) { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)) .WillOnce(InvokeWithoutArgs(StopADCDataDump)); } else { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)); } } } setup(); for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } EXPECT_EQ(0x2, receiveDataStatus); isrPacketWatch(); EXPECT_EQ(0x0, receiveDataStatus); EXPECT_EQ(0x0080, command); loop(); // dispatch StopADCDataDump loop(); } TEST(UART, StopADCDataDump_By_SPIReset) { EXPECT_CALL(packetWatchTimer, attach(_, _)).Times(AnyNumber()); EXPECT_CALL(uart, attach(_, NewJapanRadio::Serial::RxIrq)) .WillRepeatedly(Invoke(_attach)); adcDataBuffer.SetDataLength(16); adcDataBuffer.allocatedSize = 16; adcDataBuffer.adcDataBuffer[0] = 0x1234; adcDataBuffer.adcDataBuffer[1] = 0x5678; adcDataBuffer.adcDataBuffer[2] = 0x9ABC; adcDataBuffer.adcDataBuffer[3] = 0xDEF1; adcDataBuffer.adcDataBuffer[4] = 0x1234; adcDataBuffer.adcDataBuffer[5] = 0x5678; adcDataBuffer.adcDataBuffer[6] = 0x9ABC; adcDataBuffer.adcDataBuffer[7] = 0xDEF1; adcDataBuffer.adcDataBuffer[8] = 0x1234; adcDataBuffer.adcDataBuffer[9] = 0x5678; adcDataBuffer.adcDataBuffer[10] = 0x9ABC; adcDataBuffer.adcDataBuffer[11] = 0xDEF1; adcDataBuffer.adcDataBuffer[12] = 0x1234; adcDataBuffer.adcDataBuffer[13] = 0x5678; adcDataBuffer.adcDataBuffer[14] = 0x9ABC; adcDataBuffer.adcDataBuffer[15] = 0xDEF1; { InSequence s; for (int i = 0; i < (PACKET_SIZE+1)*2; i++) { EXPECT_CALL(uart, readable()) .Times(Exactly(2)) .WillOnce(Return(1)) .WillOnce(Return(0)); } } { InSequence s; EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0x7F)); // SPIResetCommand 0 EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0xFF)); // SPIResetCommand 1 EXPECT_CALL(*(dispatcher.spiCommand)->spi, write(0xFF)); // SPIResetCommand 2 } uint8_t cmd1[] = { 0x10, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6F }; uint8_t cmd2[] = { 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEF }; { InSequence s; for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd1[i])); } for (int i = 0; i < PACKET_SIZE+1; i++) { EXPECT_CALL(uart, read()) .WillOnce(Return(cmd2[i])); } } uint8_t res[] = { 0x20, 0x80, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x50, 0x30, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF1, 0x96, 0x30, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF1, 0x96, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDF }; { InSequence s; for (int i = 0; i < (PACKET_SIZE+1)*4; i++) { if (i == 20) { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)) .WillOnce(InvokeWithoutArgs(StopADCDataDump)); } else { EXPECT_CALL(uart, write(res[i])) .Times(Exactly(1)); } } } setup(); for (int i = 0; i < PACKET_SIZE+1; i++) { fpIsrRx(); } EXPECT_EQ(0x2, receiveDataStatus); isrPacketWatch(); EXPECT_EQ(0x0, receiveDataStatus); EXPECT_EQ(0x0080, command); loop(); // dispatch SPIResetCommand loop(); }
32.642807
123
0.573996
NewJapanRadio
4ef3b5c42c10e5060eadccf67795828260d1a368
21,406
cpp
C++
WonderBrush/src/gui/listviews/ListViews.cpp
waddlesplash/WonderBrush-v2
df20b6a43115d02e4606c71f27d0712ac2aebb62
[ "MIT" ]
11
2018-11-10T11:14:11.000Z
2021-12-27T17:17:08.000Z
WonderBrush/src/gui/listviews/ListViews.cpp
waddlesplash/WonderBrush-v2
df20b6a43115d02e4606c71f27d0712ac2aebb62
[ "MIT" ]
27
2018-11-11T00:06:25.000Z
2021-06-24T06:43:38.000Z
WonderBrush/src/gui/listviews/ListViews.cpp
waddlesplash/WonderBrush-v2
df20b6a43115d02e4606c71f27d0712ac2aebb62
[ "MIT" ]
7
2018-11-10T20:32:49.000Z
2021-03-15T18:03:42.000Z
// ListViews.cpp #include <stdio.h> #include <malloc.h> #include <Bitmap.h> #include <Cursor.h> #include <Entry.h> #include <MessageRunner.h> #include <Messenger.h> #include <ScrollBar.h> #include <ScrollView.h> #include <String.h> #include <Window.h> #include "cursors.h" #include "ListViews.h" #define MAX_DRAG_HEIGHT 200.0 #define ALPHA 170 #define TEXT_OFFSET 5.0 enum { MSG_TICK = 'tick', }; // SimpleItem class SimpleItem::SimpleItem( const char *name ) : BStringItem( name ) { } SimpleItem::~SimpleItem() { } // SimpleItem::DrawItem void SimpleItem::Draw(BView *owner, BRect frame, uint32 flags) { DrawBackground(owner, frame, flags); // label owner->SetHighColor( 0, 0, 0, 255 ); font_height fh; owner->GetFontHeight( &fh ); const char* text = Text(); BString truncatedString( text ); owner->TruncateString( &truncatedString, B_TRUNCATE_MIDDLE, frame.Width() - TEXT_OFFSET - 4.0 ); float height = frame.Height(); float textHeight = fh.ascent + fh.descent; BPoint textPoint; textPoint.x = frame.left + TEXT_OFFSET; textPoint.y = frame.top + ceilf(height / 2.0 - textHeight / 2.0 + fh.ascent); owner->DrawString(truncatedString.String(), textPoint); } // SimpleItem::DrawBackground void SimpleItem::DrawBackground(BView *owner, BRect frame, uint32 flags) { // stroke a blue frame around the item if it's focused if (flags & FLAGS_FOCUSED) { owner->SetLowColor(ui_color(B_KEYBOARD_NAVIGATION_COLOR)); owner->StrokeRect(frame, B_SOLID_LOW); frame.InsetBy(1.0, 1.0); } // figure out bg-color rgb_color color = (rgb_color){ 255, 255, 255, 255 }; if ( flags & FLAGS_TINTED_LINE ) color = tint_color( color, 1.06 ); // background if ( IsSelected() ) color = tint_color( color, B_DARKEN_2_TINT ); owner->SetLowColor( color ); owner->FillRect( frame, B_SOLID_LOW ); } // DragSortableListView class DragSortableListView::DragSortableListView(BRect frame, const char* name, list_view_type type, uint32 resizingMode, uint32 flags) : BListView(frame, name, type, resizingMode, flags), fDropRect(0.0, 0.0, -1.0, -1.0), fMouseWheelFilter(NULL), fScrollPulse(NULL), fDropIndex(-1), fLastClickedItem(NULL), fScrollView(NULL), fDragCommand(B_SIMPLE_DATA), fFocusedIndex(-1) { SetViewColor(B_TRANSPARENT_32_BIT); } DragSortableListView::~DragSortableListView() { // delete fMouseWheelFilter; delete fScrollPulse; } // AttachedToWindow void DragSortableListView::AttachedToWindow() { if (!fMouseWheelFilter) fMouseWheelFilter = new MouseWheelFilter(this); Window()->AddCommonFilter(fMouseWheelFilter); BListView::AttachedToWindow(); // work arround a bug in BListView BRect bounds = Bounds(); BListView::FrameResized(bounds.Width(), bounds.Height()); } // DetachedFromWindow void DragSortableListView::DetachedFromWindow() { // Window()->RemoveCommonFilter(fMouseWheelFilter); } // FrameResized void DragSortableListView::FrameResized(float width, float height) { BListView::FrameResized(width, height); } /* // MakeFocus void DragSortableListView::MakeFocus(bool focused) { if (focused != IsFocus()) { Invalidate(); BListView::MakeFocus(focused); } } */ // Draw void DragSortableListView::Draw( BRect updateRect ) { int32 firstIndex = IndexOf(updateRect.LeftTop()); int32 lastIndex = IndexOf(updateRect.RightBottom()); if (firstIndex >= 0) { if (lastIndex < firstIndex) lastIndex = CountItems() - 1; // update rect contains items BRect r = updateRect; for (int32 i = firstIndex; i <= lastIndex; i++) { r = ItemFrame(i); DrawListItem(this, i, r); } updateRect.top = r.bottom + 1.0; if (updateRect.IsValid()) { SetLowColor(255, 255, 255, 255); FillRect(updateRect, B_SOLID_LOW); } } else { SetLowColor(255, 255, 255, 255); FillRect(updateRect, B_SOLID_LOW); } // drop anticipation indication if (fDropRect.IsValid()) { SetHighColor(255, 0, 0, 255); StrokeRect(fDropRect); } /* // focus indication if (IsFocus()) { SetHighColor(ui_color(B_KEYBOARD_NAVIGATION_COLOR)); StrokeRect(Bounds()); }*/ } // ScrollTo void DragSortableListView::ScrollTo(BPoint where) { uint32 buttons; BPoint point; GetMouse(&point, &buttons, false); uint32 transit = Bounds().Contains(point) ? B_INSIDE_VIEW : B_OUTSIDE_VIEW; MouseMoved(point, transit, &fDragMessageCopy); BListView::ScrollTo(where); } // TargetedByScrollView void DragSortableListView::TargetedByScrollView(BScrollView* scrollView) { fScrollView = scrollView; BListView::TargetedByScrollView(scrollView); } // InitiateDrag bool DragSortableListView::InitiateDrag( BPoint point, int32 index, bool ) { // supress drag&drop while an item is focused if (fFocusedIndex >= 0) return false; bool success = false; BListItem* item = ItemAt( CurrentSelection( 0 ) ); if ( !item ) { // workarround a timing problem Select( index ); item = ItemAt( index ); } if ( item ) { // create drag message BMessage msg( fDragCommand ); MakeDragMessage( &msg ); // figure out drag rect float width = Bounds().Width(); BRect dragRect(0.0, 0.0, width, -1.0); // figure out, how many items fit into our bitmap int32 numItems; bool fade = false; for (numItems = 0; BListItem* item = ItemAt( CurrentSelection( numItems ) ); numItems++) { dragRect.bottom += ceilf( item->Height() ) + 1.0; if ( dragRect.Height() > MAX_DRAG_HEIGHT ) { fade = true; dragRect.bottom = MAX_DRAG_HEIGHT; numItems++; break; } } BBitmap* dragBitmap = new BBitmap( dragRect, B_RGB32, true ); if ( dragBitmap && dragBitmap->IsValid() ) { if ( BView *v = new BView( dragBitmap->Bounds(), "helper", B_FOLLOW_NONE, B_WILL_DRAW ) ) { dragBitmap->AddChild( v ); dragBitmap->Lock(); BRect itemBounds( dragRect) ; itemBounds.bottom = 0.0; // let all selected items, that fit into our drag_bitmap, draw for ( int32 i = 0; i < numItems; i++ ) { int32 index = CurrentSelection( i ); BListItem* item = ItemAt( index ); itemBounds.bottom = itemBounds.top + ceilf( item->Height() ); if ( itemBounds.bottom > dragRect.bottom ) itemBounds.bottom = dragRect.bottom; DrawListItem( v, index, itemBounds ); itemBounds.top = itemBounds.bottom + 1.0; } // make a black frame arround the edge v->SetHighColor( 0, 0, 0, 255 ); v->StrokeRect( v->Bounds() ); v->Sync(); uint8 *bits = (uint8 *)dragBitmap->Bits(); int32 height = (int32)dragBitmap->Bounds().Height() + 1; int32 width = (int32)dragBitmap->Bounds().Width() + 1; int32 bpr = dragBitmap->BytesPerRow(); if (fade) { for ( int32 y = 0; y < height - ALPHA / 2; y++, bits += bpr ) { uint8 *line = bits + 3; for (uint8 *end = line + 4 * width; line < end; line += 4) *line = ALPHA; } for ( int32 y = height - ALPHA / 2; y < height; y++, bits += bpr ) { uint8 *line = bits + 3; for (uint8 *end = line + 4 * width; line < end; line += 4) *line = (height - y) << 1; } } else { for ( int32 y = 0; y < height; y++, bits += bpr ) { uint8 *line = bits + 3; for (uint8 *end = line + 4 * width; line < end; line += 4) *line = ALPHA; } } dragBitmap->Unlock(); } } else { delete dragBitmap; dragBitmap = NULL; } if (dragBitmap) DragMessage( &msg, dragBitmap, B_OP_ALPHA, BPoint( 0.0, 0.0 ) ); else DragMessage( &msg, dragRect.OffsetToCopy( point ), this ); _SetDragMessage(&msg); success = true; } return success; } // WindowActivated void DragSortableListView::WindowActivated( bool active ) { // workarround for buggy focus indication of BScrollView if ( BView* view = Parent() ) view->Invalidate(); } // MessageReceived void DragSortableListView::MessageReceived(BMessage* message) { if (message->what == fDragCommand) { DragSortableListView *list = NULL; if ( message->FindPointer( "list", (void **)&list ) == B_OK && list == this ) { int32 count = CountItems(); if ( fDropIndex < 0 || fDropIndex > count ) fDropIndex = count; BList items; int32 index; for ( int32 i = 0; message->FindInt32( "index", i, &index ) == B_OK; i++ ) if ( BListItem* item = ItemAt(index) ) items.AddItem( (void*)item ); if ( items.CountItems() > 0 ) { if ( modifiers() & B_SHIFT_KEY ) CopyItems( items, fDropIndex ); else MoveItems( items, fDropIndex ); } fDropIndex = -1; } } else { switch ( message->what ) { case MSG_TICK: { float scrollV = 0.0; BRect rect(Bounds()); BPoint point; uint32 buttons; GetMouse(&point, &buttons, false); if (rect.Contains(point)) { // calculate the vertical scrolling offset float hotDist = rect.Height() * SCROLL_AREA; if (point.y > rect.bottom - hotDist) scrollV = hotDist - (rect.bottom - point.y); else if (point.y < rect.top + hotDist) scrollV = (point.y - rect.top) - hotDist; } // scroll if (scrollV != 0.0 && fScrollView) { if (BScrollBar* scrollBar = fScrollView->ScrollBar(B_VERTICAL)) { float value = scrollBar->Value(); scrollBar->SetValue(scrollBar->Value() + scrollV); if (scrollBar->Value() != value) { // update mouse position uint32 buttons; BPoint point; GetMouse(&point, &buttons, false); uint32 transit = Bounds().Contains(point) ? B_INSIDE_VIEW : B_OUTSIDE_VIEW; MouseMoved(point, transit, &fDragMessageCopy); } } } break; } // case B_MODIFIERS_CHANGED: // ModifiersChanged(); // break; case B_MOUSE_WHEEL_CHANGED: { BListView::MessageReceived( message ); BPoint point; uint32 buttons; GetMouse(&point, &buttons, false); uint32 transit = Bounds().Contains(point) ? B_INSIDE_VIEW : B_OUTSIDE_VIEW; MouseMoved(point, transit, &fDragMessageCopy); break; } default: BListView::MessageReceived( message ); break; } } } // KeyDown void DragSortableListView::KeyDown( const char* bytes, int32 numBytes ) { if ( numBytes < 1 ) return; if ( ( bytes[0] == B_BACKSPACE ) || ( bytes[0] == B_DELETE ) ) RemoveSelected(); BListView::KeyDown( bytes, numBytes ); } // MouseDown void DragSortableListView::MouseDown( BPoint where ) { int32 clicks = 1; uint32 buttons = 0; Window()->CurrentMessage()->FindInt32("clicks", &clicks); Window()->CurrentMessage()->FindInt32("buttons", (int32*)&buttons); int32 clickedIndex = -1; for (int32 i = 0; BListItem* item = ItemAt(i); i++) { if (ItemFrame(i).Contains(where)) { if (clicks == 2) { // only do something if user clicked the same item twice if (fLastClickedItem == item) DoubleClicked(i); } else { // remember last clicked item fLastClickedItem = item; } clickedIndex = i; break; } } if (clickedIndex == -1) fLastClickedItem = NULL; BListItem* item = ItemAt(clickedIndex); if (ListType() == B_MULTIPLE_SELECTION_LIST && item && (buttons & B_SECONDARY_MOUSE_BUTTON)) { if (item->IsSelected()) Deselect(clickedIndex); else Select(clickedIndex, true); } else { BListView::MouseDown(where); } } // MouseMoved void DragSortableListView::MouseMoved(BPoint where, uint32 transit, const BMessage *msg) { if (msg && AcceptDragMessage(msg)) { switch (transit) { case B_ENTERED_VIEW: case B_INSIDE_VIEW: { // remember drag message // this is needed to react on modifier changes _SetDragMessage(msg); // set drop target through virtual function SetDropTargetRect(msg, where); // go into autoscrolling mode BRect r = Bounds(); r.InsetBy(0.0, r.Height() * SCROLL_AREA); SetAutoScrolling(!r.Contains(where)); break; } case B_EXITED_VIEW: // forget drag message _SetDragMessage(NULL); SetAutoScrolling(false); // fall through case B_OUTSIDE_VIEW: _RemoveDropAnticipationRect(); break; } } else { _RemoveDropAnticipationRect(); BListView::MouseMoved(where, transit, msg); _SetDragMessage(NULL); SetAutoScrolling(false); BCursor cursor(B_HAND_CURSOR); SetViewCursor(&cursor, true); } fLastMousePos = where; } // MouseUp void DragSortableListView::MouseUp( BPoint where ) { // remove drop mark _SetDropAnticipationRect( BRect( 0.0, 0.0, -1.0, -1.0 ) ); SetAutoScrolling(false); // be sure to forget drag message _SetDragMessage(NULL); BListView::MouseUp( where ); BCursor cursor(B_HAND_CURSOR); SetViewCursor(&cursor, true); } // DrawItem void DragSortableListView::DrawItem( BListItem *item, BRect itemFrame, bool complete ) { DrawListItem( this, IndexOf( item ), itemFrame ); /* if (IsFocus()) { SetHighColor(ui_color(B_KEYBOARD_NAVIGATION_COLOR)); StrokeRect(Bounds()); }*/ } // MouseWheelChanged bool DragSortableListView::MouseWheelChanged(float x, float y) { BPoint where; uint32 buttons; GetMouse(&where, &buttons, false); if (Bounds().Contains(where)) return true; else return false; } // SetDragCommand void DragSortableListView::SetDragCommand(uint32 command) { fDragCommand = command; } // ModifiersChaned void DragSortableListView::ModifiersChanged() { SetDropTargetRect(&fDragMessageCopy, fLastMousePos); } // SetItemFocused void DragSortableListView::SetItemFocused(int32 index) { InvalidateItem(fFocusedIndex); InvalidateItem(index); fFocusedIndex = index; } // AcceptDragMessage bool DragSortableListView::AcceptDragMessage(const BMessage* message) const { return message->what == fDragCommand; } // SetDropTargetRect void DragSortableListView::SetDropTargetRect(const BMessage* message, BPoint where) { if (AcceptDragMessage(message)) { bool copy = modifiers() & B_SHIFT_KEY; bool replaceAll = !message->HasPointer("list") && !copy; BRect r = Bounds(); if (replaceAll) { r.bottom--; // compensate for scrollbar offset _SetDropAnticipationRect(r); fDropIndex = -1; } else { // offset where by half of item height r = ItemFrame(0); where.y += r.Height() / 2.0; int32 index = IndexOf(where); if (index < 0) index = CountItems(); _SetDropIndex(index); const uchar* cursorData = copy ? kCopyCursor : B_HAND_CURSOR; BCursor cursor(cursorData); SetViewCursor(&cursor, true); } } } // SetAutoScrolling void DragSortableListView::SetAutoScrolling(bool enable) { if (fScrollPulse && enable) return; if (enable) { BMessenger messenger(this, Window()); BMessage message(MSG_TICK); fScrollPulse = new BMessageRunner(messenger, &message, 40000LL); } else { delete fScrollPulse; fScrollPulse = NULL; } } // DoesAutoScrolling bool DragSortableListView::DoesAutoScrolling() const { return fScrollPulse; } // ScrollTo void DragSortableListView::ScrollTo(int32 index) { if (index < 0) index = 0; if (index >= CountItems()) index = CountItems() - 1; if (BListItem* item = ItemAt(index)) { BRect itemFrame = ItemFrame(index); BRect bounds = Bounds(); if (itemFrame.top < bounds.top) { ScrollTo(itemFrame.LeftTop()); } else if (itemFrame.bottom > bounds.bottom) { ScrollTo(BPoint(0.0, itemFrame.bottom - bounds.Height())); } } } // MoveItems void DragSortableListView::MoveItems( BList& items, int32 index ) { DeselectAll(); // we remove the items while we look at them, the insertion index is decreased // when the items index is lower, so that we insert at the right spot after // removal BList removedItems; int32 count = items.CountItems(); for ( int32 i = 0; i < count; i++ ) { BListItem* item = (BListItem*)items.ItemAt( i ); int32 removeIndex = IndexOf( item ); if ( RemoveItem( item ) && removedItems.AddItem( (void*)item ) ) { if ( removeIndex < index ) index--; } // else ??? -> blow up } for ( int32 i = 0; BListItem* item = (BListItem*)removedItems.ItemAt( i ); i++ ) { if ( AddItem( item, index ) ) { // after we're done, the newly inserted items will be selected Select( index, true ); // next items will be inserted after this one index++; } else delete item; } } // CopyItems void DragSortableListView::CopyItems( BList& items, int32 index ) { DeselectAll(); // by inserting the items after we copied all items first, we avoid // cloning an item we already inserted and messing everything up // in other words, don't touch the list before we know which items // need to be cloned BList clonedItems; int32 count = items.CountItems(); for ( int32 i = 0; i < count; i++ ) { BListItem* item = CloneItem( IndexOf( (BListItem*)items.ItemAt( i ) ) ); if ( item && !clonedItems.AddItem( (void*)item ) ) delete item; } for ( int32 i = 0; BListItem* item = (BListItem*)clonedItems.ItemAt( i ); i++ ) { if ( AddItem( item, index ) ) { // after we're done, the newly inserted items will be selected Select( index, true ); // next items will be inserted after this one index++; } else delete item; } } // RemoveItemList void DragSortableListView::RemoveItemList( BList& items ) { int32 count = items.CountItems(); for ( int32 i = 0; i < count; i++ ) { BListItem* item = (BListItem*)items.ItemAt( i ); if ( RemoveItem( item ) ) delete item; } } // RemoveSelected void DragSortableListView::RemoveSelected() { // if (fFocusedIndex >= 0) // return; BList items; for ( int32 i = 0; BListItem* item = ItemAt( CurrentSelection( i ) ); i++ ) items.AddItem( (void*)item ); RemoveItemList( items ); } // CountSelectedItems int32 DragSortableListView::CountSelectedItems() const { int32 count = 0; while ( CurrentSelection( count ) >= 0 ) count++; return count; } // SelectAll void DragSortableListView::SelectAll() { Select(0, CountItems() - 1); } // DeleteItem bool DragSortableListView::DeleteItem(int32 index) { BListItem* item = ItemAt(index); if (item && RemoveItem(item)) { delete item; return true; } return false; } // _SetDropAnticipationRect void DragSortableListView::_SetDropAnticipationRect(BRect r) { if (fDropRect != r) { if (fDropRect.IsValid()) Invalidate(fDropRect); fDropRect = r; if (fDropRect.IsValid()) Invalidate(fDropRect); } } // _SetDropIndex void DragSortableListView::_SetDropIndex(int32 index) { if (fDropIndex != index) { fDropIndex = index; if (fDropIndex >= 0) { int32 count = CountItems(); if (fDropIndex == count) { BRect r; if (BListItem* item = ItemAt(count - 1)) { r = ItemFrame(count - 1); r.top = r.bottom; r.bottom = r.top + 1.0; } else { r = Bounds(); r.bottom--; // compensate for scrollbars moved slightly out of window } _SetDropAnticipationRect(r); } else { BRect r = ItemFrame(fDropIndex); r.top--; r.bottom = r.top + 1.0; _SetDropAnticipationRect(r); } } } } // _RemoveDropAnticipationRect void DragSortableListView::_RemoveDropAnticipationRect() { _SetDropAnticipationRect(BRect(0.0, 0.0, -1.0, -1.0)); // _SetDropIndex(-1); } // _SetDragMessage void DragSortableListView::_SetDragMessage(const BMessage* message) { if (message) fDragMessageCopy = *message; else fDragMessageCopy.what = 0; } // SimpleListView class SimpleListView::SimpleListView( BRect frame, BMessage* selectionChangeMessage ) : DragSortableListView( frame, "playlist listview", B_MULTIPLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW | B_NAVIGABLE | B_FRAME_EVENTS | B_FULL_UPDATE_ON_RESIZE ), fSelectionChangeMessage( selectionChangeMessage ) { } // SimpleListView class SimpleListView::SimpleListView( BRect frame, const char* name, BMessage* selectionChangeMessage, list_view_type type, uint32 resizingMode, uint32 flags ) : DragSortableListView( frame, name, type, resizingMode, flags ), fSelectionChangeMessage( selectionChangeMessage ) { } // destructor SimpleListView::~SimpleListView() { delete fSelectionChangeMessage; } // layoutprefs minimax SimpleListView::layoutprefs() { mpm.mini.x = 30.0; mpm.maxi.x = 10000.0; mpm.mini.y = 50.0; mpm.maxi.y = 10000.0; mpm.weight = 1.0; return mpm; } // layout BRect SimpleListView::layout(BRect frame) { MoveTo(frame.LeftTop()); ResizeTo(frame.Width(), frame.Height()); return Frame(); } // MessageReceived void SimpleListView::MessageReceived( BMessage* message) { switch ( message->what ) { default: DragSortableListView::MessageReceived( message ); break; } } // SelectionChanged void SimpleListView::SelectionChanged() { BLooper* looper = Looper(); if (fSelectionChangeMessage && looper) { BMessage message(*fSelectionChangeMessage); looper->PostMessage(&message); } } // CloneItem BListItem* SimpleListView::CloneItem(int32 atIndex) const { BListItem* clone = NULL; if (SimpleItem* item = dynamic_cast<SimpleItem*>(ItemAt(atIndex))) clone = new SimpleItem(item->Text()); return clone; } // DrawListItem void SimpleListView::DrawListItem(BView* owner, int32 index, BRect frame) const { if (SimpleItem* item = dynamic_cast<SimpleItem*>(ItemAt(index))) { uint32 flags = FLAGS_NONE; if (index == fFocusedIndex) flags |= FLAGS_FOCUSED; if (index % 2) flags |= FLAGS_TINTED_LINE; item->Draw(owner, frame, flags); } } // MakeDragMessage void SimpleListView::MakeDragMessage(BMessage* message) const { if (message) { message->AddPointer( "list", (void*)dynamic_cast<const DragSortableListView*>(this)); int32 index; for (int32 i = 0; (index = CurrentSelection(i)) >= 0; i++) message->AddInt32( "index", index ); } }
23.705426
94
0.674437
waddlesplash
4efbe771379047c03250c09e4ebd4a9f154e18b8
10,823
cpp
C++
Engine/Interface/UITextureManager.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
1
2022-02-14T15:46:44.000Z
2022-02-14T15:46:44.000Z
Engine/Interface/UITextureManager.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
null
null
null
Engine/Interface/UITextureManager.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
2
2022-01-10T22:17:06.000Z
2022-01-17T09:34:08.000Z
#include "stdh.h" #include <Engine/Interface/UITextureManager.h> #include <Engine/Interface/UIManager.h> #include <Engine/Help/DefineHelp.h> // ---------------------------------------------------------------------------- // Name : CUIFontTextureManager() // Desc : Constructor // ---------------------------------------------------------------------------- CUIFontTextureManager::CUIFontTextureManager() { // Font texture for( INDEX iTex = 0; iTex < FONT_MAX; iTex++ ) m_aptdFont[iTex] = NULL; memset(m_aFontWidthThai,0,sizeof(int[6][16])); } // ---------------------------------------------------------------------------- // Name : ~CUITextTextureManager() // Desc : Destructor // ---------------------------------------------------------------------------- CUIFontTextureManager::~CUIFontTextureManager() { Destroy(); } // ---------------------------------------------------------------------------- // Name : Create() // Desc : // ---------------------------------------------------------------------------- void CUIFontTextureManager::Create() { extern INDEX g_iCountry; INDEX iTex; CTString strFullPath; CTString strDirectory = "Local\\"; strDirectory += DefHelp::getNationPostfix(g_iCountry, true); strDirectory += "\\"; CTString strFileName; switch( g_iCountry ) { case KOREA: { m_nLanguage = FONT_KOREAN; for( iTex = 0; iTex < TEXCT_FONT_KOREAN; iTex++ ) { strFileName.PrintF( "FontKorean%d.tex", iTex ); strFullPath = strDirectory + strFileName; m_aptdFont[iTex] = _pTextureStock->Obtain_t( strFullPath ); } m_nFontTextureCount = TEXCT_FONT_KOREAN; m_nFontSpacing = 0; m_nLineSpacing = 1; } break; case THAILAND: { m_nLanguage = FONT_THAILAND; for( iTex = 0; iTex < TEXCT_FONT_THAILAND; iTex++ ) { //test 050910 strFileName="FontThailand0.tex"; strFullPath = strDirectory + strFileName; m_aptdFont[iTex] = _pTextureStock->Obtain_t( strFullPath ); } m_nFontTextureCount = TEXCT_FONT_THAILAND; m_nFontSpacing = 1; m_nLineSpacing = 2; // Size of font texture m_nFontTexWidth = m_aptdFont[0]->GetPixWidth(); m_nFontTexHeight = m_aptdFont[0]->GetPixHeight(); // Font information m_nFontWidth = 6; m_nFontWidth2Byte = 12; m_nFontHeight = 12; m_nLineHeight = m_nFontHeight + m_nLineSpacing; // wooss 059030 for non-fixed font int fontWidthThai[6][16]={ 6, 7, 7, 8, 7, 7, 8, 5, 6, 7, 8, 9, 10, 10, 7, 7, 6, 10, 10, 10, 7, 7, 7, 8, 6, 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 5, 6, 7, 7, 5, 8, 10, 8, 7, 9, 7, 8, 6, 5, 7, 5, 9, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 3, 6, 5, 5, 6, 5, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 10, 10, 7, 9, 9, 9, 7, 12, 6, 6, 6, 6 }; memcpy(m_aFontWidthThai,fontWidthThai,sizeof(fontWidthThai)); return; } break; case USA: case ENGLAND: { m_nLanguage = FONT_CHINESE_T; for( iTex = 0; iTex < TEXCT_FONT_USA; iTex++ ) { //strFileName.PrintF( "FontUSA%d.tex", iTex); strFileName.PrintF( "FontChineseT%d.tex", iTex ); strFullPath = strDirectory + strFileName; m_aptdFont[iTex] = _pTextureStock->Obtain_t( strFullPath ); } m_nFontTextureCount = TEXCT_FONT_USA; m_nFontSpacing = 0; m_nLineSpacing = 2; } break; case BRAZIL: { m_nLanguage = FONT_PROTUGES; for( iTex = 0; iTex < TEXCT_FONT_BRZ; iTex++ ) { strFileName.PrintF( "FontBrazil%d.tex", iTex ); strFullPath = strDirectory + strFileName; m_aptdFont[iTex] = _pTextureStock->Obtain_t( strFullPath ); } m_nFontTextureCount = TEXCT_FONT_BRZ; m_nFontSpacing = 0; m_nLineSpacing = 2; } break; case GERMANY: { m_nLanguage = FONT_GERMAN; for( iTex = 0; iTex < TEXCT_FONT_GERMAN; iTex++ ) { strFileName.PrintF( "FontGerman%d.tex", iTex ); strFullPath = strDirectory + strFileName; m_aptdFont[iTex] = _pTextureStock->Obtain_t( strFullPath ); } m_nFontTextureCount = TEXCT_FONT_GERMAN; m_nFontSpacing = 0; m_nLineSpacing = 2; } break; case RUSSIA: { m_nLanguage = FONT_RUSSIAN; for( iTex = 0; iTex < TEXCT_FONT_RUSSIAN; iTex++ ) { strFileName.PrintF( "FontRussia%d.tex", iTex ); strFullPath = strDirectory + strFileName; m_aptdFont[iTex] = _pTextureStock->Obtain_t( strFullPath ); } m_nFontTextureCount = TEXCT_FONT_RUSSIAN; m_nFontSpacing = 0; m_nLineSpacing = 2; } break; case SPAIN://FRANCE_SPAIN_CLOSEBETA_NA_20081124 { m_nLanguage = FONT_SPAIN; for (iTex = 0; iTex < TEXCT_FONT_SPAIN; iTex++) { strFileName.PrintF("FontSpain%d.tex", iTex); strFullPath = strDirectory + strFileName; m_aptdFont[iTex] = _pTextureStock->Obtain_t(strFullPath); } m_nFontTextureCount = TEXCT_FONT_SPAIN; m_nFontSpacing = 0; m_nLineSpacing = 2; } break; case FRANCE: { m_nLanguage = FONT_FRANCE; for (iTex = 0; iTex < TEXCT_FONT_FRANCE; iTex++) { strFileName.PrintF("FontFrance%d.tex", iTex); strFullPath = strDirectory + strFileName; m_aptdFont[iTex] = _pTextureStock->Obtain_t(strFullPath); } m_nFontTextureCount = TEXCT_FONT_FRANCE; m_nFontSpacing = 0; m_nLineSpacing = 2; } break; case POLAND: { m_nLanguage = FONT_POLAND; for (iTex = 0; iTex < TEXCT_FONT_POLAND; iTex++) { strFileName.PrintF("FontPOLAND%d.tex", iTex); strFullPath = strDirectory + strFileName; m_aptdFont[iTex] = _pTextureStock->Obtain_t(strFullPath); } m_nFontTextureCount = TEXCT_FONT_POLAND; m_nFontSpacing = 0; m_nLineSpacing = 2; } break; case MEXICO: { m_nLanguage = FONT_MEXICO; for (iTex = 0; iTex < TEXCT_FONT_MEXICO; iTex++) { strFileName.PrintF("FontMEXICO%d.tex", iTex); strFullPath = strDirectory + strFileName; m_aptdFont[iTex] = _pTextureStock->Obtain_t(strFullPath); } m_nFontTextureCount = TEXCT_FONT_MEXICO; m_nFontSpacing = 0; m_nLineSpacing = 2; } break; case ITALY: { m_nLanguage = FONT_ITALY; for (iTex = 0; iTex < TEXCT_FONT_ITALY; iTex++) { strFileName.PrintF("FontITALY%d.tex", iTex); strFullPath = strDirectory + strFileName; m_aptdFont[iTex] = _pTextureStock->Obtain_t(strFullPath); } m_nFontTextureCount = TEXCT_FONT_ITALY; m_nFontSpacing = 0; m_nLineSpacing = 2; } break; } // Size of font texture m_nFontTexWidth = m_aptdFont[0]->GetPixWidth(); m_nFontTexHeight = m_aptdFont[0]->GetPixHeight(); // Font information m_nFontWidth = 6; m_nFontWidth2Byte = 12; m_nFontHeight = 12; m_nLineHeight = m_nFontHeight + m_nLineSpacing; } // ---------------------------------------------------------------------------- // Name : Destroy() // Desc : // ---------------------------------------------------------------------------- void CUIFontTextureManager::Destroy() { // Font texture for( INDEX iTex = 0; iTex < FONT_MAX; iTex++ ) { if( m_aptdFont[iTex] != NULL ) { _pTextureStock->Release( m_aptdFont[iTex] ); m_aptdFont[iTex] = NULL; } } } // ---------------------------------------------------------------------------- // Name : CUIButtonTextureManager() // Desc : Constructor // ---------------------------------------------------------------------------- CUIButtonTextureManager::CUIButtonTextureManager() { m_aptdButton.resize(UBET_TYPE_MAX); } // ---------------------------------------------------------------------------- // Name : ~CUIButtonTextureManager() // Desc : Destructor // ---------------------------------------------------------------------------- CUIButtonTextureManager::~CUIButtonTextureManager() { Destroy(); } // ---------------------------------------------------------------------------- // Name : Create() // Desc : // ---------------------------------------------------------------------------- void CUIButtonTextureManager::Create() { INDEX iTex; CTString strFullPath; CTString strDirectory = CTString( "Data\\Interface\\" ); CTString strFileName; CTextureData* tmp = NULL; // Skill texture { vecTexData& vec_ = m_aptdButton[UBET_SKILL]; for( iTex = 0; iTex < TEXCT_SKILL; iTex++ ) { strFileName.PrintF( "SkillBtn%d.tex", iTex ); strFullPath = strDirectory + strFileName; tmp = _pTextureStock->Obtain_t( strFullPath ); vec_.push_back(tmp); } for( iTex = 0; iTex < TEXCT_SKILL; iTex++ ) { strFileName.PrintF( "SkillBtnD%d.tex", iTex ); strFullPath = strDirectory + strFileName; tmp = _pTextureStock->Obtain_t( strFullPath ); vec_.push_back(tmp); } } // Action texture { vecTexData& vec_ = m_aptdButton[UBET_ACTION]; for( iTex = 0; iTex < TEXCT_ACTION; iTex++ ) { strFileName.PrintF( "ActionBtn%d.tex", iTex ); strFullPath = strDirectory + strFileName; tmp = _pTextureStock->Obtain_t( strFullPath ); vec_.push_back(tmp); } } // Item texture { vecTexData& vec_ = m_aptdButton[UBET_ITEM]; for( iTex = 0; iTex < TEXCT_ITEM; iTex++ ) { strFileName.PrintF( "ItemBtn%d.tex", iTex ); strFullPath = strDirectory + strFileName; tmp = _pTextureStock->Obtain_t( strFullPath ); vec_.push_back(tmp); } } // Quest texture { vecTexData& vec_ = m_aptdButton[UBET_QUEST]; for( iTex = 0; iTex < TEXCT_QUEST; iTex++ ) { strFileName.PrintF( "QuestBtn%d.tex", iTex ); strFullPath = strDirectory + strFileName; tmp = _pTextureStock->Obtain_t( strFullPath ); vec_.push_back(tmp); } } // Event texture { vecTexData& vec_ = m_aptdButton[UBET_EVENT]; for( iTex = 0; iTex < TEXCT_EVENT; iTex++ ) { strFileName.PrintF( "EventBtn%d.tex", iTex ); strFullPath = strDirectory + strFileName; tmp = _pTextureStock->Obtain_t( strFullPath ); vec_.push_back(tmp); } } // Remission texture { vecTexData& vec_ = m_aptdButton[UBET_REMISSION]; for( iTex = 0; iTex < TEXCT_REMISSION; iTex++ ) { strFileName.PrintF( "RemissionBtn%d.tex", iTex ); strFullPath = strDirectory + strFileName; tmp = _pTextureStock->Obtain_t( strFullPath ); vec_.push_back(tmp); } } // MissionCase texture { vecTexData& vec_ = m_aptdButton[UBET_COMBO]; for( iTex = 0; iTex < TEXCT_COMBO; iTex++ ) { strFileName.PrintF( "ComboBtn%d.tex", iTex ); strFullPath = strDirectory + strFileName; tmp = _pTextureStock->Obtain_t( strFullPath ); vec_.push_back(tmp); } } } // ---------------------------------------------------------------------------- // Name : Destroy() // Desc : // ---------------------------------------------------------------------------- void CUIButtonTextureManager::Destroy() { int i, nMax = m_aptdButton.size(); int iChild, nChildMax = 0; CTextureData* pData = NULL; for (i = 0; i < nMax; ++i) { vecTexData& vec_ = m_aptdButton[i]; nChildMax = vec_.size(); for (iChild = 0; iChild < nChildMax; ++iChild) { pData = vec_[iChild]; STOCK_RELEASE(pData); } } }
25.111369
79
0.583849
openlastchaos
4efe07d47b67960cc0d7ebd883582a768ecb5828
1,230
hpp
C++
include/range/v3/utility/tagged_tuple.hpp
seewpx/range-v3
8527a9741518dd61082bc3e2139aed8ecb5da4f6
[ "MIT" ]
3,436
2015-01-05T14:27:21.000Z
2022-03-31T07:56:04.000Z
include/range/v3/utility/tagged_tuple.hpp
seewpx/range-v3
8527a9741518dd61082bc3e2139aed8ecb5da4f6
[ "MIT" ]
1,197
2015-01-01T21:27:32.000Z
2022-03-29T17:46:09.000Z
include/range/v3/utility/tagged_tuple.hpp
seewpx/range-v3
8527a9741518dd61082bc3e2139aed8ecb5da4f6
[ "MIT" ]
490
2015-01-04T00:18:04.000Z
2022-03-25T18:59:43.000Z
/// \file // Range v3 library // // Copyright Eric Niebler 2013-present // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/ericniebler/range-v3 #ifndef RANGES_V3_UTILITY_TAGGED_TUPLE_HPP #define RANGES_V3_UTILITY_TAGGED_TUPLE_HPP #include <tuple> #include <range/v3/range_fwd.hpp> #include <range/v3/utility/tagged_pair.hpp> #include <range/v3/detail/prologue.hpp> RANGES_DIAGNOSTIC_PUSH RANGES_DIAGNOSTIC_IGNORE_DEPRECATED_DECLARATIONS namespace ranges { template<typename... Ts> using tagged_tuple RANGES_DEPRECATED("ranges::tagged_tuple is deprecated.") = tagged<std::tuple<detail::tag_elem<Ts>...>, detail::tag_spec<Ts>...>; template<typename... Tags, typename... Ts> RANGES_DEPRECATED("ranges::make_tagged_tuple is deprecated.") constexpr tagged_tuple<Tags(bind_element_t<Ts>)...> make_tagged_tuple(Ts &&... ts) { return tagged_tuple<Tags(bind_element_t<Ts>)...>{static_cast<Ts &&>(ts)...}; } } // namespace ranges RANGES_DIAGNOSTIC_POP #include <range/v3/detail/epilogue.hpp> #endif
26.73913
86
0.73252
seewpx
4efedbb5006b17af465fa191aaf495036daebabd
1,169
cpp
C++
gecode/string/tests/str_ex10.cpp
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
1
2021-05-26T13:27:00.000Z
2021-05-26T13:27:00.000Z
gecode/string/tests/str_ex10.cpp
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
null
null
null
gecode/string/tests/str_ex10.cpp
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
null
null
null
#include <gecode/string.hh> #include <gecode/driver.hh> using namespace Gecode; using namespace String; class StringOptions : public Options { public: StringOptions(const char* s): Options(s) { } }; class Ex10 : public Script { StringVarArray string_vars; public: static bool unsat; Ex10(Ex10& s): Script(s) { string_vars.update(*this, s.string_vars); } virtual Space* copy() { return new Ex10(*this); } Ex10(const StringOptions& so): Script(so) { // Variables. StringVar x(*this, NSIntSet('A', 'B'), 0, 10000); StringVar y(*this, NSIntSet('A', 'B'), 0, 10000); StringVarArgs e1, e2; e1 << x << StringVar(*this, "A") << x; e2 << x << StringVar(*this, "B") << x; gconcat(*this, e1, y); gconcat(*this, e2, y); StringVarArgs sva; sva << x << y; string_vars = StringVarArray(*this, sva); blockmin_lllm(*this, string_vars); } virtual void print(std::ostream& os) const { unsat = false; } }; bool Ex10::unsat = true; int main() { StringOptions opt("*** Ex10 ***"); opt.solutions(1); Script::run<Ex10, DFS, StringOptions>(opt); assert (Ex10::unsat); return 0; }
18.854839
53
0.612489
ramadini
4eff64c9ba8fd2cc001e1de93b7726fefc97ede3
542
hpp
C++
include/mango/image/quantize.hpp
JessyDL/mango
8db9632fb2e81ba0a13129d3d19019688fab7bd1
[ "Zlib" ]
null
null
null
include/mango/image/quantize.hpp
JessyDL/mango
8db9632fb2e81ba0a13129d3d19019688fab7bd1
[ "Zlib" ]
null
null
null
include/mango/image/quantize.hpp
JessyDL/mango
8db9632fb2e81ba0a13129d3d19019688fab7bd1
[ "Zlib" ]
null
null
null
/* MANGO Multimedia Development Platform Copyright (C) 2012-2019 Twilight Finland 3D Oy Ltd. All rights reserved. */ #pragma once #include "format.hpp" #include "surface.hpp" namespace mango { namespace image { struct ColorQuantizeOptions { float quality = 0.90f; bool dithering = true; }; struct ColorQuantizer { Palette palette; void quantize(const Surface& dest, const Surface& source, const ColorQuantizeOptions& options); }; } // namespace image } // namespace mango
19.357143
103
0.666052
JessyDL
f60116f898c6d861145323ac507b1906e7d7b73f
7,506
cpp
C++
Plugins/AdvKitPlugin/Source/AdvKitRuntime/Private/Environment/BuildModules/AdvKitBuildModule_Ledge_Tightspace.cpp
crimsonstrife/velorum-defunct
1a6e1eab9057293da2aa045eff021d069df54c5e
[ "CC0-1.0" ]
null
null
null
Plugins/AdvKitPlugin/Source/AdvKitRuntime/Private/Environment/BuildModules/AdvKitBuildModule_Ledge_Tightspace.cpp
crimsonstrife/velorum-defunct
1a6e1eab9057293da2aa045eff021d069df54c5e
[ "CC0-1.0" ]
null
null
null
Plugins/AdvKitPlugin/Source/AdvKitRuntime/Private/Environment/BuildModules/AdvKitBuildModule_Ledge_Tightspace.cpp
crimsonstrife/velorum-defunct
1a6e1eab9057293da2aa045eff021d069df54c5e
[ "CC0-1.0" ]
null
null
null
// Copyright 2015 Pascal Krabbe #include "AdvKitRuntime.h" #include "AdvKitTypes.h" #include "Player/AdvKitCharacter.h" #include "Environment/Zones/AdvKitZoneLine.h" #include "Environment/BuildModules/AdvKitBuildModule_Ledge_Tightspace.h" #include "Environment/Transitions/AdvKitTransitionComponentPoint.h" #include "Environment/Transitions/AdvKitTransitionComponentArea.h" bool UAdvKitBuildModule_Ledge_Tightspace::CanCreateTransitionsFor_Implementation(TSubclassOf<AAdvKitCharacter> ForCharacterClass, AAdvKitZone* ForZone) { //Cannot create transitions on non line zone object if (!ForZone->IsA(AAdvKitZoneLine::StaticClass())) { return false; } //Only valid for these movement modes if (ForZone->GetPhysics() != EAdvKitMovementMode::ClimbingLedge && ForZone->GetPhysics() != EAdvKitMovementMode::WalkingTightspace) { return false; } //Need to know character's movement properties to build transitions auto MovementProps = GetCharacterMovementProperties(ForCharacterClass); if (!MovementProps) { return false; } //No need to create transitions for a character that cannot use them return MovementProps->bCanClimbLedge && MovementProps->bCanWalkTightSpace; } bool UAdvKitBuildModule_Ledge_Tightspace::GatherPotentialTargetZones_Implementation(TSubclassOf<AAdvKitCharacter> ForCharacterClass, AAdvKitZone* ForZone, TArray<AAdvKitZone*>& OutZones) { OutZones.Empty(); auto LineZone = Cast<AAdvKitZoneLine>(ForZone); check(LineZone); //Check for zones that almost or actually touch one another FVector CharacterHalfExtent = GetCharacterHalfExtent(ForCharacterClass, LineZone); TArray<AAdvKitZone*> TempZones; if (!OverlapForCloseZones(LineZone, LineZone->GetZoneStartWorld(), LineZone->GetZoneEndWorld(), CharacterHalfExtent.Z * 2, TempZones)) { return false; } //Filter targets for (auto Zone : TempZones) { //Only works for lines if (!Zone->IsA(AAdvKitZoneLine::StaticClass())) { continue; } //Cannot create transitions from tight space to anything other than ledge if (LineZone->GetPhysics() == EAdvKitMovementMode::WalkingTightspace && Zone->GetPhysics() == EAdvKitMovementMode::ClimbingLedge) { OutZones.Add(Zone); continue; } //Cannot create transitions from ledge to anything other than tight space if (LineZone->GetPhysics() == EAdvKitMovementMode::ClimbingLedge && Zone->GetPhysics() == EAdvKitMovementMode::WalkingTightspace) { OutZones.Add(Zone); } } return OutZones.Num() > 0; } bool UAdvKitBuildModule_Ledge_Tightspace::CreateTransitionBetween_Implementation(TSubclassOf<AAdvKitCharacter> ForCharacterClass, AAdvKitZone* SourceZone, AAdvKitZone* TargetZone) { if (SourceZone->GetPhysics() == EAdvKitMovementMode::ClimbingLedge) { return CreateTransitionLedgeToTightSpace(ForCharacterClass, SourceZone, TargetZone); } if (SourceZone->GetPhysics() == EAdvKitMovementMode::WalkingTightspace) { return CreateTransitionTightSpaceToLedge(ForCharacterClass, SourceZone, TargetZone); } return false; } bool UAdvKitBuildModule_Ledge_Tightspace::CreateTransitionLedgeToTightSpace(TSubclassOf<AAdvKitCharacter> ForCharacterClass, AAdvKitZone* Ledge, AAdvKitZone* TightSpace) { auto LedgeLine = Cast<AAdvKitZoneLine>(Ledge); auto TightSpaceLine = Cast<AAdvKitZoneLine>(TightSpace); FVector CharacterHalfExtent = GetCharacterHalfExtent(ForCharacterClass, LedgeLine); FVector OtherCharacterHalfExtent = GetCharacterHalfExtent(ForCharacterClass, TightSpaceLine); //Zones have to be parallel float Dot = FVector::DotProduct(TightSpaceLine->GetActorForwardVector(), LedgeLine->GetActorForwardVector()); if (Dot < (1.0f - ErrorMarginDot)) { return false; } //Project zones onto each other FVector OtherMin = TightSpaceLine->ConstrainPositionToZone(LedgeLine->GetZoneStartWorld(), OtherCharacterHalfExtent); FVector OtherMax = TightSpaceLine->ConstrainPositionToZone(LedgeLine->GetZoneEndWorld(), OtherCharacterHalfExtent); FVector SelfMin = LedgeLine->ConstrainPositionToZone(OtherMin, CharacterHalfExtent); FVector SelfMax = LedgeLine->ConstrainPositionToZone(OtherMax, CharacterHalfExtent); OtherMin = TightSpaceLine->ConstrainPositionToZone(SelfMin, OtherCharacterHalfExtent); OtherMax = TightSpaceLine->ConstrainPositionToZone(SelfMax, OtherCharacterHalfExtent); UAdvKitTransitionComponent* Transition = nullptr; //Area overlapping if (SelfMin != SelfMax) { Transition = CreateTransitionArea("ToTightSpace", LedgeLine, SelfMin, OtherMin, SelfMax, OtherMax, ForCharacterClass, TightSpaceLine->GetPhysics(), TightSpaceLine); } //Only a single point overlapping else if (SelfMin == SelfMax) { Transition = CreateTransitionPoint("ToTightSpace", LedgeLine, SelfMin, OtherMin, ForCharacterClass, TightSpaceLine->GetPhysics(), TightSpaceLine); } if (!Transition) { return false; } //Transition from ledge to tight space should be up vertically Transition->TransitionDirection = FVector::UpVector; Transition->bNeedsJump = true; return true; } bool UAdvKitBuildModule_Ledge_Tightspace::CreateTransitionTightSpaceToLedge(TSubclassOf<AAdvKitCharacter> ForCharacterClass, AAdvKitZone* TightSpace, AAdvKitZone* Ledge) { auto LedgeLine = Cast<AAdvKitZoneLine>(Ledge); auto TightSpaceLine = Cast<AAdvKitZoneLine>(TightSpace); FVector CharacterHalfExtent = GetCharacterHalfExtent(ForCharacterClass, TightSpaceLine); FVector OtherCharacterHalfExtent = GetCharacterHalfExtent(ForCharacterClass, LedgeLine); //Zones have to be parallel float Dot = FVector::DotProduct(TightSpaceLine->GetActorForwardVector(), LedgeLine->GetActorForwardVector()); if (Dot < (1.0f - ErrorMarginDot)) { return false; } //Check if ledge is below tight space FVector ClosestLocationOther = LedgeLine->ConstrainPositionToZone(TightSpaceLine->GetActorLocation(), OtherCharacterHalfExtent); FVector ClosestLocationSelf = TightSpaceLine->ConstrainPositionToZone(ClosestLocationOther, CharacterHalfExtent); FVector LocalLocationOther = TightSpaceLine->GetTransform().InverseTransformPositionNoScale(ClosestLocationOther); FVector LocalLocationSelf = TightSpaceLine->GetTransform().InverseTransformPositionNoScale(ClosestLocationSelf); if (LocalLocationOther.Z >= LocalLocationSelf.Z) { return false; } //Project zones onto each other FVector OtherMin = LedgeLine->ConstrainPositionToZone(TightSpaceLine->GetZoneStartWorld(), OtherCharacterHalfExtent); FVector OtherMax = LedgeLine->ConstrainPositionToZone(TightSpaceLine->GetZoneEndWorld(), OtherCharacterHalfExtent); FVector SelfMin = TightSpaceLine->ConstrainPositionToZone(OtherMin, CharacterHalfExtent); FVector SelfMax = TightSpaceLine->ConstrainPositionToZone(OtherMax, CharacterHalfExtent); OtherMin = LedgeLine->ConstrainPositionToZone(SelfMin, OtherCharacterHalfExtent); OtherMax = LedgeLine->ConstrainPositionToZone(SelfMax, OtherCharacterHalfExtent); UAdvKitTransitionComponent* Transition = nullptr; //Area overlapping if (SelfMin != SelfMax) { Transition = CreateTransitionArea("ToLedge",TightSpaceLine, SelfMin, OtherMin, SelfMax, OtherMax, ForCharacterClass, LedgeLine->GetPhysics(), LedgeLine); } //Only a single point overlapping else if (SelfMin == SelfMax) { Transition = CreateTransitionPoint("ToLedge", TightSpaceLine, SelfMin, OtherMin, ForCharacterClass, LedgeLine->GetPhysics(), LedgeLine); } if (!Transition) { return false; } //Transition from tight space to ledge should be down vertically Transition->TransitionDirection = -FVector::UpVector; return true; }
37.343284
186
0.800693
crimsonstrife
f6123fa6b3077eb7e373405e3b46a8c3782910e2
562
hpp
C++
include/Quasura/Common.hpp
jcoder39/Quasura
f6a8b43620aa77f5488327f0cfe4773b7301bae4
[ "MIT" ]
null
null
null
include/Quasura/Common.hpp
jcoder39/Quasura
f6a8b43620aa77f5488327f0cfe4773b7301bae4
[ "MIT" ]
null
null
null
include/Quasura/Common.hpp
jcoder39/Quasura
f6a8b43620aa77f5488327f0cfe4773b7301bae4
[ "MIT" ]
null
null
null
/* * Common.hpp * * Created by Viacheslav Borisenko * * Copyright (c) 2018 spectrobyte http://spectrobyte.com * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * */ #ifndef QUASURA_COMMON_HPP #define QUASURA_COMMON_HPP #include "Quasura/common/Logger.hpp" #include "Quasura/common/StringGenerator.hpp" #include "Quasura/common/Singleton.hpp" #include "Quasura/common/random/Bag.hpp" #include "Quasura/common/random/Chaos.hpp" #endif //QUASURA_COMMON_HPP
24.434783
65
0.729537
jcoder39
f61a3522035b21de3e09acb93bb718ef63a77de5
1,181
cc
C++
checkcsa.cc
super-mini-shogi/dobutsu
c93425078fe0b07441fce260da1842c60a8b397f
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
checkcsa.cc
super-mini-shogi/dobutsu
c93425078fe0b07441fce260da1842c60a8b397f
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
checkcsa.cc
super-mini-shogi/dobutsu
c93425078fe0b07441fce260da1842c60a8b397f
[ "BSD-2-Clause-FreeBSD" ]
1
2019-12-28T07:44:45.000Z
2019-12-28T07:44:45.000Z
/** * csa形式の棋譜ファイルを読み込んで,それぞれの手の勝敗をチェックする */ #include "allStateTable.h" #include "dobutsu.h" #include "winLoseTable.h" void usage() { std::cerr << "Usage: checkcsa csafile" << std::endl; } int main(int ac, char **ag) { if (ac < 2) { usage(); } vMove moves = readMoveFile(ag[1]); AllStateTable allS("allstates.dat"); WinLoseTable winLose(allS, "winLoss.dat", "winLossCount.dat"); State s; std::cerr << s << std::endl; for (size_t i = 0; i < moves.size(); i++) { vMove ret = s.nextMoves(); int lastwlc; int lastwl = winLose.getWinLose(s, lastwlc); #if 1 for (size_t j = 0; j < ret.size(); j++) { int wlc, wl; wl = winLose.getWinLose(s, ret[j], wlc); std::cerr << j << " : " << ret[j] << ",wl=" << wl << "(" << wlc << ")" << std::endl; } #endif std::cerr << "Move : " << moves[i] << std::endl; int wlc, wl; wl = winLose.getWinLose(s, moves[i], wlc); if (lastwl != -wl) { std::cerr << s << std::endl; std::cerr << i << " : " << moves[i] << " " << -lastwl << " -> " << wl << std::endl; } s.applyMove(moves[i]); // std::cerr << s << std::endl; } }
27.465116
76
0.510584
super-mini-shogi
f61a88b2e0953f9770cd66cea0d3d7921318da9f
10,310
cc
C++
src/vt/vrt/collection/balance/read_lb.cc
rbuch/vt
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
[ "BSD-3-Clause" ]
26
2019-11-26T08:36:15.000Z
2022-02-15T17:13:21.000Z
src/vt/vrt/collection/balance/read_lb.cc
rbuch/vt
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
[ "BSD-3-Clause" ]
1,215
2019-09-09T14:31:33.000Z
2022-03-30T20:20:14.000Z
src/vt/vrt/collection/balance/read_lb.cc
rbuch/vt
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
[ "BSD-3-Clause" ]
12
2019-09-08T00:03:05.000Z
2022-02-23T21:28:35.000Z
/* //@HEADER // ***************************************************************************** // // read_lb.cc // DARMA/vt => Virtual Transport // // Copyright 2019-2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright 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 OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact darma@sandia.gov // // ***************************************************************************** //@HEADER */ #include "vt/config.h" #include "vt/context/context.h" #include "vt/vrt/collection/balance/read_lb.h" #include "vt/vrt/collection/balance/lb_type.h" #include "vt/configs/arguments/app_config.h" #include <sstream> #include <string> #include <fstream> #include <cassert> #include <cctype> #include <cmath> namespace vt { namespace vrt { namespace collection { namespace balance { /*static*/ std::string ReadLBSpec::open_filename_ = {}; /*static*/ typename ReadLBSpec::SpecMapType ReadLBSpec::spec_mod_ = {}; /*static*/ typename ReadLBSpec::SpecMapType ReadLBSpec::spec_exact_ = {}; /*static*/ std::vector<SpecIndex> ReadLBSpec::spec_prec_ = {}; /*static*/ bool ReadLBSpec::read_complete_ = false; /*static*/ bool ReadLBSpec::openSpec(std::string const& filename) { // No-op if no file specified. Can't be used to clear. if (filename.empty()) { return false; } // Ignore attempt to open same spec. if (not open_filename_.empty() and open_filename_ == filename) { return true; } vtAssert( open_filename_.empty(), "Spec already opened. Use clear first to load again." ); // Ensure file can be opened. std::ifstream file(filename); if (not file.good()) { auto str = fmt::format("Unable to open spec file: {}", filename); vtAbort(str); } // Remember loaded file - multiple calls to same file are idempotent. open_filename_ = filename; readFile(filename); return true; } /*static*/ LBType ReadLBSpec::getLB(SpecIndex const& idx) { auto const lb = entry(idx); if (lb) { return lb->getLB(); } else { return LBType::NoLB; } } /*static*/ SpecEntry* ReadLBSpec::entry(SpecIndex const& idx) { // First, search the exact iter spec for this iteration: it has the highest // precedence auto spec_iter = spec_exact_.find(idx); if (spec_iter != spec_exact_.end()) { return &spec_iter->second; } // Second, walk through the spec precedence map for the mod overloads for (auto mod : spec_prec_) { auto iter = spec_mod_.find(mod); if (iter != spec_mod_.end()) { // Check if this mod is applicable to the idx if (idx % mod == 0) { auto iter_mod = spec_mod_.find(mod); if (iter_mod != spec_mod_.end()) { return &iter_mod->second; } } } } // Else, return nullptr---no applicable entry found return nullptr; } int eatWhitespace(std::ifstream& file) { while (not file.eof() and std::isspace(file.peek()) and file.peek() != '\n') { file.get(); } return file.eof() ? 0 : file.peek(); } /*static*/ void ReadLBSpec::readFile(std::string const& filename) { std::ifstream file(filename); vtAssert(file.good(), "must be valid"); while (!file.eof()) { bool is_mod = false; int64_t mod = -1; std::string lb_name; std::vector<std::string> params; int c = eatWhitespace(file); /* * Parse an entry that starts with an LB: "% ..." */ if (static_cast<char>(c) == '%') { is_mod = true; // Eat up the '%', move to next file.get(); c = eatWhitespace(file); } /* * Parse entry starting LB iter/mod: "[%] 10 GreedyLB ..." */ if (std::isdigit(c)) { file >> mod; } c = eatWhitespace(file); /* * Parse the name of the LB: "GreedyLB ..." */ if (std::isalpha(c)) { file >> lb_name; } c = eatWhitespace(file); /* * Parse out all the parameters for the LB: "x=1 y=2 test=3 ..." */ while (file.peek() != '\n' and not file.eof()) { std::string param; file >> param; params.push_back(param); } eatWhitespace(file); while (file.peek() == '\n') { file.get(); } /* * Split params into 'key=value' */ auto const param_map = parseParams(params); /* * Check to make sure we have a valid LB name */ bool valid_lb_found = false; for (auto&& elm : get_lb_names()) { if (lb_name == elm.second) { valid_lb_found = true; } } if (not valid_lb_found) { auto err_msg = fmt::format("Valid LB not found: \"name={}\"\n", lb_name); vtAbort(err_msg); } /* * If the line is specified as a mod '%' or not line is specified (assume * mod 1) */ SpecMapType* map = nullptr; if (is_mod or mod == -1) { if (mod == -1) { mod = 1; } spec_prec_.push_back(mod); map = &spec_mod_; } else { map = &spec_exact_; } if (map->find(mod) != map->end()) { auto err_msg = fmt::format( "Iter {} specified twice: name={}, mod={}\n", mod, lb_name, is_mod ); vtAbort(err_msg); } map->emplace( std::piecewise_construct, std::forward_as_tuple(mod), std::forward_as_tuple(SpecEntry{mod, lb_name, param_map}) ); } read_complete_ = true; } /*static*/ void ReadLBSpec::clear() { read_complete_ = false; open_filename_ = ""; spec_mod_.clear(); spec_exact_.clear(); spec_prec_.clear(); } /*static*/ typename ReadLBSpec::ParamMapType ReadLBSpec::parseParams(std::vector<std::string> params) { ParamMapType param_map; /* * Split params into 'key=value' */ for (auto&& p : params) { if (p == "") { continue; } std::string key, value; bool found = false; for (std::size_t i = 0; i < p.size(); i++) { if (p[i] == '=') { key = p.substr(0, i); value = p.substr(i + 1, p.length() - 1); param_map[key] = value; found = true; } } if (not found) { auto err = fmt::format("LB file reader: could not parse param: \"{}\"", p); vtAbort(err); } } return param_map; } /*static*/ SpecEntry ReadLBSpec::makeSpecFromParams(std::string param_str) { std::istringstream stream(param_str); std::vector<std::string> params; while (not stream.eof()) { std::string param; stream >> param; params.push_back(param); } auto param_map = parseParams(params); return SpecEntry{0, "", param_map}; } auto param_str = []( std::map<std::string,std::string> const& params ) -> std::string { if (params.empty()) { return ""; } std::stringstream ss; ss << " with arguments `"; for (auto const& param : params) { ss << fmt::format("{}={} ", vt::debug::emph(param.first), vt::debug::emph(param.second)); } ss.seekp(-1, ss.cur); ss << '`'; return ss.str(); }; auto excluded_str = [](SpecIndex idx) -> std::string { std::stringstream ss; auto exact_entries = ReadLBSpec::getExactEntries(); auto max_idx = exact_entries.empty() ? 0 : exact_entries.rbegin()->first; for (auto k = 1; k*idx <= max_idx; k++) { auto next_entry = ReadLBSpec::entry(k*idx); if (next_entry != nullptr and next_entry->getIdx() != idx) { ss << fmt::format("{}, ", debug::emph(std::to_string(k*idx))); } } std::string s = ss.str(); return s.empty() ? s : s.substr(0, s.size() - 2); }; /*static*/ std::string ReadLBSpec::toString() { std::stringstream ss; if (open_filename_.empty()) { return "[No LB Spec open]"; } if (not ReadLBSpec::getExactEntries().empty()) { ss << fmt::format("{}\tExact specification lines:\n", vt::debug::vtPre()); } for (auto const& exact_entry : ReadLBSpec::getExactEntries()) { ss << fmt::format("{}\tRun `{}` on phase {}{}", vt::debug::vtPre(), vt::debug::emph(exact_entry.second.getName()), vt::debug::emph(std::to_string(exact_entry.first)), param_str(exact_entry.second.getParams())); ss << '\n'; } if (not ReadLBSpec::getModEntries().empty()) { ss << fmt::format( "{}\tMod (%) specification lines:\n", vt::debug::vtPre() ); } for (auto const& mod_entry : ReadLBSpec::getModEntries()) { ss << fmt::format("{}\tRun `{}` every {} phases{}", vt::debug::vtPre(), vt::debug::emph(mod_entry.second.getName()), vt::debug::emph(std::to_string(mod_entry.first)), param_str(mod_entry.second.getParams())); auto excluded_phases = excluded_str(mod_entry.first); if (not excluded_phases.empty()) { ss << " excluding phases " << excluded_phases; } ss << '\n'; } return ss.str(); } }}}} /* end namespace vt::vrt::collection::balance */
27.789757
81
0.610572
rbuch
f61b9ef994f4a86b570db2d439160792d47021a6
38,946
cpp
C++
Eudora71/Eudora/PaigeStyle.cpp
dusong7/eudora-win
850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2
[ "BSD-3-Clause-Clear" ]
10
2018-05-23T10:43:48.000Z
2021-12-02T17:59:48.000Z
Eudora71/Eudora/PaigeStyle.cpp
dusong7/eudora-win
850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2
[ "BSD-3-Clause-Clear" ]
1
2019-03-19T03:56:36.000Z
2021-05-26T18:36:03.000Z
Eudora71/Eudora/PaigeStyle.cpp
evilneuro/eudora-win
850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2
[ "BSD-3-Clause-Clear" ]
11
2018-05-23T10:43:53.000Z
2021-12-27T15:42:58.000Z
// PaigeStyle.cpp : implementation file // // Copyright (c) 1997-2001 by QUALCOMM, Incorporated /* Copyright (c) 2016, Computer History Museum All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) 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 Computer History Museum nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. 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 "stdafx.h" #include "resource.h" #include "defprocs.h" #include "pgutils.h" #include "paige.h" #include "pgtraps.h" #include "machine.h" #include "pggrafx.h" #include "PaigeStyle.h" #include "pghtmdef.h" #include "PgStuffBucket.h" #include "font.h" #include "rs.h" #include "machine.h" // high-level style interface #include "pghlevel.h" #include "moodwatch.h" #include "pgcompmsgview.h" #include "PGDEFSTL.H" #include "PgStyleUtils.h" //class PgCompMsgView; #include "DebugNewHelpers.h" #include "BossProtector.h" #define EXCERPT_OFFSET 8 #define VBAR_LINEWIDTH 3 #define SEPARATOR_LINEWIDTH 3 #define LIST_OFFSET 16 #define ID_UNDERLINE_DISTANCE 4 //3 drawing pixel and one blank // pattern bmps for making brushes CBitmap g_bmpSpell, g_bmpHWord, g_bmpNonHWord; // hard-coded heights for the brushes (a pox on win95!) enum { kSpellBrushHeight = 3, kHWordBrushHeight = 4, kNonHWordBrushHeight = 3 }; // protected one-time init of moodwatch drawing globals void PGS_InitDrawGlobals() { static bool initialized = false; if ( !initialized ) { assert( (HBITMAP)g_bmpHWord == 0 ); assert( (HBITMAP)g_bmpNonHWord == 0 ); assert( (HBITMAP)g_bmpSpell == 0 ); // TODO: match background color to document g_bmpHWord.LoadBitmap( IDB_CHILIBRUSH ); g_bmpNonHWord.LoadBitmap( IDB_NONHWORDBRUSH ); g_bmpSpell.LoadBitmap( IDB_SPELLBRUSH ); initialized = true; } } void PGS_DrawUnderline( HDC hDC, POINT* ptStart, int length, underline_type kind ) { HPEN underline_pen = NULL, old_pen = NULL, second_underline_pen = NULL; COLORREF pen_color = 0, second_pen_color = 0; const int pen_size = 1; const int pen_type = PS_SOLID; if (length <= 0) return; if ( kind == kSpellUnderline ) { pen_color = RGB(255,0,0); } else if (kind == kBPUnderline ) { pen_color = CBossProtector::GetBPColorCode(); } else if ( kind == kHWordUnderline ) { pen_color = RGB(128,0,0);//maroon second_pen_color = RGB(0,255,0); } else if ( kind == kNonHWordUnderline ) { pen_color = RGB(0,255,0); } else { // oops, looks like somebody's screwing up---for safety's sake we'll // draw the spell underline, but just use the current text color. assert(0); pen_color = RGB(255,0,0); } underline_pen = CreatePen(pen_type, pen_size, pen_color); if ( kind == kHWordUnderline ) second_underline_pen = CreatePen(pen_type, pen_size, second_pen_color); old_pen = (HPEN) SelectObject(hDC, underline_pen); //first row of underline int nIntervals = length/ID_UNDERLINE_DISTANCE; int nRemainder = length%ID_UNDERLINE_DISTANCE; MoveToEx(hDC, ptStart->x, ++ptStart->y, NULL); int distance = ptStart->x; int pen_toggle = 0; for(int j =0; j<nIntervals; j++) { distance +=(ID_UNDERLINE_DISTANCE-2); LineTo(hDC,distance,ptStart->y); distance+=2; MoveToEx(hDC, distance, ptStart->y, NULL); //toggle the colors if it h word if ( kind == kHWordUnderline ) { if(pen_toggle==0) { SelectObject(hDC, second_underline_pen); pen_toggle = 1; } else { SelectObject(hDC, underline_pen); pen_toggle = 0; } } } if (nRemainder > 1) LineTo(hDC,distance+nRemainder-2,ptStart->y); //// ///second row of underline if ( kind == kHWordUnderline ) SelectObject(hDC, underline_pen); nIntervals = (length-2)/ID_UNDERLINE_DISTANCE; nRemainder = (length-2)%ID_UNDERLINE_DISTANCE; ptStart->y+=1; MoveToEx(hDC, ptStart->x+2, ptStart->y, NULL); distance = ptStart->x+2; pen_toggle=1; for(j =0; j<nIntervals; j++) { distance +=(ID_UNDERLINE_DISTANCE-2); LineTo(hDC,distance,ptStart->y); distance+=2; MoveToEx(hDC, distance, ptStart->y, NULL); } if (nRemainder > 1) LineTo(hDC,distance+nRemainder-2,ptStart->y); /////////////////////////////// SelectObject(hDC, old_pen); DeleteObject(underline_pen); if ( kind == kHWordUnderline ) DeleteObject(second_underline_pen); } PG_PASCAL (void) pgDrawSpellUnderline (paige_rec_ptr pg, Point from_pt, short distance ) { // No misspelling underlines when printing if ((pg->flags & PRINT_MODE_BIT) != 0) return; HDC hdc = pgGetPlatformDevice(pg->globals->current_port); CPoint pt( from_pt.h, from_pt.v ); PGS_DrawUnderline( hdc, &pt, distance, kSpellUnderline ); pgReleasePlatformDevice(pg->globals->current_port); } static PG_PASCAL (void) spell_draw_proc(paige_rec_ptr pg, style_walk_ptr walker, pg_byte_ptr data, pg_short_t offset, pg_short_t length, draw_points_ptr draw_position, long extra, short draw_mode) { Point start_pt; Point end_pt; pgDrawProc( pg, walker, data, offset, length, draw_position, extra, draw_mode); if (walker->cur_style->user_id & PAIGE_STYLE_USER_ID_MISSPELLED) { start_pt.h = pgLongToShort(draw_position->from.h); start_pt.v = pgLongToShort(draw_position->from.v); end_pt.h = pgLongToShort(draw_position->to.h); end_pt.v = pgLongToShort(draw_position->to.v); pgDrawSpellUnderline(pg, start_pt, (short)(end_pt.h-start_pt.h+1)); } } static PG_PASCAL (void) draw_h_word_proc(paige_rec_ptr pg, style_walk_ptr walker, pg_byte_ptr data, pg_short_t offset, pg_short_t length, draw_points_ptr draw_position, long extra, short draw_mode) { pgDrawProc( pg, walker, data, offset, length, draw_position, extra, draw_mode); PgStuffBucket* pSB = (PgStuffBucket*) pg->user_refcon; CWnd* pwnd = pSB->pWndOwner; bool bDrawBadWords = false; // UGLY: should really do this with type/subtype "stuff"; leave it for now. if ( pwnd && pwnd->IsKindOf(RUNTIME_CLASS(PgCompMsgView))) { if((((PgCompMsgView*)pwnd)->GetMoodScore() >1)&& (((PgCompMsgView*)pwnd)->GetMoodScore() <5)) { bDrawBadWords = true; } } if ( (walker->cur_style->user_id & PAIGE_STYLE_USER_ID_BAD_MOOD_WORD) && bDrawBadWords ) { HDC hdc = pgGetPlatformDevice(pg->globals->current_port); Point start_pt; Point end_pt; start_pt.h = pgLongToShort(draw_position->from.h); start_pt.v = pgLongToShort(draw_position->from.v); end_pt.h = pgLongToShort(draw_position->to.h); end_pt.v = pgLongToShort(draw_position->to.v); CPoint pt( start_pt.h, start_pt.v ); int distance = end_pt.h - start_pt.h + 1; PGS_DrawUnderline( hdc, &pt, distance, kHWordUnderline ); pgReleasePlatformDevice(pg->globals->current_port); } } static PG_PASCAL (void) draw_non_h_word_proc(paige_rec_ptr pg, style_walk_ptr walker, pg_byte_ptr data, pg_short_t offset, pg_short_t length, draw_points_ptr draw_position, long extra, short draw_mode) { pgDrawProc( pg, walker, data, offset, length, draw_position, extra, draw_mode); PgStuffBucket* pSB = (PgStuffBucket*) pg->user_refcon; CWnd* pwnd = pSB->pWndOwner; bool bDrawBadWords = false; // UGLY: should really do this with type/subtype "stuff"; leave it for now. if ( pwnd && pwnd->IsKindOf(RUNTIME_CLASS(PgCompMsgView))) { if((((PgCompMsgView*)pwnd)->GetMoodScore() >1)&& (((PgCompMsgView*)pwnd)->GetMoodScore() <5)) { bDrawBadWords = true; } } if ( walker->cur_style->user_id & PAIGE_STYLE_USER_ID_BAD_MOOD_WORD && bDrawBadWords ) { HDC hdc = pgGetPlatformDevice(pg->globals->current_port); Point start_pt; Point end_pt; start_pt.h = pgLongToShort(draw_position->from.h); start_pt.v = pgLongToShort(draw_position->from.v); end_pt.h = pgLongToShort(draw_position->to.h); end_pt.v = pgLongToShort(draw_position->to.v); CPoint pt( start_pt.h, start_pt.v ); int distance = end_pt.h - start_pt.h + 1; PGS_DrawUnderline( hdc, &pt, distance, kNonHWordUnderline ); pgReleasePlatformDevice(pg->globals->current_port); } } static PG_PASCAL (void) spell_init_proc (paige_rec_ptr pg, style_info_ptr style, font_info_ptr font) { // register short distance; pgStyleInitProc(pg, style, font); // distance = 0; //style->styles[boxed_var]; // style->ascent += distance; // style->descent += distance; style->class_bits |= NO_SMART_DRAW_BIT; } static PG_PASCAL(void) excerpt_glitter_proc ( paige_rec_ptr pg, style_walk_ptr walker, long line_number, long par_number, text_block_ptr block, point_start_ptr first_line, point_start_ptr last_line, point_start_ptr previous_first, point_start_ptr previous_last, co_ordinate_ptr offset_extra, rectangle_ptr vis_rect, short call_verb ) { co_ordinate begin, end; COLORREF lineColor; if (call_verb == glitter_post_bitmap_draw) return; color_value bk_color; bk_color = pg->bk_color; if ( GetIniShort(IDS_INI_USE_SYSCOLORS) ) lineColor = GetSysColor( COLOR_BTNSHADOW ); else lineColor = pgGetGrayScale(&bk_color, -54); //BORDER_DARK_SCALE); begin.v = first_line->bounds.top_left.v + offset_extra->v; end.v = first_line->bounds.bot_right.v + offset_extra->v - VBAR_LINEWIDTH; begin.h = end.h = EXCERPT_OFFSET + offset_extra->h; long n = walker->cur_par_style->user_data; while ( n-- > 0 ) { pgLineDraw(pg->globals->current_port, &begin, &end, lineColor, VBAR_LINEWIDTH); begin.h += EXCERPT_OFFSET; } } static PG_PASCAL(void) signed_glitter_proc ( paige_rec_ptr pg, style_walk_ptr walker, long line_number, long par_number, text_block_ptr block, point_start_ptr first_line, point_start_ptr last_line, point_start_ptr previous_first, point_start_ptr previous_last, co_ordinate_ptr offset_extra, rectangle_ptr vis_rect, short call_verb ) { co_ordinate begin, end; COLORREF pen_color; if (call_verb == glitter_post_bitmap_draw) return; color_value bk_color; bk_color = pg->bk_color; pen_color = 0x000000FF; pen_color |= pg->port.palette_select; begin.v = first_line->bounds.top_left.v + offset_extra->v; end.v = first_line->bounds.bot_right.v + offset_extra->v - VBAR_LINEWIDTH; begin.h = end.h = EXCERPT_OFFSET + offset_extra->h; pgLineDraw(pg->globals->current_port, &begin, &end, pen_color, VBAR_LINEWIDTH); } PG_PASCAL (void) DrawSigSeparator( paige_rec_ptr pg, Point fromPt, short lineLength, long lineWidth ) { // no sig separator when printing [?] if ( (pg->flags & PRINT_MODE_BIT) != 0 ) return; HDC hdc = pgGetPlatformDevice(pg->globals->current_port); // draw the "lit" part of the line COLORREF penColor = GetSysColor( COLOR_BTNFACE ); penColor |= pg->port.palette_select; int penType = PS_SOLID; long penSize = lineWidth - 1; pgScaleLong( pg->scale_factor.scale, 0, &penSize ); if ( !penSize ) penSize = 1; HPEN pen = CreatePen( penType, (short)penSize, penColor ); HPEN oldPen = (HPEN) SelectObject( hdc, pen ); MoveToEx( hdc, fromPt.h, fromPt.v, NULL ); LineTo( hdc, fromPt.h + lineLength, fromPt.v ); SelectObject( hdc, oldPen ); DeleteObject( pen ); // now give it a shadow---source from the top fromPt.v = (short)(fromPt.v - (lineWidth - 1)); penColor = GetSysColor( COLOR_BTNSHADOW ); penColor |= pg->port.palette_select; penType = PS_SOLID; penSize = 1; pen = CreatePen( penType, (short)penSize, penColor ); oldPen = (HPEN) SelectObject( hdc, pen ); MoveToEx( hdc, fromPt.h, fromPt.v, NULL ); LineTo( hdc, fromPt.h + lineLength, fromPt.v ); SelectObject( hdc, oldPen ); DeleteObject( pen ); pgReleasePlatformDevice(pg->globals->current_port); } // how much space between the sig and body? inline long sig_spacer() { return GetMessageFont().CellHeight(); } static PG_PASCAL(void) signature_glitter_proc ( paige_rec_ptr pg, style_walk_ptr walker, long line_number, long par_number, text_block_ptr block, point_start_ptr first_line, point_start_ptr last_line, point_start_ptr previous_first, point_start_ptr previous_last, co_ordinate_ptr offset_extra, rectangle_ptr vis_rect, short call_verb ) { if (call_verb == glitter_post_bitmap_draw) return; if ( first_line->flags & NEW_PAR_BIT ) { select_pair sp; sp.begin = sp.end = first_line->offset - 1; if ( !CPaigeStyle(pg->doc_pg).IsSignature(&sp) ) { long sigExtra = sig_spacer() / 2; rectangle visBounds; pgAreaBounds( pg->doc_pg, NULL, &visBounds ); long lineLength = visBounds.bot_right.h - visBounds.top_left.h; Point pt; pt.h = (short)(first_line->bounds.top_left.h - 1 + offset_extra->h); pt.v = (short)(first_line->bounds.top_left.v + sigExtra + offset_extra->v); DrawSigSeparator( pg, pt, (short)(lineLength + 1), SEPARATOR_LINEWIDTH ); } } } extern "C" PG_PASCAL(void) PGS_MainGlitterProc ( paige_rec_ptr pg, style_walk_ptr walker, long line_number, long par_number, text_block_ptr block, point_start_ptr first_line, point_start_ptr last_line, point_start_ptr previous_first, point_start_ptr previous_last, co_ordinate_ptr offset_extra, rectangle_ptr vis_rect, short call_verb ) { // first call the default paige impl---for par borders and tables pgLineGlitterProc( pg, walker, line_number, par_number, block, first_line, last_line, previous_first, previous_last, offset_extra, vis_rect, call_verb ); // // Now pass off to our own procs for a little extra fluff. Currently, we are doing one // of these to the exclusion of the other, but that's just a signed vs. excerpt thing. // Do as many as ya want---as long as everybody respects everybody else's space! // par_info_ptr parInfo = walker->cur_par_style; if ( parInfo->user_id & PAIGE_FORMAT_USER_ID_EXCERPT ) { excerpt_glitter_proc( pg, walker, line_number, par_number, block, first_line, last_line, previous_first, previous_last, offset_extra, vis_rect, call_verb ); } else if ( parInfo->user_id & PAIGE_FORMAT_USER_ID_SIGNED ) { signed_glitter_proc( pg, walker, line_number, par_number, block, first_line, last_line, previous_first, previous_last, offset_extra, vis_rect, call_verb ); } else if ( parInfo->user_id & PAIGE_FORMAT_USER_ID_SIGNATURE ) { signature_glitter_proc( pg, walker, line_number, par_number, block, first_line, last_line, previous_first, previous_last, offset_extra, vis_rect, call_verb ); } } extern "C" PG_PASCAL(void) PGS_MainLineAdjustProc ( paige_rec_ptr pg, pg_measure_ptr measure, point_start_ptr starts, pg_short_t num_starts, rectangle_ptr line_fit, par_info_ptr par_format ) { ASSERT(par_format); // We can't do anything without a valid par_format if (!par_format) return; // Detect the beginning or end of any HTML list type (bullets, indents, etc.) bool bIsOffsetItemChange = false; style_walk_ptr walker = measure->styles; long nLineStartOffset = measure->block->begin + starts->offset; if ( walker && walker->par_base && (starts->flags & NEW_PAR_BIT) && (nLineStartOffset > 0) ) { // We only offset the top, so we only care about paragraphs that have // a previous paragraph (i.e. not the first paragraph) par_info_ptr prev_par_format = pgFindParStyle(pg, nLineStartOffset - 1); if (prev_par_format) { // Check to see if the paragraph formats are different if (prev_par_format != par_format) { long cur_html_bullet = par_format->html_bullet; long prev_html_bullet = prev_par_format->html_bullet; long cur_html_style = par_format->html_style & 0x0000FFFF; long prev_html_style = prev_par_format->html_style & 0x0000FFFF; // It's an offset change if: // * Current item is bulleted and previous item was not bulleted // * Current item is not bulleted and previous item was bulleted // * Current item is a list type (i.e. indented, etc.) and previous item was not a list type // * Current item is not a list type (i.e. indented, etc.) and previous item was a list type bIsOffsetItemChange = ( (cur_html_bullet > 0) && (prev_html_bullet == 0) ) || ( (cur_html_bullet == 0) && (prev_html_bullet > 0) ) || ( (cur_html_style != html_par_normal) && (prev_html_style == html_par_normal) ) || ( (cur_html_style == html_par_normal) && (prev_html_style != html_par_normal) ); } UnuseMemory(pg->par_formats); } // Space HTML list types (e.g. bullets and indented blocks) down by LIST_OFFSET if (bIsOffsetItemChange) par_format->top_extra += LIST_OFFSET; } // first call default paige impl to do a whole lot of nasty-lookin' stuff! pgLineAdjustProc( pg, measure, starts, num_starts, line_fit, par_format ); // The paragraph formats are often shared among multiple paragraphs. If we kept // the offset in place it would incorrectly offset subsequent HTML list items // rather than just offsetting before the first item and after the last item. // Restore top_extra to its previous value. if (bIsOffsetItemChange) par_format->top_extra -= LIST_OFFSET; // not a whole lot to this routine for now. the only thing we adjust at // this point is the first line of an inline sig, by moving it down a // little to create some padding between it and the message body if ( !GetIniShort( IDS_INI_INLINE_SIGNATURE ) ) return; if ( CPaigeStyle::IsSignature(par_format) && starts->flags & NEW_PAR_BIT ) { select_pair sp; sp.begin = sp.end = starts->offset - 1; if ( !CPaigeStyle(pg->doc_pg).IsSignature(&sp) ) { co_ordinate top_left; long sigExtra = sig_spacer(); for ( pg_short_t i = 0; i < num_starts; ++i ) { top_left = starts[i].bounds.top_left; pgOffsetRect( &starts[i].bounds, 0, sigExtra ); starts[i].bounds.top_left = top_left; } top_left = line_fit->top_left; pgOffsetRect( line_fit, 0, sigExtra ); line_fit->top_left = top_left; top_left = measure->actual_rect.top_left; pgOffsetRect( &measure->actual_rect, 0, sigExtra ); measure->actual_rect.top_left = top_left; } } } /////////////////////////////////////////////////////////////////////////////// // CPaigeStyle -- class for handling custom message styles CPaigeStyle::CPaigeStyle(pg_ref pg) { m_paigeRef = pg; } CPaigeStyle::~CPaigeStyle() { return; } // BOG -- code for marking items that need to be spell-checked, in addition // to items done on the fly. the custom style being applied is a "hidden" // style; it differs from the current style only in the `user_id' field. bool CPaigeStyle::SetNeedsScanned( bool bOn, select_pair_ptr pSel ) { style_info mask, info; pgInitStyleMask( &info, 0 ); pgInitStyleMask( &mask, 0 ); //SDSpellTRACE("SetNeedsSpell %d %d.%d\n",bOn,pSel->begin,pSel->end); mask.user_id = -1; mask.class_bits = -1; pgGetStyleInfo( m_paigeRef, pSel, FALSE, &info, &mask ); pgInitStyleMask( &mask, 0 ); mask.user_id = -1; mask.class_bits = -1; // mask.procs.init = (style_init_proc) -1; // mask.procs.draw = (text_draw_proc) -1; // info.procs.init = pgStyleInitProc; // info.procs.draw = pgDrawProc; if ( bOn ) { info.user_id |= PAIGE_STYLE_USER_ID_NEEDSSCANNED; info.user_id &= ~PAIGE_STYLE_USER_ID_MISSPELLED; } else { //info.user_id = 0; if ( !(info.user_id & PAIGE_STYLE_USER_ID_NEEDSSCANNED) ) return false; info.user_id ^= PAIGE_STYLE_USER_ID_NEEDSSCANNED; } // Set the style. If it was misspelled before, we'll have to draw. // If it wasn't misspelled before, there's no reason to draw, because // the needspellcheck style isn't visible anyway. pgSetStyleInfo( m_paigeRef, pSel, &info, &mask, IsMisspelled(pSel) ? (short)best_way : (short)draw_none ); return TRUE; // How useful. It always returns true, no matter what. } // two ways of checking for the "needs spell-check" style. // // the easiest possible check is to set a select_pair to begin=0, end=pgTextSize(...), // and pass it to NeedsSpellCheck( select_pair_ptr ) to return whether the style // exists in the document at all. to find exact text ranges to check, one must use // a style-walker. #if 0 // this is in the header file now static bool CPaigeStyle::NeedsSpellCheck( style_info_ptr pStyle ) { return (pStyle->user_id == PAIGE_STYLE_USER_ID_NEEDSSCANNED); } #endif bool CPaigeStyle::NeedsScanned( select_pair_ptr sel ) { pgInitStyleMask( &m_style, 0 ); pgInitStyleMask( &m_styleMask, 0 ); m_styleMask.user_id = -1; pgGetStyleInfo( m_paigeRef, sel, FALSE, &m_style, &m_styleMask ); return ((m_style.user_id & PAIGE_STYLE_USER_ID_NEEDSSCANNED) && (m_styleMask.user_id != 0)); } bool CPaigeStyle::ApplyBadMoodWord(bool bOn, select_pair_ptr pSel,int nWordType) { style_info mask, info; pgInitStyleMask(&info,0); pgInitStyleMask(&mask,0); //SDSpellTRACE("ApplyMisspelled %d %d.%d\n",bOn,pSel?pSel->begin:-1,pSel?pSel->end:-1); mask.user_id=-1; mask.class_bits = -1; //mask.procs.init = (style_init_proc) -1; mask.procs.draw = (text_draw_proc) -1; pgGetStyleInfo( m_paigeRef, pSel, FALSE, &info, &mask ); pgInitStyleMask(&mask,0); mask.user_id=-1; mask.class_bits = -1; mask.procs.draw = (text_draw_proc) -1; //mask.bot_extra = -1; if ( bOn ) { // make sure the drawing globals are happy PGS_InitDrawGlobals(); info.user_id |= PAIGE_STYLE_USER_ID_BAD_MOOD_WORD; //info.procs.init= spell_init_proc; // BITMAP bm; int brushHeight = 0; if (nWordType == MOOD_H_WORD) { // g_bmpHWord.GetBitmap( &bm ); brushHeight = kHWordBrushHeight; info.procs.draw = draw_h_word_proc; } else if (nWordType == MOOD_NON_H_WORD) { // g_bmpNonHWord.GetBitmap( &bm ); brushHeight = kNonHWordBrushHeight; info.procs.draw = draw_non_h_word_proc; } // info.bot_extra = bm.bmHeight - 1;, //info.bot_extra = brushHeight - 1; } else { if ( !(info.user_id & PAIGE_STYLE_USER_ID_BAD_MOOD_WORD) ) return false; info.user_id ^= PAIGE_STYLE_USER_ID_BAD_MOOD_WORD; //info.user_id=0; //info.procs.init= pgStyleInitProc; info.procs.draw = pgDrawProc; //info.bot_extra = 0; } // all these shenanigans figure out if the window is visible paige_rec_ptr pgRec = (paige_rec_ptr) UseMemory( m_paigeRef ); PgStuffBucket* pSB = (PgStuffBucket*) pgRec->user_refcon; bool isVisible = 0!=(pSB->pWndOwner->GetStyle() & WS_VISIBLE); UnuseMemory( m_paigeRef ); pgSetStyleInfo(m_paigeRef,pSel,&info,&mask, (short)(isVisible? best_way:draw_none)); return TRUE; } bool CPaigeStyle::IsBadMoodWord(style_info_ptr pStyle) { return (pStyle->user_id & PAIGE_STYLE_USER_ID_BAD_MOOD_WORD) != 0; } bool CPaigeStyle::IsBadMoodWord(select_pair_ptr sel) { pgInitStyleMask(&m_style,0); pgInitStyleMask(&m_styleMask,0); // This is how we check if ANYTHING in the selection is misspelled; // fill in the user_id we like, and call pgGSI with TRUE //m_styleMask.user_id = -1; //m_style.user_id = PAIGE_STYLE_USER_ID_BAD_MOOD_WORD; //pgGetStyleInfo(m_paigeRef, sel, TRUE, &m_style, &m_styleMask); // return ( (m_style.user_id & PAIGE_STYLE_USER_ID_BAD_MOOD_WORD ) && (m_styleMask.user_id != 0 ) ); m_styleMask.user_id = -1; pgGetStyleInfo(m_paigeRef, sel, FALSE, &m_style, &m_styleMask); return ((m_style.user_id & PAIGE_STYLE_USER_ID_BAD_MOOD_WORD) != 0); } // end BOG //Wrote following 3 functions while fixing some bug#5874 Hyperlinking Test with spelling errrow causes broken link. //Turns out we don't need this functions at this moment but might be useful in future so doing #if 0. #if 0 bool CPaigeStyle::ApplyURL(bool bOn, select_pair_ptr pSel) { style_info mask, info; pgInitStyleMask(&info,0); pgInitStyleMask(&mask,0); //SDSpellTRACE("ApplyMisspelled %d %d.%d\n",bOn,pSel?pSel->begin:-1,pSel?pSel->end:-1); mask.user_id=-1; mask.class_bits = -1; mask.procs.init = (style_init_proc) -1; mask.procs.draw = (text_draw_proc) -1; if ( bOn ) { info.user_id |= PAIGE_STYLE_USER_ID_URL; info.procs.init= spell_init_proc; info.procs.draw = spell_draw_proc; } else { info.user_id=0; info.procs.init= pgStyleInitProc; info.procs.draw = pgDrawProc; } // all these shenanigans figure out if the window is visible paige_rec_ptr pgRec = (paige_rec_ptr) UseMemory( m_paigeRef ); PgStuffBucket* pSB = (PgStuffBucket*) pgRec->user_refcon; bool isVisible = 0!=(pSB->pWndOwner->GetStyle() & WS_VISIBLE); UnuseMemory( m_paigeRef ); pgSetStyleInfo(m_paigeRef,pSel,&info,&mask, (short)(isVisible? best_way:draw_none)); return TRUE; } bool CPaigeStyle::IsURL(style_info_ptr pStyle) { return (pStyle->user_id & PAIGE_STYLE_USER_ID_URL); } bool CPaigeStyle::IsURL(select_pair_ptr sel) { pgInitStyleMask(&m_style,0); pgInitStyleMask(&m_styleMask,0); // This is how we check if ANYTHING in the selection is misspelled; // fill in the user_id we like, and call pgGSI with TRUE m_style.user_id = PAIGE_STYLE_USER_ID_URL; pgGetStyleInfo(m_paigeRef, sel, TRUE, &m_style, &m_styleMask); return ( (m_style.user_id & PAIGE_STYLE_USER_ID_URL ) && (m_styleMask.user_id != 0 ) ); } #endif bool CPaigeStyle::ApplyMisspelled(bool bOn, select_pair_ptr pSel, bool bRedrawImmediately) { style_info mask, info; pgInitStyleMask(&info,0); pgInitStyleMask(&mask,0); //SDSpellTRACE("ApplyMisspelled %d %d.%d\n",bOn,pSel?pSel->begin:-1,pSel?pSel->end:-1); mask.user_id=-1; mask.class_bits = -1; mask.procs.init = (style_init_proc) -1; mask.procs.draw = (text_draw_proc) -1; pgGetStyleInfo( m_paigeRef, pSel, FALSE, &info, &mask ); pgInitStyleMask(&mask,0); mask.user_id=-1; mask.class_bits = -1; mask.procs.init = (style_init_proc) -1; mask.procs.draw = (text_draw_proc) -1; //mask.bot_extra = -1; if ( bOn ) { // Don't want to mark URLs, bad mood words, or embedded objects as mispelled if ( IsWithinURLRange(pSel)|| IsBadMoodWord(pSel) || info.embed_object ) return false; PGS_InitDrawGlobals(); #if 0 BITMAP bm; g_bmpSpell.GetBitmap( &bm ); #endif info.user_id |= PAIGE_STYLE_USER_ID_MISSPELLED; info.procs.init= spell_init_proc; info.procs.draw = spell_draw_proc; // BOG: the underline gets drawn starting at the last pixel row of // the actual text, so we pad the line for one less pixel. // info.bot_extra = bm.bmHeight - 1; //info.bot_extra = kSpellBrushHeight - 1; } else { info.user_id &= ~PAIGE_STYLE_USER_ID_MISSPELLED; info.procs.init= pgStyleInitProc; info.procs.draw = pgDrawProc; //info.bot_extra = 0; } bool bRedraw = false; if (bRedrawImmediately) { // all these shenanigans figure out if the window is visible paige_rec_ptr pgRec = (paige_rec_ptr) UseMemory( m_paigeRef ); PgStuffBucket* pSB = (PgStuffBucket*) pgRec->user_refcon; bRedraw = ( (pSB->pWndOwner->GetStyle() & WS_VISIBLE) != 0 ); UnuseMemory( m_paigeRef ); } pgSetStyleInfo( m_paigeRef,pSel,&info,&mask, static_cast<short>(bRedraw ? best_way : draw_none) ); return true; } bool CPaigeStyle::IsMisspelled(style_info_ptr pStyle) { return (pStyle->user_id & PAIGE_STYLE_USER_ID_MISSPELLED); } bool CPaigeStyle::IsMisspelled(select_pair_ptr sel) { pgInitStyleMask(&m_style,0); pgInitStyleMask(&m_styleMask,0); // This is how we check if ANYTHING in the selection is misspelled; // fill in the user_id we like, and call pgGSI with TRUE m_style.user_id = PAIGE_STYLE_USER_ID_MISSPELLED; pgGetStyleInfo(m_paigeRef, sel, TRUE, &m_style, &m_styleMask); //SDSpellTRACE("IsMisspelled %d.%d %d\n", sel->begin, sel->end, (m_style.user_id & PAIGE_STYLE_USER_ID_SPELL ) && (m_styleMask.user_id != 0 ) ); return ( (m_style.user_id & PAIGE_STYLE_USER_ID_MISSPELLED ) && (m_styleMask.user_id != 0 ) ); } void CPaigeStyle::ClearMisspellingAndRecheck(select_pair_ptr sel) { select_pair sel2, sel3; //SDSpell{static int n; n++; TRACE("ClearM&R%d %x\n",n,sel);} // Use current selection if no selection given if (sel) sel2 = *sel; else pgGetSelection(m_paigeRef,&sel2.begin,&sel2.end); // mark the whole word for checking sel3 = sel2; pgFindWord(m_paigeRef, sel2.begin, &sel2.begin, &sel2.end, TRUE, FALSE); // if the original range was more than one word, make sure we get it all if (sel3.begin != sel3.end && sel3.end > sel2.end) { pgFindWord(m_paigeRef, sel3.end, &sel3.begin, &sel3.end, TRUE, FALSE); sel2.end = sel3.end; } // Back up until just after a blank character so that we can be sure // that we're marking entire emoticon trigger potentials as needing // to be scanned (otherwise trigger characters are often consider word // breaking characters and so we would incorrectly skip scanning them). sel2.begin = PgScanBackwardsToJustAfterBlank(m_paigeRef, sel2.begin); SetNeedsScanned( TRUE, &sel2 ); #ifndef VOODOO_IS_DEAD // The following is voodoo, pure and simple. // For some reason, this incantation, while it should be // a complete no-op, fixes a big big big performance problem // during typing. Someone should probably figure out why, but that // someone ain't me, at least not now. SD 4/19/99 // all this virgin goat slaying is hard on fonts & styles in the insertion point, so save them style_info oldStyleInfo, oldStyleMask; pgInitStyleMask( &oldStyleInfo, 0 ); pgInitStyleMask( &oldStyleMask, 0 ); pgGetStyleInfo( m_paigeRef, NULL, FALSE, &oldStyleInfo, &oldStyleMask ); // Get the current selection pgGetSelection(m_paigeRef, &sel2.begin, &sel2.end); // first, we get a virgin chicken // Set the selection to just what it was pgSetSelection(m_paigeRef, sel2.begin, sel2.end, 0, FALSE); // then we slit its throat and pour the blood on the fire // now we clean up some of the offal, hoping that it wasn't really the intestines that placate the gods pgInitStyleMask( &oldStyleMask, 0); // clear the mask we just got // restore what we believe is good oldStyleMask.styles[bold_var] = -1; oldStyleMask.styles[italic_var] = -1; oldStyleMask.styles[underline_var] = -1; oldStyleMask.styles[strikeout_var] = -1; oldStyleMask.fg_color.red = 0xFFFF; oldStyleMask.fg_color.green = 0xFFFF; oldStyleMask.fg_color.blue = 0xFFFF; oldStyleMask.bk_color.red = 0xFFFF; oldStyleMask.bk_color.green = 0xFFFF; oldStyleMask.bk_color.blue = 0xFFFF; oldStyleMask.font_index = -1; oldStyleMask.point = -1; //dont restore the bad mood word id oldStyleMask.user_id = -1; oldStyleInfo.user_id &= ~PAIGE_STYLE_USER_ID_BAD_MOOD_WORD; pgSetStyleInfo( m_paigeRef, NULL, &oldStyleInfo, &oldStyleMask, best_way); // Ok, we now return to the rational universe #endif // Make sure the insertion style does not contain misspelling if (IsMisspelled((select_pair_ptr)NULL)) { ApplyMisspelled(FALSE,NULL); } } bool CPaigeStyle::IsExcerpt(par_info_ptr pPar) { return ( pPar->user_id & PAIGE_FORMAT_USER_ID_EXCERPT ); } bool CPaigeStyle::IsExcerpt(select_pair_ptr sel) { pgInitParMask(&m_par,0); pgInitParMask(&m_parMask,0); pgGetParInfo( m_paigeRef, sel, false, &m_par, &m_parMask ); return ( IsExcerpt(&m_par) ); } // // Accepts a currently filled paragraph format structure and // modifies it to the appropriate style. // bool CPaigeStyle::ApplyExcerpt(par_info_ptr info, bool bOn) { if ( bOn ) { info->user_id |= PAIGE_FORMAT_USER_ID_EXCERPT; info->user_data++; info->left_extra = info->user_data * EXCERPT_OFFSET; } else { // If we weren't in an excerpt, then bail if (!(info->user_id & PAIGE_FORMAT_USER_ID_EXCERPT)) return FALSE; info->user_data--; //info->user_data = max(info->user_data,0); info->user_data = (((info->user_data) > (0)) ? (info->user_data) : (0)); info->left_extra = info->user_data * EXCERPT_OFFSET; // If no more exerpt levels then turn excerpting off if ( info->user_data == 0 ) { info->user_id = 0; // Change this to an and/or operation } } return TRUE; } bool CPaigeStyle::SetExcerpt(int n) { pgInitParMask(&m_par,0); pgInitParMask(&m_parMask,0); m_parMask.user_id=-1; m_parMask.user_data=-1; m_parMask.left_extra =-1; pgGetParInfo( m_paigeRef, NULL, false, &m_par, &m_parMask ); if ( n == 0 ) { m_par.user_data = 0; m_par.left_extra = 0; m_par.user_id = 0; // Change this to an and/or operation } else { m_par.user_id |= PAIGE_FORMAT_USER_ID_EXCERPT; m_par.user_data = n; m_par.left_extra = m_par.user_data * EXCERPT_OFFSET; } pgSetParInfo(m_paigeRef,NULL,&m_par,&m_parMask, best_way); return TRUE; } bool CPaigeStyle::IsBullet(select_pair_ptr sel) { pgInitParMask(&m_par,0); pgInitParMask(&m_parMask,0); pgGetParInfo( m_paigeRef, sel, false, &m_par, &m_parMask ); return ( (m_par.class_info & BULLETED_LINE) && (m_par.html_style & html_unordered_list) ); } long CPaigeStyle::GetBulletLevel(select_pair_ptr sel) { long nBulletLevel = 0; if ( IsBullet(sel) ) { // We retrieved information into m_par in IsBullet nBulletLevel = m_par.html_bullet; // We know there's a bullet so make sure that the level is at least 1 if (nBulletLevel <= 0) nBulletLevel = 1; } return nBulletLevel; } bool CPaigeStyle::ApplyBullet(bool bOn) { par_info info, mask; pgInitParMask(&info,0); pgInitParMask(&mask,0); pgGetParInfo( m_paigeRef, NULL, false, &info, &mask ); mask.html_bullet = -1; mask.class_info = -1; mask.indents.left_indent = -1; mask.html_style = -1; if ( bOn ) { info.class_info |= BULLETED_LINE; info.html_bullet = 1; info.indents.left_indent += DEFLIST_INDENT_VALUE; info.html_style = html_unordered_list; } else { info.html_bullet = 0; //max(0,info.html_bullet-2); info.indents.left_indent -= DEFLIST_INDENT_VALUE; if ( !info.html_bullet ) { info.html_style = (info.indents.left_indent >= DEFLIST_INDENT_VALUE) ? html_definition_list : 0; info.class_info = 0; } } pgSetParInfo(m_paigeRef, NULL, &info, &mask, best_way); return TRUE; } bool CPaigeStyle::ApplySigned(bool bOn) { par_info mask, info; pgInitParMask(&info,0); pgInitParMask(&mask,0); mask.user_id=-1; mask.left_extra =-1; pgGetParInfo( m_paigeRef, NULL, false, &info, &mask ); if ( ApplySigned(&info, bOn) ) pgSetParInfo(m_paigeRef,NULL,&info,&mask, best_way); return TRUE; } bool CPaigeStyle::ApplySigned(par_info_ptr info, bool bOn) { if ( bOn ) { info->user_id |= PAIGE_FORMAT_USER_ID_SIGNED; info->left_extra = EXCERPT_OFFSET; } else { // If we weren't in an excerpt, then bail if (!(info->user_id & PAIGE_FORMAT_USER_ID_EXCERPT)) return FALSE; m_par.left_extra = 0; m_par.user_id = 0; // Change this to an and/or operation } return TRUE; } bool CPaigeStyle::IsSigned(par_info_ptr pPar) { return ( pPar->user_id & PAIGE_FORMAT_USER_ID_EXCERPT ); } // BOG: inline signature support bool CPaigeStyle::ApplySignature( bool bOn /*= true*/, select_pair_ptr sel /*= 0*/ ) { par_info mask, info; pgInitParMask( &info, 0 ); pgInitParMask( &mask, 0 ); mask.user_id = -1; pgGetParInfo( m_paigeRef, sel, false, &info, &mask ); pgInitParMask( &mask, 0 ); mask.user_id = -1; if ( ApplySignature( &info, bOn ) ) pgSetParInfo( m_paigeRef, sel, &info, &mask, best_way ); return true; } bool CPaigeStyle::ApplySignature( par_info_ptr info, bool bOn /*= true*/ ) { if ( bOn ) { info->user_id |= PAIGE_FORMAT_USER_ID_SIGNATURE; } else { // If we aren't in a sig, then bail if ( !(info->user_id & PAIGE_FORMAT_USER_ID_SIGNATURE) ) return false; info->user_id ^= PAIGE_FORMAT_USER_ID_SIGNATURE; } return true; } bool CPaigeStyle::IsSignature( par_info_ptr pPar ) { return (pPar->user_id & PAIGE_FORMAT_USER_ID_SIGNATURE) != 0; } bool CPaigeStyle::IsSignature( select_pair_ptr sel ) { par_info mask, info; pgInitParMask( &info, 0 ); pgInitParMask( &mask, 0 ); mask.user_id = -1; pgGetParInfo( m_paigeRef, sel, false, &info, &mask ); return IsSignature( &info ); } bool CPaigeStyle::IsWithinURLRange( select_pair_ptr within /*= NULL*/ ) { bool bRetVal = false; long startOffset, searchLimit; if ( within ) { startOffset = within->begin; searchLimit = within->end; } else { /*startOffset = 0; searchLimit = pgTextSize( m_paigeRef );*/ return bRetVal; } style_walk sw; paige_rec_ptr prp = (paige_rec_ptr) UseMemory( m_paigeRef ); pgPrepareStyleWalk( prp, startOffset, &sw, false ); UnuseMemory( m_paigeRef ); for ( ; sw.current_offset < searchLimit; ) { if ( sw.hyperlink->unique_id ) { if (within->begin >= sw.hyperlink->applied_range.begin && within->begin <= sw.hyperlink->applied_range.end) { bRetVal = true; break; } } else break; if ( sw.next_style_run->offset <= sw.t_length ) pgWalkStyle( &sw, sw.hyperlink->applied_range.end - sw.current_offset ); else break; } pgPrepareStyleWalk( prp, 0, NULL, false ); return bRetVal; }
30.237578
145
0.69527
dusong7