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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
01f64c6395833802dcec9fcd0d166fe9fa238644
| 7,491
|
cpp
|
C++
|
app/app/scene/ui_overlay_system.cpp
|
muleax/slope
|
254138703163705b57332fc7490dd2eea0082b57
|
[
"MIT"
] | 6
|
2022-02-05T23:28:12.000Z
|
2022-02-24T11:08:04.000Z
|
app/app/scene/ui_overlay_system.cpp
|
muleax/slope
|
254138703163705b57332fc7490dd2eea0082b57
|
[
"MIT"
] | null | null | null |
app/app/scene/ui_overlay_system.cpp
|
muleax/slope
|
254138703163705b57332fc7490dd2eea0082b57
|
[
"MIT"
] | null | null | null |
#include "app/scene/ui_overlay_system.hpp"
#include "app/scene/physics_system.hpp"
#include "app/render/render_system.hpp"
#include "app/system/utils.hpp"
#include "imgui/imgui.h"
namespace slope::app {
void UIOverlaySystem::update(float dt)
{
auto* ps = w().modify_singleton<PhysicsSingleton>();
if (!ps)
return;
auto& stats = ps->dynamics_world.stats();
auto& np_stats = stats.np_stats;
auto& gjk_stats = np_stats.gjk_stats;
auto& epa_stats = np_stats.epa_stats;
auto& sat_stats = np_stats.sat_stats;
auto treeNodeFlags = ImGuiTreeNodeFlags_DefaultOpen;
ImGui::SetNextWindowPos(ImVec2(340, 10), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(230, 550), ImGuiCond_FirstUseEver);
ImGui::Begin("Stats");
if (ImGui::CollapsingHeader("General", treeNodeFlags)) {
ImGui::Text("Simulation Time: %.1f s", stats.simulation_time);
ImGui::Text("CPU Frame Time: %.1f ms", ps->cpu_time.instantaneous() * 1000);
ImGui::Text("Kinematic Actors: %d", stats.kinematic_actor_count);
ImGui::Text("Dynamic Actors: %d", stats.dynamic_actor_count);
ImGui::Text("Joints: %d", stats.joint_count);
}
if (ImGui::CollapsingHeader("Narrowphase", treeNodeFlags)) {
ImGui::Text("Narrowphase Tests: %d", np_stats.test_count);
ImGui::Text("Collisions: %d", np_stats.collision_count);
ImGui::Text("Contact points: %d", np_stats.contact_count);
ImGui::Text("GJK Tests: %llu", gjk_stats.cum_test_count);
ImGui::Text("GJK Total Fails: %llu", gjk_stats.total_fail_count);
ImGui::Text("GJK Max Iterations: %d", gjk_stats.max_iteration_count);
ImGui::Text("GJK Avg Iterations: %.2f", float(gjk_stats.cum_iterations_count) / float(gjk_stats.cum_test_count));
ImGui::Text("EPA Tests: %llu", epa_stats.cum_test_count);
ImGui::Text("EPA Total Fails: %llu", epa_stats.total_fail_count);
ImGui::Text("EPA Max Iterations: %d", epa_stats.max_iteration_count);
ImGui::Text("EPA Avg Iterations: %.2f", float(epa_stats.cum_iterations_count) / float(epa_stats.cum_test_count));
ImGui::Text("SAT Tests: %llu", sat_stats.cum_test_count);
ImGui::Text("SAT Avg Projections: %.2f", float(sat_stats.cum_projection_count) / float(sat_stats.cum_test_count));
}
if (ImGui::CollapsingHeader("Islands", treeNodeFlags)) {
ImGui::Text("Island Count: %d", stats.island_count);
for (int i = 0; i < stats.larges_islands.size(); i++) {
ImGui::Text("%d-Largest: %.3f", i + 1, stats.larges_islands[i] / float(stats.dynamic_actor_count));
}
}
if (ImGui::CollapsingHeader("Solver", treeNodeFlags)) {
ImGui::Text("Constraints: %d", stats.constraint_count);
}
ImGui::End();
DynamicsWorldConfig world_config = ps->dynamics_world.config();
auto& solver_config = world_config.solver_config;
auto& np_config = world_config.np_config;
auto& gjk_config = np_config.gjk_config;
auto& epa_config = np_config.epa_config;
ImGui::SetNextWindowPos(ImVec2(10, 10), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(320, 980), ImGuiCond_FirstUseEver);
ImGui::Begin("Config");
if (ImGui::CollapsingHeader("General", treeNodeFlags)) {
ImGui::Checkbox("Pause", &ps->pause);
ImGui::Checkbox("Enable Constraint Resolving", &world_config.enable_constraint_resolving);
ImGui::Checkbox("Enable Integration", &world_config.enable_integration);
ImGui::Checkbox("Real Time Sync", &ps->real_time_sync);
ImGui::DragFloat("Time Factor", &ps->time_factor, 0.01f, 0.001f, 100.f);
float time_step_ms = world_config.solver_config.time_interval * 1000.f;
ImGui::DragFloat("Time Step", &time_step_ms, 0.1f, 0.1f, 1000.f);
world_config.solver_config.time_interval = time_step_ms * 0.001f;
ImGui::Checkbox("Gyroscopic Torque", &world_config.enable_gyroscopic_torque);
ImGui::Checkbox("Enable Gravity", &world_config.enable_gravity);
ImGui::InputFloat3("Gravity", world_config.gravity.data);
}
if (ImGui::CollapsingHeader("Narrowphase", treeNodeFlags)) {
ImGui::Text("Policy:");
ImGui::SameLine();
bool use_mixed = (world_config.np_backend_hint == NpBackendHint::Mixed);
if (ImGui::RadioButton("Mixed", use_mixed))
world_config.np_backend_hint = NpBackendHint::Mixed;
ImGui::SameLine();
bool use_gjk = (world_config.np_backend_hint == NpBackendHint::GJK_EPA);
if (ImGui::RadioButton("GJK/EPA", use_gjk))
world_config.np_backend_hint = NpBackendHint::GJK_EPA;
ImGui::SameLine();
bool use_sat = (world_config.np_backend_hint == NpBackendHint::SAT);
if (ImGui::RadioButton("SAT", use_sat))
world_config.np_backend_hint = NpBackendHint::SAT;
ImGui::DragScalar("GJK Max Iters", ImGuiDataType_U32, &gjk_config.max_iteration_count);
ImGui::DragScalar("EPA Max Iters", ImGuiDataType_U32, &epa_config.max_iteration_count);
ImGui::DragFloat("EPA Support Bloat", &epa_config.support_bloat);
ImGui::DragFloat("EPA Early Threshold", &epa_config.early_threshold, 1e-7f, -1.f, 1.f, "%.8f");
ImGui::DragFloat("EPA Final Threshold", &epa_config.final_threshold, 1e-4f, -1.f, 1.f, "%.8f");
}
if (ImGui::CollapsingHeader("Solver", treeNodeFlags)) {
ImGui::Checkbox("Initial Randomization", &world_config.randomize_order);
ImGui::Checkbox("Velocity Dependent Friction", &world_config.enable_velocity_dependent_friction);
ImGui::Checkbox("Cone Friction", &world_config.enable_cone_friction);
ImGui::DragInt("Iterations", &solver_config.iteration_count, 0.5f, 1, 300);
ImGui::DragFloat("SOR", &solver_config.sor, 0.001f, 0.f, 1.f);
ImGui::DragFloat("Normal WS", &world_config.normal_warmstarting, 0.002f, 0.f, 1.f);
ImGui::DragFloat("Friction WS", &world_config.friction_warmstarting, 0.002f, 0.f, 1.f);
ImGui::DragFloat("Contact ERP", &world_config.contact_erp, 0.001f, 0.f, 1.f);
ImGui::DragFloat("Contact CFM", &world_config.contact_cfm, 0.001f, 0.f, 1.f);
ImGui::DragFloat("Contact Penetration", &world_config.contact_penetration, 0.001f, 0.f, 1.f);
ImGui::DragFloat("Joint WS", &world_config.joint_warmstarting, 0.002f, 0.f, 1.f);
ImGui::DragFloat("Joint ERP", &world_config.joint_erp, 0.002f, 0.f, 1.f);
}
if (ImGui::CollapsingHeader("Performance", treeNodeFlags)) {
ImGui::DragInt("Concurrency", &ps->concurrency, 1.f, 1, 16);
ImGui::Checkbox("Use SIMD Solver", &world_config.solver_config.use_simd);
}
auto* rs = w().modify_singleton<RenderSingleton>();
if (rs) {
if (ImGui::CollapsingHeader("Visualization", treeNodeFlags)) {
ImGui::Checkbox("Wireframe", &rs->wireframe);
ImGui::Checkbox("Contact Normals 1", &world_config.draw_contact_normals1);
ImGui::Checkbox("Contact Friction 1", &world_config.draw_contact_friction1);
ImGui::Checkbox("Contact Normals 2", &world_config.draw_contact_normals2);
ImGui::Checkbox("Contact Friction 2", &world_config.draw_contact_friction2);
ImGui::Checkbox("Delay Integration", &world_config.delay_integration);
}
}
ImGui::End();
ps->dynamics_world.update_config(world_config);
// ImGui::ShowDemoWindow();
}
} // slope::app
| 47.411392
| 122
| 0.676679
|
muleax
|
01fdec22a1d72f3eb83aa4827ffdfe5fa0957b11
| 1,177
|
cpp
|
C++
|
catkin_ws/topic_publisher_pkg/src/simple_topic_publisher.cpp
|
BV-Pradeep/RIA-ROS-Basics-with-CPP-in-5-days
|
2c33397de94a5d35cd9bb5d957fb0a15dd0b70b1
|
[
"MIT"
] | 5
|
2019-08-09T03:07:30.000Z
|
2021-12-09T15:51:09.000Z
|
catkin_ws/topic_publisher_pkg/src/simple_topic_publisher.cpp
|
BV-Pradeep/RIA-ROS-Basics-with-CPP-in-5-days
|
2c33397de94a5d35cd9bb5d957fb0a15dd0b70b1
|
[
"MIT"
] | null | null | null |
catkin_ws/topic_publisher_pkg/src/simple_topic_publisher.cpp
|
BV-Pradeep/RIA-ROS-Basics-with-CPP-in-5-days
|
2c33397de94a5d35cd9bb5d957fb0a15dd0b70b1
|
[
"MIT"
] | 3
|
2019-07-22T07:43:46.000Z
|
2021-07-12T14:23:24.000Z
|
#include <ros/ros.h>
#include <std_msgs/Int32.h>
// Here we are including all the headers necessary to use the most common public
// pieces of the ROS system. Always we create a new C++ file, we will need to
// add this include.
int main(int argc, char** argv) {// We start the main C++ program
ros::init(argc, argv, "topic_publisher");// We initiate a ROS node called topic_publisher
ros::NodeHandle nh;// We create a handler for the node. This handler will actually do the initialization of the node.
ros::Publisher pub = nh.advertise<std_msgs::Int32>("counter", 1000); //We create a publisher called counter which uses std_msgs of Int32 type to publish 1000
ros::Rate loop_rate(2);// We create a Rate object of 2Hz
std_msgs::Int32 count;//We initializing count variable.
count.data = 0;// we are setting Count data to zero
while (ros::ok())//Endless loop to publish the count variable
{
pub.publish(count);// Publish the message within the 'count' variable
ros::spinOnce();
loop_rate.sleep();// Make sure the publish rate maintains at 2 Hz
++count.data;// Increment 'count' variable
}
return 0;
}
| 43.592593
| 161
| 0.694138
|
BV-Pradeep
|
01fe7d60bfde4b6e405bf68d39b2ee2133c0684c
| 44
|
hpp
|
C++
|
src/boost_compute_utility_source.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_compute_utility_source.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_compute_utility_source.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/compute/utility/source.hpp>
| 22
| 43
| 0.795455
|
miathedev
|
01ffdf5f4339758462412e2c3a7e8816f89191d6
| 13,212
|
hpp
|
C++
|
NMEA0183.hpp
|
Emandhal/NMEA0183
|
12d50fe84022b0e1d9c24829cea6931de33d83ca
|
[
"MIT"
] | null | null | null |
NMEA0183.hpp
|
Emandhal/NMEA0183
|
12d50fe84022b0e1d9c24829cea6931de33d83ca
|
[
"MIT"
] | null | null | null |
NMEA0183.hpp
|
Emandhal/NMEA0183
|
12d50fe84022b0e1d9c24829cea6931de33d83ca
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
* @file NMEA0183.hpp
* @author Fabien 'Emandhal' MAILLY
* @version 1.0.0
* @date 13/02/2022
* @brief NMEA decoder library (C++ class wrapper header for C NMEA0183 library)
*
* Supports common GPS frames
******************************************************************************/
/* @page License
*
* Copyright (c) 2020-2022 Fabien MAILLY
*
* 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,
* IMPLIED OR STATUTORY, 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.
*****************************************************************************/
/* Revision history:s
* 1.0.0 Release version
*****************************************************************************/
#ifndef NMEA0183_LIB_HPP_
#define NMEA0183_LIB_HPP_
//=============================================================================
//-----------------------------------------------------------------------------
#if !defined(NMEA0183_USE_INPUT_BUFFER)
# define NMEA0183_USE_INPUT_BUFFER
#endif
//-----------------------------------------------------------------------------
#include "NMEA0183.h"
//-----------------------------------------------------------------------------
#ifdef NMEA0183_FLOAT_BASED_TOOLS
# include <math.h>
#endif
//-----------------------------------------------------------------------------
//********************************************************************************************************************
// NMEA0183 decoder Class
//********************************************************************************************************************
class NMEA0183decoder
{
protected:
struct NMEA0183_InputBuffer InputData; // NMEA0183 decoder structure
public:
/*! @brief Constructor
* Initialize NMEA0183 decoder input data
*/
NMEA0183decoder() { (void)Init_NMEA0183(&InputData); };
/*! @brief Destructor
* Do nothing in this case
*/
~NMEA0183decoder() { };
public:
/*! @brief Add NMEA0183 received frame character data
*
* @param[in] data Is the char to add to input data buffer
* @return Returns an #eERRORRESULT value enum
*/
eERRORRESULT AddReceivedCharacter(char data) { return NMEA0183_AddReceivedCharacter(&InputData, data); };
/*! @brief Get decoder state
* @return Returns an #eNMEA0183_State value enum
*/
eNMEA0183_State GetDecoderState(void) { return NMEA0183_GetDecoderState(&InputData); };
/*! @brief Is a frame ready to process?
* @return Returns 'true' if a frame is ready to process else 'false'
*/
bool IsFrameReadyToProcess(void) { NMEA0183_IsFrameReadyToProcess(&InputData); };
/*! @brief Process the NMEA0183 frame (used with the decode structure)
*
* @param[out] *pData Is the decoded data
* @return Returns an #eERRORRESULT value enum
*/
eERRORRESULT ProcessFrame(NMEA0183_DecodedData* pData) { return NMEA0183_ProcessFrame(&InputData, pData); };
//-----------------------------------------------------------------------------
/*! @brief Process the NMEA0183 frame string line
*
* This function can be used alone without using the NMEA0183_DecodeInput structure
* This fucntion process a whole NMEA0183 line at once (from '$' to the char before the \r or \n terminal)
* @param[in] *pDecoder Is the frame string (with '\0' terminal) to process
* @param[out] *pData Is the decoded data
* @return Returns an #eERRORRESULT value enum
*/
eERRORRESULT ProcessLine(const char* string, NMEA0183_DecodedData* pData);
#ifdef NMEA0183_FLOAT_BASED_TOOLS
public:
/*! @brief Convert coordinate to degree (D.d)
*
* @param[in] &pCoordinate Is the coordinate to convert
* @param[out] *pDegree Is where the coordinate converted will be stored
* @return Returns an #eERRORRESULT value enum
*/
eERRORRESULT CoordinateToDegree(NMEA0183_Coordinate& pCoordinate, double* pDegree) { return NMEA0183_CoordinateToDegree(&pCoordinate, pDegree); };
/*! @brief Convert coordinate to degree minute (D M.m)
*
* @param[in] &pCoordinate Is the coordinate to convert
* @param[out] *pDegMinute Is where the coordinate converted will be stored
* @return Returns an #eERRORRESULT value enum
*/
eERRORRESULT CoordinateToDegreeMinute(NMEA0183_Coordinate& pCoordinate, NMEA0183_DegreeMinute* pDegMinute) { return NMEA0183_CoordinateToDegreeMinute(&pCoordinate, pDegMinute); };
/*! @brief Convert coordinate to degree minute seconds (D M S)
*
* @param[in] &pCoordinate Is the coordinate to convert
* @param[out] *pDegMinSec Is where the coordinate converted will be stored
* @return Returns an #eERRORRESULT value enum
*/
eERRORRESULT CoordinateToDegreeMinuteSeconds(NMEA0183_Coordinate& pCoordinate, NMEA0183_DegreeMinuteSeconds* pDegMinSec) { return NMEA0183_CoordinateToDegreeMinuteSeconds(&pCoordinate, pDegMinSec); };
#endif
};
#if defined(NMEA0183_GPS_DECODER_CLASS) && defined(NMEA0183_FLOAT_BASED_TOOLS)
//********************************************************************************************************************
// GPS decoder Class
//********************************************************************************************************************
class GPSdecoder
{
protected:
struct NMEA0183_InputBuffer InputData; // NMEA0183 decoder structure
private:
NMEA0183_Time _Time; bool _NewTimeAvailable; // Time
NMEA0183_Date _Date; bool _NewDateAvailable; // Date
double _Latitude; bool _NewLatitudeAvailable; // Latitude in degrees
double _Longitude; bool _NewLongitudeAvailable; // Longitude in degrees
int32_t _Altitude; bool _NewAltitudeAvailable; // Altitude mean-sea-level (geoid) in meters
uint32_t _Speed; bool _NewSpeedAvailable; // Speed over the ground in knots
uint32_t _Track; bool _NewTrackAvailable; // Track angle in degrees (True)
uint16_t _HDOP; bool _NewHDOPAvailable; // Horizontal Dilution of Precision
public:
/*! @brief Constructor
* Initialize GPS decoder input data
*/
GPSdecoder();
/*! @brief Destructor
* Do nothing in this case
*/
~GPSdecoder() { };
public:
/*! @brief Process the received GPS frame character data
*
* @param[in] data Is the char to add to input data buffer
* @return Returns an #eERRORRESULT value enum
*/
eERRORRESULT ProcessCharacter(const char data);
public:
/*! @brief Is a new time available?
* @return Returns 'true' if a new time has been decoded else 'false'
*/
inline bool IsNewTimeAvailable(void) const { return _NewTimeAvailable; };
/*! @brief Get time
* @return Returns the last decoded time
*/
inline NMEA0183_Time GetTime(void) const { return _Time; };
//-----------------------------------------------------------------------------
/*! @brief Is a new date available?
* @return Returns 'true' if a new date has been decoded else 'false'
*/
inline bool IsNewDateAvailable(void) const { return _NewDateAvailable; };
/*! @brief Get date
* @return Returns the last decoded date
*/
inline NMEA0183_Date GetDate(void) const { return _Date; };
//-----------------------------------------------------------------------------
/*! @brief Is a new latitude available?
* @return Returns 'true' if a new latitude has been decoded else 'false'
*/
inline bool IsNewLatitudeAvailable(void) const { return _NewLatitudeAvailable; };
/*! @brief Get latitude in degree (D.d)
* @return Returns the last decoded latitude in decimal degrees
*/
inline double GetLatitudeInDegree(void) const { return _Latitude; };
/*! @brief Get latitude in degree minute (D M.m)
* @return Returns the last decoded latitude in decimal degrees
*/
inline NMEA0183_DegreeMinute GetLatitudeInDegreeMinute(void) const
{
NMEA0183_DegreeMinute Result;
(void)NMEA0183_DegreeToDegreeMinute(_Latitude, &Result);
return Result;
};
/*! @brief Get latitude in degree minute seconds (D M S.s)
* @return Returns the last decoded latitude in decimal degrees
*/
inline NMEA0183_DegreeMinuteSeconds GetLatitudeInDegreeMinuteSeconds(void) const
{
NMEA0183_DegreeMinuteSeconds Result;
(void)NMEA0183_DegreeToDegreeMinuteSeconds(_Latitude, &Result);
return Result;
};
//-----------------------------------------------------------------------------
/*! @brief Is a new longitude available?
* @return Returns 'true' if a new longitude has been decoded else 'false'
*/
inline bool IsNewLongitudeAvailable(void) const { return _NewLongitudeAvailable; };
/*! @brief Get longitude in degree (D.d)
* @return Returns the last decoded longitude in decimal degrees
*/
inline double GetLongitudeInDegree(void) const { return _Longitude; };
/*! @brief Get longitude in degree minute (D M.m)
* @return Returns the last decoded longitude in decimal degrees
*/
inline NMEA0183_DegreeMinute GetLongitudeInDegreeMinute(void) const
{
NMEA0183_DegreeMinute Result;
(void)NMEA0183_DegreeToDegreeMinute(_Latitude, &Result);
return Result;
};
/*! @brief Get longitude in degree minute seconds (D M S.s)
* @return Returns the last decoded longitude in decimal degrees
*/
inline NMEA0183_DegreeMinuteSeconds GetLongitudeInDegreeMinuteSeconds(void) const
{
NMEA0183_DegreeMinuteSeconds Result;
(void)NMEA0183_DegreeToDegreeMinuteSeconds(_Latitude, &Result);
return Result;
};
//-----------------------------------------------------------------------------
/*! @brief Is a new altitude available?
* @return Returns 'true' if a new altitude has been decoded else 'false'
*/
inline bool IsNewAltitudeAvailable(void) const { return _NewAltitudeAvailable; };
/*! @brief Get altitude mean-sea-level (geoid) in meters
* @return Returns the last decoded altitude mean-sea-level (geoid) in meters
*/
inline double GetAltitudeInMeter(void) const { return (double)_Altitude / 100.0; };
//-----------------------------------------------------------------------------
/*! @brief Is a new speed available?
* @return Returns 'true' if a new speed has been decoded else 'false'
*/
inline bool IsNewSpeedAvailable(void) const { return _NewSpeedAvailable; };
/*! @brief Get speed over the ground in knots
* @return Returns the last decoded speed over the ground in knots
*/
inline double GetSpeedInKnots(void) const { return (_Speed != NMEA0183_NO_VALUE ? (double)_Speed / 10000.0 : NAN); };
//-----------------------------------------------------------------------------
/*! @brief Is a new track available?
* @return Returns 'true' if a new track has been decoded else 'false'
*/
inline bool IsNewTrackAvailable(void) const { return _NewTrackAvailable; };
/*! @brief Get track angle in degrees (True)
* @return Returns the last decoded track angle in degrees (True)
*/
inline double GetTrackInDegree(void) const { return (_Track != NMEA0183_NO_VALUE ? (double)_Track / 10000.0 : NAN); };
/*! @brief Convert track/course to cardinal direction
* @return Returns the cardinal direction string
*/
const char* const TrackToCardinal(double track) const;
//-----------------------------------------------------------------------------
/*! @brief Is a new HDOP available?
* @return Returns 'true' if a new HDOP has been decoded else 'false'
*/
inline bool IsNewHDOPAvailable(void) const { return _NewHDOPAvailable; };
/*! @brief Get Horizontal Dilution of Precision
* @return Returns the last decoded Horizontal Dilution of Precision
*/
inline double GetHDOP(void) const { return (_HDOP != NMEA0183_NO_VALUE ? (double)_HDOP / 100.0 : NAN); };
};
#endif
//-----------------------------------------------------------------------------
#endif /* NMEA0183_LIB_HPP_ */
| 40.280488
| 204
| 0.598168
|
Emandhal
|
01fff55c581b30405869552a6f7d5c90d1036b08
| 4,973
|
cpp
|
C++
|
testsuites/unittest/net/socket/net_socket_test.cpp
|
onattof/Cbad13i
|
17a25f2026802c02e7fb4876309382914cfd6c4f
|
[
"BSD-3-Clause"
] | null | null | null |
testsuites/unittest/net/socket/net_socket_test.cpp
|
onattof/Cbad13i
|
17a25f2026802c02e7fb4876309382914cfd6c4f
|
[
"BSD-3-Clause"
] | null | null | null |
testsuites/unittest/net/socket/net_socket_test.cpp
|
onattof/Cbad13i
|
17a25f2026802c02e7fb4876309382914cfd6c4f
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "stdio.h"
#include <climits>
#include <gtest/gtest.h>
#include "lt_net_socket.h"
using namespace testing::ext;
namespace OHOS {
class NetSocketTest : public testing::Test {
public:
static void SetUpTestCase(void)
{
struct sched_param param = { 0 };
int currThreadPolicy, ret;
ret = pthread_getschedparam(pthread_self(), &currThreadPolicy, ¶m);
ICUNIT_ASSERT_EQUAL_VOID(ret, 0, -ret);
param.sched_priority = TASK_PRIO_TEST;
ret = pthread_setschedparam(pthread_self(), SCHED_RR, ¶m);
ICUNIT_ASSERT_EQUAL_VOID(ret, 0, -ret);
}
static void TearDownTestCase(void) {}
};
#if defined(LOSCFG_USER_TEST_SMOKE) && defined(LOSCFG_USER_TEST_NET_SOCKET)
/* *
* @tc.name: NetSocketTest001
* @tc.desc: function for NetSocketTest
* @tc.type: FUNC
*/
HWTEST_F(NetSocketTest, NetSocketTest001, TestSize.Level0)
{
NetSocketTest001();
}
/* *
* @tc.name: NetSocketTest002
* @tc.desc: function for NetSocketTest
* @tc.type: FUNC
*/
HWTEST_F(NetSocketTest, NetSocketTest002, TestSize.Level0)
{
NetSocketTest002();
}
#if TEST_ON_LINUX
/* *
* @tc.name: NetSocketTest003
* @tc.desc: function for NetSocketTest
* @tc.type: FUNC
*/
HWTEST_F(NetSocketTest, NetSocketTest003, TestSize.Level0)
{
NetSocketTest003(); // getifaddrs need PF_NETLINK which was not supported by lwip currently
}
#endif
/* *
* @tc.name: NetSocketTest004
* @tc.desc: function for NetSocketTest
* @tc.type: FUNC
*/
HWTEST_F(NetSocketTest, NetSocketTest004, TestSize.Level0)
{
NetSocketTest004();
}
/* *
* @tc.name: NetSocketTest005
* @tc.desc: function for NetSocketTest
* @tc.type: FUNC
*/
HWTEST_F(NetSocketTest, NetSocketTest005, TestSize.Level0)
{
NetSocketTest005();
}
/* *
* @tc.name: NetSocketTest006
* @tc.desc: function for NetSocketTest
* @tc.type: FUNC
*/
HWTEST_F(NetSocketTest, NetSocketTest006, TestSize.Level0)
{
NetSocketTest006();
}
#if TEST_ON_LINUX
/* *
* @tc.name: NetSocketTest007
* @tc.desc: function for NetSocketTest
* @tc.type: FUNC
*/
HWTEST_F(NetSocketTest, NetSocketTest007, TestSize.Level0)
{
NetSocketTest007();
}
#endif
/* *
* @tc.name: NetSocketTest008
* @tc.desc: function for NetSocketTest
* @tc.type: FUNC
*/
HWTEST_F(NetSocketTest, NetSocketTest008, TestSize.Level0)
{
NetSocketTest008();
}
/* *
* @tc.name: NetSocketTest009
* @tc.desc: function for NetSocketTest
* @tc.type: FUNC
*/
HWTEST_F(NetSocketTest, NetSocketTest009, TestSize.Level0)
{
NetSocketTest009();
}
/* *
* @tc.name: NetSocketTest010
* @tc.desc: function for NetSocketTest
* @tc.type: FUNC
*/
HWTEST_F(NetSocketTest, NetSocketTest010, TestSize.Level0)
{
NetSocketTest010();
}
/* *
* @tc.name: NetSocketTest011
* @tc.desc: function for NetSocketTest
* @tc.type: FUNC
*/
HWTEST_F(NetSocketTest, NetSocketTest011, TestSize.Level0)
{
NetSocketTest011();
}
/* *
* @tc.name: NetSocketTest012
* @tc.desc: function for NetSocketTest
* @tc.type: FUNC
*/
HWTEST_F(NetSocketTest, NetSocketTest012, TestSize.Level0)
{
NetSocketTest012();
}
/* *
* @tc.name: NetSocketTest013
* @tc.desc: function for NetSocketTest
* @tc.type: FUNC
*/
/*
HWTEST_F(NetSocketTest, NetSocketTest013, TestSize.Level0)
{
//NetSocketTest013(); // broadcast to self to be supported.
}
*/
#endif
}
| 25.901042
| 95
| 0.72411
|
onattof
|
bf00b7aa177ab4db13b4f43fd41c9096656b6dc9
| 176
|
cpp
|
C++
|
tests/external_view_test.cpp
|
somefoo/game_server
|
9fb6b8aac8cb20f7e3cea8b74d9e9cb86324e65f
|
[
"Apache-2.0"
] | null | null | null |
tests/external_view_test.cpp
|
somefoo/game_server
|
9fb6b8aac8cb20f7e3cea8b74d9e9cb86324e65f
|
[
"Apache-2.0"
] | null | null | null |
tests/external_view_test.cpp
|
somefoo/game_server
|
9fb6b8aac8cb20f7e3cea8b74d9e9cb86324e65f
|
[
"Apache-2.0"
] | 1
|
2022-03-05T23:03:17.000Z
|
2022-03-05T23:03:17.000Z
|
#include <iostream>
#include "client.h"
client c;
int main(){
if(c.get_game_state().m_player_runtime_state.m_player_runtime_data[0].m_kills != 0) return 1;
return 0;
}
| 14.666667
| 95
| 0.715909
|
somefoo
|
bf03efc72d30a5bc8274bbf11e35e09b51c503ec
| 1,564
|
cpp
|
C++
|
Data_Structures/Binary_Tree/diameter.cpp
|
abhishekjha786/ds_algo
|
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
|
[
"MIT"
] | 11
|
2020-03-20T17:24:28.000Z
|
2022-01-08T02:43:24.000Z
|
Data_Structures/Binary_Tree/diameter.cpp
|
abhishekjha786/ds_algo
|
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
|
[
"MIT"
] | 1
|
2021-07-25T11:24:46.000Z
|
2021-07-25T12:09:25.000Z
|
Data_Structures/Binary_Tree/diameter.cpp
|
abhishekjha786/ds_algo
|
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
|
[
"MIT"
] | 4
|
2020-03-20T17:24:36.000Z
|
2021-12-07T19:22:59.000Z
|
// Diameter of Tree
// Given a binary tree, you need to compute the length of the diameter of the tree.
// The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
// Example:
// Given a binary tree
// 1
// / '\'
// 2 3
// / \
// 4 5
// Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
#include<bits/stdc++.h>
using namespace std;
int res = INT_MIN;
class Node
{
public:
int data;
Node *left, *right;
};
Node *newnode(int new_data)
{
Node *new_node = new Node;
new_node->data = new_data;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
// The idea is quite simple.
// Max value of Height(leftSubtree) +
// Height(rightSubtree) (at any node) is the diameter.
// Keep track of maximum diameter duing traversal and
// find the height of the tree.
int diameter_tree(Node *node)
{
int d = 0;
auto _ = dmtree(node, d);
return d;
}
int dmtree(Node *node, int &d)
{
if(node == NULL)
{
return 0;
}
int ld = dmtree(node->left, d);
int rd = dmtree(node->right, d);
d = max(d, ld+ rd);
return max(ld, rd) + 1;
}
int main(int argc, char const *argv[])
{
Node *root = newnode(1);
root->left = newnode(2);
root->right = newnode(3);
root->left->left = newnode(4);
root->left->right = newnode(5);
cout<<"diameter of tree: "<<diameter_tree(root)<<endl;
return 0;
}
| 19.073171
| 147
| 0.586957
|
abhishekjha786
|
bf04062ed57cf909c2542c53f73a0e0bfb7b92ad
| 91
|
cxx
|
C++
|
Software/CPU/myscrypt/build/cmake-3.12.3/Tests/Fortran/mycxx.cxx
|
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
|
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
|
[
"MIT"
] | 107
|
2021-08-28T20:08:42.000Z
|
2022-03-22T08:02:16.000Z
|
Software/CPU/myscrypt/build/cmake-3.12.3/Tests/Fortran/mycxx.cxx
|
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
|
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
|
[
"MIT"
] | 3
|
2021-09-08T02:18:00.000Z
|
2022-03-12T00:39:44.000Z
|
Software/CPU/myscrypt/build/cmake-3.12.3/Tests/Fortran/mycxx.cxx
|
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
|
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
|
[
"MIT"
] | 16
|
2021-08-30T06:57:36.000Z
|
2022-03-22T08:05:52.000Z
|
extern "C" int myc(void);
extern "C" int mycxx(void)
{
delete new int;
return myc();
}
| 13
| 26
| 0.626374
|
duonglvtnaist
|
bf06cdf38345019bff00e5e9063c9ef68122c2ce
| 5,673
|
hh
|
C++
|
include/ignition/gazebo/comms/Broker.hh
|
Thodoris1999/ign-gazebo
|
66fa61a1c2b018fa0a4d1080ef89c7cc9d321cea
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
include/ignition/gazebo/comms/Broker.hh
|
Thodoris1999/ign-gazebo
|
66fa61a1c2b018fa0a4d1080ef89c7cc9d321cea
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
include/ignition/gazebo/comms/Broker.hh
|
Thodoris1999/ign-gazebo
|
66fa61a1c2b018fa0a4d1080ef89c7cc9d321cea
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) 2022 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef IGNITION_GAZEBO_BROKER_HH_
#define IGNITION_GAZEBO_BROKER_HH_
#include <memory>
#include <ignition/utils/ImplPtr.hh>
#include <sdf/sdf.hh>
#include "ignition/gazebo/comms/MsgManager.hh"
#include "ignition/gazebo/config.hh"
namespace ignition
{
namespace msgs
{
// Forward declarations.
class Boolean;
class Dataframe;
class StringMsg_V;
}
namespace gazebo
{
// Inline bracket to help doxygen filtering.
inline namespace IGNITION_GAZEBO_VERSION_NAMESPACE {
namespace comms
{
// Forward declarations.
class MsgManager;
/// \brief A class to store messages to be delivered using a comms model.
/// This class should be used in combination with a specific comms model that
/// implements the ICommsModel interface.
/// \sa ICommsModel.hh
/// The broker maintains two queues: inbound and outbound. When a client
/// sends a communication request, we'll store it in the outbound queue of
/// the sender's address. When the comms model decides that a message needs
/// to be delivered to one of the destination, it'll be stored in the inbound
/// queue of the destination's address.
///
/// The main goal of this class is to receive the comms requests, stamp the
/// time, and place them in the appropriate outbound queue, as well as deliver
/// the messages that are in the inbound queues.
///
/// The instance of the comms model is responsible for moving around the
/// messages from the outbound queues to the inbound queues.
///
/// The broker can be configured with the following SDF parameters:
///
/// * Optional parameters:
/// <broker> Element used to capture the broker parameters. This block can
/// contain any of the next parameters:
/// <messages_topic>: Topic name where the broker receives all the incoming
/// messages. The default value is "/broker/msgs"
/// <bind_service>: Service name used to bind an address.
/// The default value is "/broker/bind"
/// <unbind_service>: Service name used to unbind from an address.
/// The default value is "/broker/unbind"
///
/// Here's an example:
/// <plugin
/// filename="ignition-gazebo-perfect-comms-system"
/// name="ignition::gazebo::systems::PerfectComms">
/// <broker>
/// <messages_topic>/broker/inbound</messages_topic>
/// <bind_service>/broker/bind_address</bind_service>
/// <unbind_service>/broker/unbind_address</unbind_service>
/// </broker>
/// </plugin>
class IGNITION_GAZEBO_VISIBLE Broker
{
/// \brief Constructor.
public: Broker();
/// \brief Configure the broker via SDF.
/// \param[in] _sdf The SDF Element associated with the broker parameters.
public: void Load(std::shared_ptr<const sdf::Element> _sdf);
/// \brief Start handling comms services.
///
/// This function allows us to wait to advertise capabilities to
/// clients until the broker has been entirely initialized.
public: void Start();
/// \brief Get the current time.
/// \return Current time.
public: std::chrono::steady_clock::duration Time() const;
/// \brief Set the current time.
/// \param[in] _time Current time.
public: void SetTime(const std::chrono::steady_clock::duration &_time);
/// \brief This method associates an address with a client topic used as
/// callback for receiving messages. This is a client requirement to
/// start receiving messages.
/// \param[in] _req Bind request containing the following content:
/// _req[0] Client address.
/// _req[1] Model name associated to the address.
/// _req[2] Client subscription topic.
/// \param[out] _rep Unused
/// \return True when the bind service succeeded or false otherwise.
public: bool OnBind(const ignition::msgs::StringMsg_V &_req,
ignition::msgs::Boolean &_rep);
/// \brief Unbind a given client address. The client associated to this
/// address will not receive any more messages.
/// \param[in] _req Bind request containing the following content:
/// _req[0] Client address.
/// _req[1] Client subscription topic.
public: void OnUnbind(const ignition::msgs::StringMsg_V &_req);
/// \brief Callback executed to process a communication request from one of
/// the clients.
/// \param[in] _msg The message from the client.
public: void OnMsg(const ignition::msgs::Dataframe &_msg);
/// \brief Process all the messages in the inbound queue and deliver them
/// to the destination clients.
public: void DeliverMsgs();
/// \brief Get a mutable reference to the message manager.
/// \return The mutable reference.
public: MsgManager &DataManager();
/// \brief Lock the mutex to access the message manager.
public: void Lock();
/// \brief Unlock the mutex to access the message manager.
public: void Unlock();
/// \brief Private data pointer.
IGN_UTILS_UNIQUE_IMPL_PTR(dataPtr)
};
}
}
}
}
#endif
| 36.6
| 80
| 0.686762
|
Thodoris1999
|
bf071154cb6fbde15128d7d0ed69e6ba4abf5f4f
| 348
|
hpp
|
C++
|
src/Entity.hpp
|
asalahli/jubilant-octo-invention
|
c04e5b3347338615935eefaeba349db538099b87
|
[
"MIT"
] | null | null | null |
src/Entity.hpp
|
asalahli/jubilant-octo-invention
|
c04e5b3347338615935eefaeba349db538099b87
|
[
"MIT"
] | null | null | null |
src/Entity.hpp
|
asalahli/jubilant-octo-invention
|
c04e5b3347338615935eefaeba349db538099b87
|
[
"MIT"
] | null | null | null |
#pragma once
#include <Box2D/Box2D.h>
#include "Component.hpp"
#include "Process.hpp"
class Game;
class Entity : public Process {
public:
Drawable *drawable;
b2Body *physicalBody;
Skeleton *skeleton;
Animation *animation;
Entity(Game *game);
~Entity();
virtual void update(float timeDelta) { (void) timeDelta; };
};
| 15.130435
| 63
| 0.675287
|
asalahli
|
bf089e028aac68e278ca543984f30d2013d7ffd5
| 410
|
cpp
|
C++
|
source/objects/imagedata/imagedatabase.cpp
|
henlo-birb/lovepotion
|
3b7128f0683252915cd0178a3e028a553b01fdc1
|
[
"0BSD"
] | 38
|
2021-11-05T10:17:28.000Z
|
2022-03-26T09:19:41.000Z
|
source/objects/imagedata/imagedatabase.cpp
|
henlo-birb/lovepotion
|
3b7128f0683252915cd0178a3e028a553b01fdc1
|
[
"0BSD"
] | 10
|
2021-11-06T04:44:49.000Z
|
2022-03-18T17:23:09.000Z
|
source/objects/imagedata/imagedatabase.cpp
|
henlo-birb/lovepotion
|
3b7128f0683252915cd0178a3e028a553b01fdc1
|
[
"0BSD"
] | 5
|
2022-01-04T20:38:35.000Z
|
2022-02-28T01:11:56.000Z
|
#include "objects/imagedata/imagedatabase.h"
using namespace love;
ImageDataBase::ImageDataBase(PixelFormat format, int width, int height) :
format(format),
width(width),
height(height)
{}
PixelFormat ImageDataBase::GetFormat() const
{
return this->format;
}
int ImageDataBase::GetWidth() const
{
return this->width;
}
int ImageDataBase::GetHeight() const
{
return this->height;
}
| 16.4
| 73
| 0.714634
|
henlo-birb
|
bf0a1ef36ad3803bd5116112f7672ad20abec202
| 1,602
|
hh
|
C++
|
generator/inc/com/centreon/broker/generator/endpoint.hh
|
joe4568/centreon-broker
|
daf454371520989573c810be1f6dfca40979a75d
|
[
"Apache-2.0"
] | null | null | null |
generator/inc/com/centreon/broker/generator/endpoint.hh
|
joe4568/centreon-broker
|
daf454371520989573c810be1f6dfca40979a75d
|
[
"Apache-2.0"
] | null | null | null |
generator/inc/com/centreon/broker/generator/endpoint.hh
|
joe4568/centreon-broker
|
daf454371520989573c810be1f6dfca40979a75d
|
[
"Apache-2.0"
] | null | null | null |
/*
** Copyright 2017 Centreon
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
**
** For more information : contact@centreon.com
*/
#ifndef CCB_GENERATOR_ENDPOINT_HH
# define CCB_GENERATOR_ENDPOINT_HH
# include "com/centreon/broker/io/endpoint.hh"
# include "com/centreon/broker/namespace.hh"
CCB_BEGIN()
namespace generator {
/**
* @class endpoint endpoint.hh "com/centreon/broker/generator/endpoint.hh"
* @brief Create generator stream.
*
* Create a generator stream.
*/
class endpoint : public io::endpoint {
public:
enum endpoint_type {
type_receiver = 1,
type_sender
};
endpoint(endpoint_type type);
~endpoint();
misc::shared_ptr<io::stream> open();
private:
endpoint(endpoint const& other);
endpoint& operator=(endpoint const& other);
endpoint_type _type;
};
}
CCB_END()
#endif // !CCB_GENERATOR_ENDPOINT_HH
| 28.607143
| 77
| 0.622971
|
joe4568
|
bf0b70073be35ecebeae43370f312f7bdda4a1c9
| 3,941
|
cpp
|
C++
|
source/backend/hiai/execution/NPUPooling.cpp
|
WillTao-RD/MNN
|
48575121859093bab8468d6992596962063b7aff
|
[
"Apache-2.0"
] | 2
|
2020-12-15T13:56:31.000Z
|
2022-01-26T03:20:28.000Z
|
source/backend/hiai/execution/NPUPooling.cpp
|
qaz734913414/MNN
|
a5d5769789054a76c6e4dce2ef97d1f45b0e7e2d
|
[
"Apache-2.0"
] | null | null | null |
source/backend/hiai/execution/NPUPooling.cpp
|
qaz734913414/MNN
|
a5d5769789054a76c6e4dce2ef97d1f45b0e7e2d
|
[
"Apache-2.0"
] | 1
|
2021-11-24T06:26:27.000Z
|
2021-11-24T06:26:27.000Z
|
//
// NPUPooling.cpp
// MNN
//
// Created by MNN on 2019/09/07.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include "NPUPooling.hpp"
#include "NPUBackend.hpp"
using namespace std;
namespace MNN {
NPUPooling::NPUPooling(MNN::Backend *b, const MNN::Op *op, const std::vector<Tensor *> &inputs, const std::vector<MNN::Tensor *> &outputs) : NPUCommonExecution(b, op) {
}
ErrorCode NPUPooling::onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) {
mNpuBackend->setNetworkInput(inputs, mOp);
auto opName = mOp->name()->str();
shared_ptr<ge::op::Pooling> pooling(new ge::op::Pooling(opName));
auto poolParam = mOp->main_as_Pool();
// 0:NOTSET, 6:SAME 5:VALID. defaul default value is 0:NOTSET
auto pad_mode = 0;
int data_mode = 0;
if (PoolPadType_VALID == poolParam->padType()) {
pad_mode = 5;
data_mode = 1;
} else if (PoolPadType_SAME == poolParam->padType()) {
pad_mode = 6;
data_mode = 1;
}
// 0:max pooling 1:avg pooling 2:L2 pooling
auto mode = 0; // TODO
if (PoolType_MAXPOOL == poolParam->type()) {
mode = 0;
} else if (PoolType_AVEPOOL == poolParam->type()) {
mode = 1;
}
int64_t kernelH = poolParam->kernelY();
int64_t kernelW = poolParam->kernelX();
if(poolParam->isGlobal() == true) {
kernelH = inputs[0]->height();
kernelW = inputs[0]->width();
}
auto xOp = mNpuBackend->getInputOps(mOp);
int64_t strideWidth = std::max(poolParam->strideX(), 1);
int64_t strideHeight = std::max(poolParam->strideY(), 1);
if (poolParam->isGlobal() == true &&
kernelH%2 == 0 && kernelW%2==0 && kernelH*kernelW >65535) {
shared_ptr<ge::op::Pooling> pooling2X2(new ge::op::Pooling(opName+"_2x2"));
(*pooling2X2)
.set_input_x(*xOp.get()).set_attr_data_mode(0)
.set_attr_pad_mode(0).set_attr_ceil_mode(0)
.set_attr_mode(mode)
.set_attr_pad(ge::AttrValue::LIST_INT({0, 0, 0, 0})) // 上下左右
.set_attr_window(ge::AttrValue::LIST_INT({2, 2}))
.set_attr_stride(ge::AttrValue::LIST_INT({2, 2}))
.set_attr_global_pooling(false);
(*pooling)
.set_input_x(*pooling2X2.get())
.set_attr_data_mode(data_mode) // data_mode, DOMI_CAFFE_DATA_MODE =0, TENSORFLOW_DATA_MODE = 1. TODO
.set_attr_pad_mode(pad_mode)
.set_attr_ceil_mode(0) // pooling ceil mode, 0: DOMI_POOLING_CEIL, 1:DOMI_POOLING_FLOOR
.set_attr_mode(mode)
.set_attr_pad(ge::AttrValue::LIST_INT(
{poolParam->padY(), poolParam->padY(), poolParam->padX(), poolParam->padX()})) // 上下左右
.set_attr_window(ge::AttrValue::LIST_INT({kernelH/2, kernelW/2}))
.set_attr_stride(ge::AttrValue::LIST_INT({strideHeight, strideWidth}))
.set_attr_global_pooling(poolParam->isGlobal());
mNpuBackend->setOutputOps(mOp, {pooling2X2,pooling});
} else {
(*pooling)
.set_input_x(*xOp.get())
.set_attr_data_mode(data_mode) // data_mode, DOMI_CAFFE_DATA_MODE =0, TENSORFLOW_DATA_MODE = 1. TODO
.set_attr_pad_mode(pad_mode)
.set_attr_ceil_mode(0) // pooling ceil mode, 0: DOMI_POOLING_CEIL, 1:DOMI_POOLING_FLOOR
.set_attr_mode(mode)
.set_attr_pad(ge::AttrValue::LIST_INT(
{poolParam->padY(), poolParam->padY(), poolParam->padX(), poolParam->padX()})) // 上下左右
.set_attr_window(ge::AttrValue::LIST_INT({kernelH, kernelW}))
.set_attr_stride(ge::AttrValue::LIST_INT({strideHeight, strideWidth}))
.set_attr_global_pooling(poolParam->isGlobal());
mNpuBackend->setOutputOps(mOp, {pooling});
}
return NO_ERROR;
}
NPUCreatorRegister<TypedCreator<NPUPooling>> __pooling_op(OpType_Pooling);
} // namespace MNN
| 39.41
| 169
| 0.622685
|
WillTao-RD
|
bf0ff78d485d4e2c1a4c9f181941382f4affc4b7
| 9,795
|
cpp
|
C++
|
AmyEdit/src/Panels/SceneHierarchyPanel.cpp
|
CloseRange/AmyWare
|
24f19cb9c983aae318c459d3dcf47ff752824d18
|
[
"Apache-2.0"
] | null | null | null |
AmyEdit/src/Panels/SceneHierarchyPanel.cpp
|
CloseRange/AmyWare
|
24f19cb9c983aae318c459d3dcf47ff752824d18
|
[
"Apache-2.0"
] | null | null | null |
AmyEdit/src/Panels/SceneHierarchyPanel.cpp
|
CloseRange/AmyWare
|
24f19cb9c983aae318c459d3dcf47ff752824d18
|
[
"Apache-2.0"
] | null | null | null |
#include "SceneHierarchyPanel.h"
#include <imgui/imgui.h>
#include <imgui/imgui_internal.h>
#include "AmyWare/Scene/Components.h"
#include <glm\gtc\type_ptr.hpp>
namespace AmyWare {
SceneHierarchyPanel::SceneHierarchyPanel(const Ref<Scene>& context) {
SetContext(context);
}
void SceneHierarchyPanel::SetContext(const Ref<Scene>& context) {
this->context = context;
selectionContext = {};
}
void SceneHierarchyPanel::OnImGuiRender() {
ImGui::Begin("Scene");
context->registry.each([&](auto entityID) {
Entity entity = { entityID, context.get() };
DrawEntityNode(entity);
});
if (ImGui::IsMouseDown(0) && ImGui::IsWindowHovered()) {
selectionContext = {};
}
if (ImGui::BeginPopupContextWindow(0, 1, false)) {
if (ImGui::MenuItem("Create Empty Entity"))
context->CreateEntity("Empty Entity");
ImGui::EndPopup();
}
ImGui::End();
ImGui::Begin("Properties");
if (selectionContext) {
DrawComponents(selectionContext);
}
ImGui::End();
}
void SceneHierarchyPanel::DrawEntityNode(Entity entity) {
auto& tag = entity.Get<CTag>().Tag;
auto sel = (selectionContext == entity) ? ImGuiTreeNodeFlags_Selected : 0;
ImGuiTreeNodeFlags flags = sel | ImGuiTreeNodeFlags_OpenOnArrow;
flags |= ImGuiTreeNodeFlags_SpanAvailWidth;
bool opened = ImGui::TreeNodeEx((void*)(uint64_t)(uint32_t)entity, flags, tag.c_str());
if (ImGui::IsItemClicked()) {
selectionContext = entity;
}
bool deleted = false;
if (ImGui::BeginPopupContextItem()) {
if (ImGui::MenuItem("Delete Entity")) deleted = true;
ImGui::EndPopup();
}
if (opened) {
ImGui::Text("A good ol' test");
ImGui::TreePop();
}
if (deleted) {
if (selectionContext == entity) selectionContext = {};
context->DestroyEntity(entity);
}
}
static ImVec2 PushVecControl(const std::string& label, int count=3, float columnWidth = 100.0f) {
ImGui::PushID(label.c_str());
ImGui::Columns(2);
ImGui::SetColumnWidth(0, columnWidth);
ImGui::Text(label.c_str());
ImGui::NextColumn();
ImGui::PushMultiItemsWidths(count, ImGui::CalcItemWidth());
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2{ 0, 0 });
float lineHeight = GImGui->Font->FontSize + GImGui->Style.FramePadding.y * 2.0f;
return { lineHeight + 3.0f, lineHeight };
}
static void PopVecControl() {
ImGui::PopStyleVar();
ImGui::Columns(1);
ImGui::PopID();
}
static void AddVecButton(float& value, char* name, char* name2, ImVec4 c1, ImVec4 c2, ImVec2 buttonSize, float resetValue = 0.0f) {
ImGuiIO& io = ImGui::GetIO();
auto boldFont = io.Fonts->Fonts[0];
ImGui::PushStyleColor(ImGuiCol_Button, c1);
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, c2);
ImGui::PushStyleColor(ImGuiCol_ButtonActive, c1);
ImGui::PushFont(boldFont);
if (ImGui::Button(name, buttonSize)) value = resetValue;
ImGui::PopFont();
ImGui::PopStyleColor(3);
ImGui::SameLine();
ImGui::DragFloat(name2, &value, 0.1f, 0.0f, 0.0f, "%.2f");
ImGui::PopItemWidth();
}
static void DrawVec3Control(const std::string& label, glm::vec3& values, float resetValue = 0.0f) {
ImVec2 buttonSize = PushVecControl(label, 3, 100.0f);
AddVecButton(values.x, "X", "##X", { 0.8f, 0.1f, 0.15f, 1.0f }, { 0.9f, 0.2f, 0.2f, 1.0f }, buttonSize, resetValue);
ImGui::SameLine();
AddVecButton(values.y, "Y", "##Y", { 0.2f, 0.7f, 0.2f, 1.0f }, { 0.3f, 0.8f, 0.3f, 1.0f }, buttonSize, resetValue);
ImGui::SameLine();
AddVecButton(values.z, "Z", "##Z", { 0.1f, 0.25f, 0.8f, 1.0f }, { 0.2f, 0.35f, 0.9f, 1.0f }, buttonSize, resetValue);
PopVecControl();
}
static void DrawVecPosition2D(const std::string& label, glm::vec3& values, float resetValue = 0.0f) {
ImVec2 buttonSize = PushVecControl(label, 2, 100.0f);
AddVecButton(values.x, "X", "##X", { 0.8f, 0.1f, 0.15f, 1.0f }, { 0.9f, 0.2f, 0.2f, 1.0f }, buttonSize, resetValue);
ImGui::SameLine();
AddVecButton(values.y, "Y", "##Y", { 0.1f, 0.25f, 0.8f, 1.0f }, { 0.2f, 0.35f, 0.9f, 1.0f }, buttonSize, resetValue);
PopVecControl();
}
static void DrawVecRotation2D(const std::string& label, glm::vec3& values, float resetValue = 0.0f) {
ImVec2 buttonSize = PushVecControl(label, 2, 100.0f);
AddVecButton(values.z, "R", "##R", { 0.25f, 0.1f, 0.8f, 1.0f }, { 0.35f, 0.2f, 0.9f, 1.0f }, buttonSize, resetValue);
PopVecControl();
}
static void DrawVecScale2D(const std::string& label, glm::vec3& values, float resetValue = 1.0f) {
ImVec2 buttonSize = PushVecControl(label, 2, 100.0f);
AddVecButton(values.x, "W", "##W", { 0.8f, 0.1f, 0.15f, 1.0f }, { 0.9f, 0.2f, 0.2f, 1.0f }, buttonSize, resetValue);
ImGui::SameLine();
AddVecButton(values.y, "H", "##H", { 0.1f, 0.25f, 0.8f, 1.0f }, { 0.2f, 0.35f, 0.9f, 1.0f }, buttonSize, resetValue);
PopVecControl();
}
void SceneHierarchyPanel::DrawComponents(Entity entity) {
if (entity.Has<CTag>()) {
auto& tag = entity.Get<CTag>().Tag;
char buffer[256];
memset(buffer, 0, sizeof(buffer));
strcpy_s(buffer, sizeof(buffer), tag.c_str());
if (ImGui::InputText("##Tag", buffer, sizeof(buffer))) {
tag = std::string(buffer);
}
}
ImGui::SameLine();
ImGui::PushItemWidth(-1);
if (ImGui::Button("Add Component"))
ImGui::OpenPopup("AddComponent");
if (ImGui::BeginPopup("AddComponent")) {
if (ImGui::MenuItem("Camera")) {
selectionContext.Add<CCamera>();
ImGui::CloseCurrentPopup();
}
if (ImGui::MenuItem("Sprite Renderer")) {
selectionContext.Add<CSpriteRenderer>();
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
ImGui::PopItemWidth();
DrawComp<CTransform>("Transform", entity, false, [](auto& component) {
const char* strs[] = { "0D", "1D", "2D", "3D" };
const char* viewPersp = strs[(int)component.ViewPerspective];
if (ImGui::BeginCombo("Perspective", viewPersp)) {
bool sel2 = component.ViewPerspective == Perspective::TWO;
bool sel3 = component.ViewPerspective == Perspective::THREE;
if (ImGui::Selectable("2D", sel2))
component.ViewPerspective = Perspective::TWO;
if (ImGui::Selectable("3D", sel3))
component.ViewPerspective = Perspective::THREE;
if (sel2 || sel3) {
ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
switch (component.ViewPerspective) {
case Perspective::TWO:
{
DrawVecPosition2D("Position", component.Position);
DrawVecScale2D("Scale", component.Scale, 1.0f);
DrawVecRotation2D("Rotation", component.Rotation);
break;
}
case Perspective::THREE:
{
DrawVec3Control("Position", component.Position);
DrawVec3Control("Rotation", component.Rotation);
DrawVec3Control("Scale", component.Scale, 1.0f);
break;
}
}
});
DrawComp<CCamera>("Camera", entity, true, [](auto& component) {
auto& camera = component.Camera;
ImGui::Checkbox("Primary", &component.Primary);
const char* projectionStrings[] = { "Perspective", "Orthographic" };
const char* cProjectionString = projectionStrings[(int)camera.GetProjectionType()];
if (ImGui::BeginCombo("Projection", cProjectionString)) {
for (int i = 0; i < 2; i++) {
bool sel = cProjectionString == projectionStrings[i];
if (ImGui::Selectable(projectionStrings[i], sel)) {
cProjectionString = projectionStrings[i];
camera.SetProjectionType((SceneCamera::ProjectionType) i);
}
if (sel) {
ImGui::SetItemDefaultFocus();
}
}
ImGui::EndCombo();
}
if (camera.GetProjectionType() == SceneCamera::ProjectionType::Perspective) {
float oSize = glm::degrees(camera.GetPerspectiveFOV());
if (ImGui::DragFloat("Vertical FOV", &oSize)) camera.SetPerspectiveFOV(glm::radians(oSize));
float oNear = camera.GetPerspectiveNearClip();
if (ImGui::DragFloat("Near Clip", &oNear)) camera.SetPerspectiveNearClip(oNear);
float oFar = camera.GetPerspectiveFarClip();
if (ImGui::DragFloat("Far Clip", &oFar)) camera.SetPerspectiveFarClip(oFar);
} else {
float oSize = camera.GetOrthographicSize();
if (ImGui::DragFloat("Size", &oSize)) camera.SetOrthographicSize(oSize);
float oNear = camera.GetOrthographicNearClip();
if (ImGui::DragFloat("Near Clip", &oNear)) camera.SetOrthographicNearClip(oNear);
float oFar = camera.GetOrthographicFarClip();
if (ImGui::DragFloat("Far Clip", &oFar)) camera.SetOrthographicFarClip(oFar);
ImGui::Checkbox("Fixed Aspect Ratio", &component.FixedAspectRatio);
}
});
DrawComp<CSpriteRenderer>("Sprite Renderer", entity, true, [](auto& component) {
ImGui::ColorEdit4("Color", glm::value_ptr(component.Color));
});
}
template<typename T, typename UIFunction>
void SceneHierarchyPanel::DrawComp(const std::string& text, Entity entity, bool destroyable, UIFunction uiFunction) {
if (!entity.Has<T>()) return;
auto& component = entity.Get<T>();
ImVec2 contentRegion = ImGui::GetContentRegionAvail();
ImGuiTreeNodeFlags flags = 0;
flags |= ImGuiTreeNodeFlags_DefaultOpen;
flags |= ImGuiTreeNodeFlags_AllowItemOverlap;
flags |= ImGuiTreeNodeFlags_Framed;
flags |= ImGuiTreeNodeFlags_SpanAvailWidth;
flags |= ImGuiTreeNodeFlags_AllowItemOverlap;
flags |= ImGuiTreeNodeFlags_FramePadding;
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2{ 4, 4 });
float lineHeight = GImGui->Font->FontSize + GImGui->Style.FramePadding.y * 2.0f;
ImGui::Separator();
bool open = ImGui::TreeNodeEx((void*)typeid(T).hash_code(), flags, text.c_str());
ImGui::PopStyleVar();
ImGui::SameLine(contentRegion.x - lineHeight * 0.5f);
if (ImGui::Button("+", ImVec2{ lineHeight, lineHeight })) {
ImGui::OpenPopup("ComponentSettings");
}
bool removeComponent = false;
if (ImGui::BeginPopup("ComponentSettings")) {
if (ImGui::MenuItem("Remove Component"))
removeComponent = true;
ImGui::EndPopup();
}
if (open) {
uiFunction(component);
ImGui::TreePop();
}
if (removeComponent)
entity.Remove<T>();
}
}
| 33.775862
| 132
| 0.682083
|
CloseRange
|
bf11636d653416d30f32bd1dfe53771d53d06f52
| 2,704
|
cpp
|
C++
|
src/session.cpp
|
smr-llc/wooten-server
|
b6b347d3b7547e26883838f71e28726154ea6809
|
[
"MIT"
] | null | null | null |
src/session.cpp
|
smr-llc/wooten-server
|
b6b347d3b7547e26883838f71e28726154ea6809
|
[
"MIT"
] | null | null | null |
src/session.cpp
|
smr-llc/wooten-server
|
b6b347d3b7547e26883838f71e28726154ea6809
|
[
"MIT"
] | 1
|
2021-03-29T20:19:06.000Z
|
2021-03-29T20:19:06.000Z
|
#include "session.h"
#include <random>
#include <iostream>
#include <unistd.h>
Session::Session()
{
static const char letters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist(0, sizeof(letters) - 2);
for (int i = 0; i < 4; i++) {
m_sid.push_back(letters[dist(rng)]);
}
m_cleanupThread = std::thread(&Session::connectionCleanup, this);
}
Session::~Session() {
}
std::string Session::sid() const {
return m_sid;
}
std::shared_ptr<PacketHandler> Session::join(ConnectionHandler *conn, const JoinData &data) {
conn->setSession(m_sid, data);
conn->sendResponse(PTYPE_JOINED, conn->joinedData(), sizeof(JoinedData));
{
std::lock_guard<std::mutex> guard(this->m_mutex);
for (auto connPair : m_conns) {
conn->sendResponse(PTYPE_JOINED, connPair.second->joinedData(), sizeof(JoinedData));
}
m_conns.emplace(conn->connId(), conn);
}
notify(PTYPE_JOINED, conn->joinedData(), sizeof(JoinedData));
std::vector<PacketHandlerFn> funcs;
funcs.push_back(heartbeatHandler());
std::shared_ptr<PacketHandler> pktHandler(new PacketHandler(funcs));
return pktHandler;
}
void Session::notify(uint8_t type, const void *data, size_t dataLen) {
std::lock_guard<std::mutex> guard(this->m_mutex);
for (auto connPair : m_conns) {
connPair.second->sendResponse(type, data, dataLen);
}
}
void Session::connectionCleanup() {
std::vector<JoinedData> deletions;
while (true) {
deletions.clear();
{
std::lock_guard<std::mutex> guard(this->m_mutex);
for (auto it = m_conns.cbegin(); it != m_conns.cend();) {
if (it->second->done()) {
deletions.push_back(*it->second->joinedData());
delete it->second;
it = m_conns.erase(it);
}
else {
it++;
}
}
}
for (auto deletion : deletions) {
notify(PTYPE_LEFT, &deletion, sizeof(JoinedData));
}
sleep(2);
}
}
PacketHandlerFn Session::heartbeatHandler() {
return [this](ConnectionHandler *conn, ConnPkt &pkt, bool &close) {
if (pkt.type != PTYPE_HEARTBEAT) {
return std::shared_ptr<PacketHandler>();
}
std::cout << "\nReceived heartbeat, responding...\n";
conn->sendResponse(PTYPE_HEARTBEAT);
std::cout << "Sending UDP packet for NAT holepunch\n\n";
conn->sendNatHolepunch();
return std::shared_ptr<PacketHandler>();
};
}
| 28.765957
| 96
| 0.597633
|
smr-llc
|
bf166650635a3d1e5c2fee133a70c6b6fe18e59a
| 7,951
|
cpp
|
C++
|
src/engine/core/file/platform_file.cpp
|
LunarGameTeam/Lunar-GameEngine
|
b387d7008525681fe06db8811f4f7ee95aa7aaf1
|
[
"MIT"
] | 4
|
2020-08-07T02:18:13.000Z
|
2021-07-08T09:46:11.000Z
|
src/engine/core/file/platform_file.cpp
|
LunarGameTeam/Lunar-GameEngine
|
b387d7008525681fe06db8811f4f7ee95aa7aaf1
|
[
"MIT"
] | null | null | null |
src/engine/core/file/platform_file.cpp
|
LunarGameTeam/Lunar-GameEngine
|
b387d7008525681fe06db8811f4f7ee95aa7aaf1
|
[
"MIT"
] | null | null | null |
#include "platform_file.h"
#include "core/object/object.h"
#include "core/file/file_subsystem.h"
#include <boost/filesystem.hpp>
#include <filesystem>
namespace luna
{
LSharedPtr<LFileStream> WindowsFileManager::OpenAsStream(const LPath &path, OpenMode mode)
{
LSharedPtr<LFileStream> file = MakeShared<LFileStream>();
file->m_file.open(path.AsStringAbs(), (int)mode);
if (file->m_file.fail())
{
LogErrorFormat(E_Core, g_Failed, "Open File: {0} Failed", path.AsString().c_str());
return NULL;
}
return file;
}
bool WindowsFileManager::ReadStringFromFile(const LPath &path, LString &res)
{
LSharedPtr<LFileStream> file = MakeShared<LFileStream>();
file->m_file.open(path.AsStringAbs(), (int)OpenMode::In);
if (file->m_file.fail())
{
LogErrorFormat(E_Core, g_Failed, "Open File: {0} Failed", path.AsString().c_str());
return false;
}
std::stringstream stream;
stream << file->m_file.rdbuf();
res.Assign(stream.str());
return true;
}
bool WindowsFileManager::IsExists(const LPath &path)
{
return boost::filesystem::exists(*path.AsString());
}
bool WindowsFileManager::IsDirctory(const LPath &path)
{
return boost::filesystem::is_directory(*path.AsString());
}
bool WindowsFileManager::IsFile(const LPath &path)
{
return boost::filesystem::is_regular_file(*path.AsString());
}
bool WindowsFileManager::DeleteFile(const LPath &path)
{
return boost::filesystem::remove(*path.AsString());
}
bool WindowsFileManager::CreateDirectory(const LPath &path)
{
return boost::filesystem::create_directory(*path.AsString());
}
bool WindowsFileManager::CreateFile(const LPath &path)
{
throw std::logic_error("The method or operation is not implemented.");
}
const LString &WindowsFileManager::EngineDir()
{
return m_EngineDir;
}
bool WindowsFileManager::GetFileInfo(const LPath &path, LFileInfo &result, bool recursive /*= false*/)
{
std::filesystem::path p(path.AsStringAbs().c_str());
if (!std::filesystem::exists(p))
{
return false;
}
std::filesystem::directory_entry file(p);
result.is_folder = file.is_directory();
result.path = file.path().string();
#ifdef _WIN32
result.path.ReplaceAll("\\", "/");
#endif
for (const auto &entry : std::filesystem::directory_iterator(p))
{
LString path = entry.path().string();
#ifdef _WIN32
path.ReplaceAll("\\", "/");
#endif
auto &info = result.folder_contents[path];
info.is_folder = entry.is_directory();
info.path = path;
if (info.is_folder && recursive)
{
GetFileInfo(LPath(info.path), info, recursive);
info.is_folder_contents_init = true;
}
}
if (result.is_folder)
result.is_folder_contents_init = true;
return true;
}
bool WindowsFileManager::GetFileInfoRecursive(const LPath &path, LFileInfo &result, bool recursive /*= false*/)
{
std::filesystem::path p(path.AsStringAbs().c_str());
if (!std::filesystem::exists(p))
{
return false;
}
std::filesystem::directory_entry file(p);
for (const auto &entry : std::filesystem::recursive_directory_iterator(p))
{
LString path = entry.path().string();
#ifdef _WIN32
path.ReplaceAll("\\", "/");
#endif
auto &info = result.folder_contents[path];
info.is_folder = entry.is_directory();
info.path = path;
}
return true;
}
bool WindowsFileManager::WriteStringToFile(const LPath &path, const LString &res)
{
LSharedPtr<LFileStream> file = MakeShared<LFileStream>();
file->m_file.open(path.AsStringAbs(), (int)OpenMode::Out | (int)OpenMode::Trunc);
if (file->m_file.fail())
{
LogError(E_Core, g_Failed, "open file failed");
return false;
}
file->m_file << res;
file->m_file.flush();
file->m_file.close();
return true;
}
bool WindowsFileManager::DisposeFileManager()
{
m_pending_lock.lock();
io_loop = false;
m_pending_lock.unlock();
delete m_io_thread;
m_io_thread = nullptr;
m_pending_lock.lock();
while (!m_pending_queue.empty()) m_pending_queue.pop();
m_pending_lock.unlock();
return true;
}
LSharedPtr<LFile> WindowsFileManager::WriteSync(const LPath &path, const LVector<byte> &data)
{
HANDLE file_handle = ::CreateFileA(path.AsStringAbs().c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, NULL, NULL);
LSharedPtr<LFile> file = MakeShared<LFile>();
if (file_handle == INVALID_HANDLE_VALUE)
{
LogErrorFormat(E_Core, g_Failed, "Open File: {0} Failed", path.AsString().c_str());
return file;
}
DWORD size = data.size();
file->data = data;
file->path = path.AsStringAbs();
DWORD actual_size = 0;
::WriteFile(file_handle, file->data.data(), size, &actual_size, NULL);
file->is_ok = true;
return LSharedPtr<LFile>();
}
LSharedPtr<FileAsyncHandle> WindowsFileManager::ReadAsync(const LPath &path, FileAsyncCallback callback)
{
LSharedPtr<FileAsyncHandle> async_handle = MakeShared<FileAsyncHandle>();
//组装异步Handle
async_handle->callback = callback;
async_handle->file = MakeShared<LFile>();
async_handle->state = AsyncState::PendingQueue;
async_handle->path = path.AsStringAbs();
m_pending_lock.lock();
m_pending_queue.push(async_handle);
m_pending_lock.unlock();
return async_handle;
}
LSharedPtr<LFile> WindowsFileManager::ReadSync(const LPath &path)
{
HANDLE file_handle = ::CreateFileA(path.AsStringAbs().c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
LSharedPtr<LFile> file = MakeShared<LFile>();
if (file_handle == INVALID_HANDLE_VALUE)
{
LogErrorFormat(E_Core, g_Failed, "Open File: {0} Failed", path.AsString().c_str());
return file;
}
DWORD size = GetFileSize(file_handle, NULL);
file->data.resize(size);
file->path = path.AsStringAbs();
DWORD actual_size = 0;
::ReadFile(file_handle, file->data.data(), size, &actual_size, NULL);
file->is_ok = true;
return file;
}
VOID CALLBACK WindowsFileManager::FileCompleteCallback(
DWORD dwErrorCode, // 对于此次操作返回的状态
DWORD dwNumberOfBytesTransfered, // 告诉已经操作了多少字节,也就是在IRP里的Infomation
LPOVERLAPPED lpOverlapped // 这个数据结构
)
{
static WindowsFileManager *instance = (WindowsFileManager *)gEngine->GetSubsystem<FileSystem>()->GetPlatformFileManager();
LSharedPtr<FileAsyncHandle> handle = instance->m_running_handles[lpOverlapped];
handle->callback(handle);
handle->state = AsyncState::Finished;
instance->m_running_lock.lock();
instance->m_running_handles.erase(lpOverlapped);
delete lpOverlapped;
instance->m_running_lock.unlock();
}
void WindowsFileManager::IO_Thread()
{
while (io_loop)
{
{
if (m_pending_queue.empty())
goto END;
//取AsyncHandle并进行处理
LSharedPtr<FileAsyncHandle> async_handle = m_pending_queue.front();
m_pending_lock.lock();
m_pending_queue.pop();
m_pending_lock.unlock();
HANDLE file_handle = ::CreateFileA(async_handle->path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
if (file_handle == INVALID_HANDLE_VALUE)
goto END;
LSharedPtr<LFile> file = async_handle->file;
DWORD size = GetFileSize(file_handle, NULL);
DWORD actual_size = 0;
OVERLAPPED *overlap = new OVERLAPPED();
memset(overlap, 0, sizeof(OVERLAPPED));
file->data.resize(size);
file->path = async_handle->path;
//创建overlap事件
async_handle->state = AsyncState::Running;
bool rc = ReadFileEx(file_handle, file->data.data(), size, overlap, WindowsFileManager::FileCompleteCallback); //进入alterable
if (!rc)
goto END;
m_running_lock.lock();
m_running_handles[overlap] = async_handle;
m_running_lock.unlock();
}
END:
SleepEx(0, TRUE);
continue;
}
}
bool WindowsFileManager::InitFileManager()
{
TCHAR tempPath[1000];
GetModuleFileName(NULL, tempPath, MAX_PATH);
m_ApplicationPath = LString(tempPath);
GetCurrentDirectory(MAX_PATH, tempPath); //获取程序的当前目录
m_EngineDir = LString(tempPath);
m_EngineDir.ReplaceAll("\\", "/");
m_ApplicationPath.ReplaceAll("\\", "/");
size_t pos = m_ApplicationPath.FindLast("/");
m_io_thread = new LThread(std::bind(&WindowsFileManager::IO_Thread, this));
return true;
}
}
| 27.323024
| 165
| 0.729342
|
LunarGameTeam
|
bf179a406977a3402cd101f3a7692becd16fcd49
| 1,534
|
cpp
|
C++
|
Sources/Components/Image.cpp
|
Mikyan0207/OOP_indie_studio_2019
|
6b7f49346b44c8db33d75000c1603239aabdd6e0
|
[
"Unlicense",
"MIT"
] | null | null | null |
Sources/Components/Image.cpp
|
Mikyan0207/OOP_indie_studio_2019
|
6b7f49346b44c8db33d75000c1603239aabdd6e0
|
[
"Unlicense",
"MIT"
] | null | null | null |
Sources/Components/Image.cpp
|
Mikyan0207/OOP_indie_studio_2019
|
6b7f49346b44c8db33d75000c1603239aabdd6e0
|
[
"Unlicense",
"MIT"
] | null | null | null |
/*
** EPITECH PROJECT, 2020
** OOP_indie_studio_2019
** File description:
** Image
*/
#include <Components/Image.h>
#include <iostream>
Image::Image(GuiEnvironment *GUIEnv)
{
this->m_GUIEnvironment = GUIEnv;
}
bool Image::Initialize(void *args)
{
this->m_Image = m_GUIEnvironment->addImage({0, 0, 0, 0});
if (!this->m_Image)
return (false);
else if (args)
this->SetTexture(static_cast<Texture *>(args));
this->SetColor();
return (true);
}
void Image::Update(const float& deltaTime, GameManager* gameManager) {}
void Image::SetTexture(Texture *t)
{
if (!t)
return;
this->m_Texture = t;
this->m_Image->setImage(this->m_Texture);
this->m_Image->setScaleImage(true);
}
void Image::SetColor(const Color &c)
{
this->m_clr = c;
this->m_Image->setColor(this->m_clr);
}
void Image::SetSize(const irr::s32 &len, const irr::s32 &hei)
{
Recti dims = {
this->m_Image->getRelativePosition().UpperLeftCorner.X,
this->m_Image->getRelativePosition().UpperLeftCorner.Y,
this->m_Image->getRelativePosition().UpperLeftCorner.X + len,
this->m_Image->getRelativePosition().UpperLeftCorner.Y + hei
};
this->m_Image->setRelativePosition(dims);
}
void Image::SetPosition(const Vector2i &np)
{
this->m_Image->setRelativePosition(np);
}
GuiImage *Image::GetImage(void)
{
return (this->m_Image);
}
Texture *Image::GetTexture(void)
{
return (this->m_Texture);
}
const Color &Image::GetColor(void)
{
return this->m_clr;
}
| 21.013699
| 71
| 0.662321
|
Mikyan0207
|
bf258fb0e05ec9ce6872cce8fa382641e73be424
| 2,614
|
cc
|
C++
|
examples/services_example_cxx/baz/private/src/Baz.cc
|
rwalraven343/celix
|
353ac0d2e0f819f8f59d4cdf8ea1dfd701201d74
|
[
"Apache-2.0"
] | 1
|
2019-03-17T06:06:19.000Z
|
2019-03-17T06:06:19.000Z
|
examples/services_example_cxx/baz/private/src/Baz.cc
|
rwalraven343/celix
|
353ac0d2e0f819f8f59d4cdf8ea1dfd701201d74
|
[
"Apache-2.0"
] | 13
|
2019-02-21T21:27:44.000Z
|
2019-02-28T22:47:13.000Z
|
examples/services_example_cxx/baz/private/src/Baz.cc
|
rwalraven343/celix
|
353ac0d2e0f819f8f59d4cdf8ea1dfd701201d74
|
[
"Apache-2.0"
] | null | null | null |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "Baz.h"
#include <iostream>
void Baz::start() {
std::cout << "start Baz\n";
this->running = true;
pollThread = std::thread {&Baz::poll, this};
}
void Baz::stop() {
std::cout << "stop Baz\n";
this->running = false;
this->pollThread.join();
}
void Baz::addAnotherExample(IAnotherExample *e) {
std::lock_guard<std::mutex> lock(this->lock_for_examples);
this->examples.push_back(e);
}
void Baz::removeAnotherExample(IAnotherExample *e) {
std::lock_guard<std::mutex> lock(this->lock_for_examples);
this->examples.remove(e);
}
void Baz::addExample(const example_t *e) {
std::lock_guard<std::mutex> lock(this->lock_for_cExamples);
this->cExamples.push_back(e);
}
void Baz::removeExample(const example_t *e) {
std::lock_guard<std::mutex> lock(this->lock_for_cExamples);
this->cExamples.remove(e);
}
void Baz::poll() {
double r1 = 1.0;
double r2 = 1.0;
while (this->running) {
//c++ service required -> if component started always available
{
std::lock_guard<std::mutex> lock(this->lock_for_examples);
int index = 0;
for (IAnotherExample *e : this->examples) {
r1 = e->method(3, r1);
std::cout << "Result IAnotherExample " << index++ << " is " << r1 << "\n";
}
}
{
std::lock_guard<std::mutex> lock(this->lock_for_cExamples);
int index = 0;
for (const example_t *e : this->cExamples) {
double out;
e->method(e->handle, 4, r2, &out);
r2 = out;
std::cout << "Result example_t " << index++ << " is " << r2 << "\n";
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(4000));
}
}
| 31.119048
| 90
| 0.619357
|
rwalraven343
|
bf30007eee835492976ed7544372caf61250f4ad
| 1,299
|
cpp
|
C++
|
tests/core/time_stamp.cpp
|
jwuttke/daquiri-qpx
|
6606f4efca9bbe460e25e511fd94a8277c7e1fe6
|
[
"BSD-2-Clause"
] | 1
|
2018-09-26T16:18:38.000Z
|
2018-09-26T16:18:38.000Z
|
tests/core/time_stamp.cpp
|
jwuttke/daquiri-qpx
|
6606f4efca9bbe460e25e511fd94a8277c7e1fe6
|
[
"BSD-2-Clause"
] | 7
|
2018-09-20T08:45:34.000Z
|
2019-03-16T17:57:40.000Z
|
tests/core/time_stamp.cpp
|
martukas/daquiri-qpx
|
6606f4efca9bbe460e25e511fd94a8277c7e1fe6
|
[
"BSD-2-Clause"
] | null | null | null |
#include <core/time_stamp.h>
#include <gtest/gtest.h>
TEST(TimeStamp, Init)
{
DAQuiri::TimeStamp t1{};
ASSERT_EQ(DAQuiri::TimeBase(), t1.base());
ASSERT_EQ(0UL, t1.native());
ASSERT_EQ(0, t1.nanosecs());
DAQuiri::TimeStamp t2{1};
ASSERT_EQ(DAQuiri::TimeBase(), t2.base());
ASSERT_EQ(1UL, t2.native());
ASSERT_EQ(1, t2.nanosecs());
DAQuiri::TimeStamp t3{4,DAQuiri::TimeBase(3,4)};
ASSERT_EQ(DAQuiri::TimeBase(3,4), t3.base());
ASSERT_EQ(4UL, t3.native());
ASSERT_EQ(3, t3.nanosecs());
t3.set_native(12);
ASSERT_EQ(12UL, t3.native());
ASSERT_EQ(9, t3.nanosecs());
}
TEST(TimeStamp, Compare)
{
DAQuiri::TimeStamp t1{1}, t2{2}, t3{2}, t4{3};
ASSERT_TRUE(t2.same_base(t3));
ASSERT_EQ(t2, t3);
ASSERT_NE(t1, t2);
ASSERT_NE(t1, t4);
ASSERT_NE(t3, t4);
ASSERT_LT(t1, t2);
ASSERT_LT(t3, t4);
ASSERT_GT(t2, t1);
ASSERT_GT(t4, t3);
ASSERT_LE(t1, t3);
ASSERT_LE(t2, t3);
ASSERT_GE(t3, t1);
ASSERT_GE(t3, t2);
}
TEST(TimeStamp, Arithmetic)
{
DAQuiri::TimeStamp t1{2}, t2{1};
ASSERT_EQ(1, t1-t2);
ASSERT_EQ(4, t2.delayed(3).nanosecs());
t2.delay(3);
ASSERT_EQ(4, t2.nanosecs());
}
TEST(TimeStamp, DebugPrint)
{
DAQuiri::TimeStamp t1{1}, t2{1, DAQuiri::TimeBase{3,7}};
ASSERT_EQ("1", t1.debug());
ASSERT_EQ("1x(3/7)", t2.debug());
}
| 22.016949
| 58
| 0.645881
|
jwuttke
|
bf345a995862b5482174cdcd255e396688755c40
| 7,126
|
hpp
|
C++
|
include/fpt/Cell.hpp
|
frobnitzem/FastParticleToolkit
|
d5bc77f891d8aae18d777b8855ff4a6b3dd79761
|
[
"CC-BY-4.0"
] | null | null | null |
include/fpt/Cell.hpp
|
frobnitzem/FastParticleToolkit
|
d5bc77f891d8aae18d777b8855ff4a6b3dd79761
|
[
"CC-BY-4.0"
] | null | null | null |
include/fpt/Cell.hpp
|
frobnitzem/FastParticleToolkit
|
d5bc77f891d8aae18d777b8855ff4a6b3dd79761
|
[
"CC-BY-4.0"
] | null | null | null |
#pragma once
#include <algorithm>
#include <alpaka/alpaka.hpp>
#include <cassert>
#include <iostream>
#include <numeric>
#include <vector>
#include <stdint.h>
#define ATOMS_PER_CELL 32
/** Round up list of CellRange to this size */
#define CELL_LIST_PAD 32
namespace fpt {
struct CellEnergy {
uint32_t n[ATOMS_PER_CELL];
double en[ATOMS_PER_CELL];
};
/** Transpose of a cell -- holding max.
number of atoms per cell.
Algorithms work with this transpose.
*/
struct CellTranspose {
uint32_t n[ATOMS_PER_CELL]; // per-thread control block / atom number, indicating continuation, etc.
float x[ATOMS_PER_CELL]; // currently 1 for "present", 0 for "absent"
float y[ATOMS_PER_CELL];
float z[ATOMS_PER_CELL];
};
using Cell = CellTranspose; // keep it simple for now
/** Specifies a strip of cells indices along the x-direction.
* Would be nice to make an iterator.
*/
struct CellRange {
union {
struct {signed char i0, i1, j, k; };
uint32_t r;
};
CellRange(signed char _i0, signed char _i1, signed char _j, signed char _k) : i0(_i0),i1(_i1),j(_j),k(_k) {};
};
/** Flat copy of CellSorter class to be passed by value to device
*/
struct CellSorter_d {
const float h[3];
const int n[3];
CellSorter_d(float Lx, float Ly, float Lz, int nx, int ny, int nz)
: h{Lx/nx, Ly/ny, Lz/nz}, n{nx, ny, nz} {}
ALPAKA_FN_HOST_ACC inline
void decodeBin(const unsigned int bin, int& i, int& j, int& k) const {
i = bin % n[0];
j = (bin/n[0])%n[1];
k = bin/(n[0]*n[1]);
}
ALPAKA_FN_HOST_ACC inline
uint32_t calcBin(const int i, const int j, const int k) const {
return (k*n[1] + j)*n[0] + i;
}
ALPAKA_FN_HOST_ACC inline
uint32_t calcBinF(const float x, const float y, const float z) const {
return calcBin(x/h[0], y/h[1], z/h[2]);
}
/** Find idx such that Y[bin].n[idx] == 0
* and set Y[bin].n[idx] = ntype
*
* returns idx, the index of the newly
* added atom within the cell.
*
* Must be called simultaneously by all threads in a warp.
* The values of ntype and bin only matter on thread = srcThread.
*/
ALPAKA_NO_HOST_ACC_WARNING
template<typename TAcc, typename Idx>
ALPAKA_FN_ACC inline int addToBin(
TAcc const &acc, Cell *Y,
const Idx srcThread,
uint32_t ntype,
uint32_t bin) const {
auto const idx(alpaka::getIdx<alpaka::Block, alpaka::Threads>(acc)[0u]); // threadIdx.x
uint64_t active = alpaka::warp::activemask(acc);
bin = alpaka::warp::shfl(acc, int32_t(bin), srcThread);
ntype = alpaka::warp::shfl(acc, int32_t(ntype), srcThread);
Cell &cell = Y[bin];
int winner;
int32_t cont = 1;
while(cont) {
uint32_t n = cell.n[idx];
auto mask = alpaka::warp::ballot(acc, n != 0);
if(mask == active) { // no open slots
// FIXME: allocate continuation
return -1;
}
for(winner=0; (1<<winner) & mask; winner++); // find winning thread (first 0)
if(idx == winner) {
cont = alpaka::atomicOp<alpaka::AtomicCas>(acc,
&cell.n[idx], uint32_t(0), ntype);
}
cont = alpaka::warp::shfl(acc, cont, winner);
}
return winner;
}
};
struct CellSorter {
const float L[6]; // x,y,z,yx,zx,zy
const int n[3];
const unsigned int cells;
CellSorter(float Lx, float Ly, float Lz, int nx, int ny, int nz, float Lyx=0.0, float Lzx=0.0, float Lzy=0.0)
: L{Lx, Ly, Lz, Lyx,Lzx,Lzy}, n{nx, ny, nz}, cells(nx*ny*nz) { }
///! Return device-accessible copy of this class.
CellSorter_d device() const {
return CellSorter_d(L[0], L[1], L[2], n[0], n[1], n[2]);
}
// Create list of cells within cutoff Rc
// inclusive range to iterate over (i0,i1),(j,k)
std::vector<CellRange> list_cells(const float Rc) {
const float eps = 1e-6;
std::vector<CellRange> cell_list;
cell_list.reserve(28);
const float h_yx = L[3]/n[1];
const float h_zx = L[4]/n[2], h_zy = L[5]/n[2];
const float hz = L[2]/n[2], hy = L[1]/n[1], hx = L[0]/n[0];
float R2 = Rc*Rc;
signed char k0 = ceil(eps-(hz + Rc)/hz);
signed char k1 = floor((hz + Rc)/hz-eps);
//for(int k=0; ; k = -k+(k<=0)) { // 0, 1, -1, 2, -2, 3, ...
for(signed char k=k0; k<=k1; k++) {
signed char absk = k > 0 ? k-1 : (k < 0 ? -k-1 : 0);
float dz = absk*hz; // z-dist. to this pt
float R2z = R2 - dz*dz;
if(R2z < 0.0) break;
float y0 = -k*h_zy; // shifted base-pt.
signed char j0 = ceil((y0 - hy - sqrt(R2z))/hy+eps);
signed char j1 = floor((y0 + hy + sqrt(R2z))/hy-eps);
for(signed char j=j0; j<=j1; j++) {
float dy = fabs(j*hy - y0) - hy;
dy -= dy*(dy < 0.0);
float R2y = R2z - dy*dy;
if(R2y < 0.0) continue;
float x0 = -j*h_yx-k*h_zx; // shifted base-pt.
signed char i0 = ceil((x0 - hx - sqrt(R2y))/hx+eps);
signed char i1 = floor((x0 + hx + sqrt(R2y))/hx-eps);
if(i1 >= i0) {
cell_list.push_back(CellRange(i0,i1,j,k));
}
}
}
cell_list.push_back(CellRange(1,0,0,0)); // end-terminator
if(cell_list.size()%CELL_LIST_PAD != 0) {
for(int k = cell_list.size()%CELL_LIST_PAD; k<CELL_LIST_PAD; k++) { // pad to end of warp size
cell_list.push_back(CellRange(1,0,0,0)); // end-terminator
}
}
return cell_list;
}
};
/** Load atom information from cell index `far' into
the buffers n, x, y, z
*/
ALPAKA_NO_HOST_ACC_WARNING
template<typename TAcc>
ALPAKA_FN_ACC inline int load_cell(TAcc const& acc,
const Cell *X, const unsigned int fbin,
CellTranspose &far) {
auto const bin(alpaka::getIdx<alpaka::Grid, alpaka::Blocks>(acc)[0u]); // blockIdx.x
auto const idx(alpaka::getIdx<alpaka::Block, alpaka::Threads>(acc)[0u]); // threadIdx.x
const Cell &A = X[fbin];
far.n[idx] = A.n[idx];
far.x[idx] = A.x[idx];
far.y[idx] = A.y[idx];
far.z[idx] = A.z[idx];
return fbin == bin;
}
}
| 35.277228
| 117
| 0.504771
|
frobnitzem
|
bf3f14675e169e3c482ff016dfb08f6a2c5806b5
| 8,300
|
cpp
|
C++
|
src/sos_mosek.cpp
|
lihaokun/sparsesos
|
262102948ebc4253b72456d6079a2a2b4686cb58
|
[
"Apache-2.0"
] | 2
|
2020-06-25T08:34:31.000Z
|
2020-09-16T03:58:33.000Z
|
src/sos_mosek.cpp
|
lihaokun/sparsesos
|
262102948ebc4253b72456d6079a2a2b4686cb58
|
[
"Apache-2.0"
] | null | null | null |
src/sos_mosek.cpp
|
lihaokun/sparsesos
|
262102948ebc4253b72456d6079a2a2b4686cb58
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
#include <fstream>
#include <sstream>
#include "fusion.h"
#include "polynomial/polynomial.hpp"
#include "sos_mosek.hpp"
#include "sos.hpp"
#ifndef mosek_v
#define mosek_v 8
#endif
using namespace std;
using namespace polynomial;
using namespace mosek::fusion;
using namespace monty;
namespace sparsesos{
vector<monomial> sos_support_mosek(atomic_polynomial<polynomial::monomial,long>&p,std::size_t polydim,int numthreads)
{
if (p.empty())
{
return vector<monomial>();
}
//std::cout<<"poly length:"<<p.size()<<"\n";
int m=polydim;
int n=p.size();
std::cout<<"poly size:"<<n<<" poly dim:"<<m<<"\n";
auto A1 = new_array_ptr<double, 1>(n*(m+1));
for(int i=0;i<n*(m+1);++i)
(*A1)[i]=0;
int n1=0;
int degmax=-1;
int degmin=-1;
double dd;
vector<int> deg_maxv(m);
for (auto &i:deg_maxv)
i=-1;
vector<int> deg_minv(m);
for (auto &i:deg_maxv)
i=-1;
for(auto &i:p){
//std::cout<<i.first.str()<<" "<<i.first.deg()<<"\n";
if ((int)(i.first.deg()/2)>degmax)
degmax=i.first.deg()/2;
if ((int)(i.first.deg()/2)<degmin || degmin<0)
degmin=i.first.deg()/2;
//std::cout<<((i.first.deg()/2))<<" "<<(degmax)<<" "<<degmin<<"\n";
for(auto &j:i.first){
dd=double(j.second)/2;
(*A1)[n1*(m+1)+j.first]=dd;
if (dd>deg_maxv[j.first])
deg_maxv[j.first]=dd;
if (dd<deg_minv[j.first] || deg_minv[j.first]<0)
deg_minv[j.first]=dd;
}
(*A1)[n1*(m+1)+m]=-1;
++n1;
}
auto A=Matrix::dense(n,m+1,A1);
//std::cout<<p.str()<<"\n";
// for (auto &i:deg_maxv)
// std::cout<<i<<" ";
// std::cout<<degmax<<std::endl;
// for (auto &i:deg_minv)
// std::cout<<i<<" ";
//std::cout<<degmin<<std::endl;
if (degmax==-1)
{
return vector<monomial>();
}
vector<int> num(m,0);//={0};
//;
//num[m]=-1;
//num[m-1]=-1;
int snum=0;
//num[snum++]=0;num[snum++]=0;num[snum++]=0;num[snum++]=0;num[snum++]=0;
//num[snum++]=1;num[snum++]=1;num[snum++]=0;num[snum++]=0;num[snum++]=1;
bool b=num_init(num,snum,deg_maxv,deg_minv,degmax,degmin);
#if mosek_v==8
auto C=new_array_ptr<double, 1>(m+1);
(*C)[m]=0;
vector<int> num1(m,0);
#endif
auto Co=new_array_ptr<double, 1>(m+1);
(*Co)[m]=-1;
var_pair* mono=new var_pair[m];
for(int i=0;i<m;++i)
{
mono[i].first=i;
(*Co)[i]=0;
#if mosek_v==8
(*C)[i]=0;
#endif
}
vector<monomial> monos;
int num_mono=0;
auto M=new Model();//auto _M = finally([&]() { M->dispose(); });
if (numthreads)
M->setSolverParam("numThreads",numthreads);
auto X=M->variable( m+1, Domain::unbounded() );//new_array_ptr<int,1>({m+1,1})
M->constraint("c",Expr::mul(A,X),Domain::lessThan(0,n));
auto c1=M->constraint("c1",Expr::dot(Co,X),Domain::greaterThan(0.0));
//auto y=Expr::dot(C,X);
cout<<"Initially poly...\n";
while (b){
++num_mono;
//if ((num_mono % 100)==0)
// std::cout<<"Initially "<<num_mono<<" monomials.\r";
for(n1=0;n1<m;++n1)
if (num[n1]>=0)
{
#if mosek_v==8
(*C)[n1]=num[n1]-num1[n1];
#endif
(*Co)[n1]=num[n1];
mono[n1].second=num[n1];
}
else{
#if mosek_v==8
(*C)[n1]=0-num1[n1];
#endif
(*Co)[n1]=0;
mono[n1].second=0;
}
#if mosek_v==8
num1=num;
c1->add(Expr::dot(C,X));
#else
c1->update(Expr::dot(Co,X));
#endif
M->objective("obj", ObjectiveSense::Maximize, Expr::dot(Co,X));
M->solve();
if (M->getPrimalSolutionStatus()==SolutionStatus::Optimal && M->primalObjValue()>=-1e-5)
{
monos.push_back(monomial(mono,m));
//std::cout<<monos.back().str()<<"\n";
}
else
if (M->getPrimalSolutionStatus()==SolutionStatus::Undefined)
{
monos.push_back(monomial(mono,m));
//std::cout<<monos.back().str()<<"\n";
}
b=num_next(num,snum,deg_maxv,deg_minv,degmax,degmin);
}
std::cout<<"Initially "<<num_mono<<" monomials.\n";
std::cout<<"Keeping "<<monos.size()<<" monomials.\n";
M->dispose();
delete [] mono;
return monos;
}
bool SOS_solver_mosek(polynomial::atomic_polynomial<polynomial::monomial,long>&p,std::vector<polynomial::monomial> &points,std::vector<std::vector<polynomial::var>> &L,
std::vector<std::vector<double>> & ans,int numthreads)
{
std::size_t size=L.size();
std::size_t tmp_size;
std::vector<monty::rc_ptr<mosek::fusion::Variable>> X(size);
std::map<polynomial::monomial,std::size_t> dct;
auto tmp_it=dct.begin();
std::vector<monty::rc_ptr<mosek::fusion::Expression>> exp;
std::vector<double> value;
polynomial::monomial mono;
auto M=new Model();
if (numthreads)
M->setSolverParam("numThreads",numthreads);
M->setLogHandler([ ](const std::string & msg) { std::cout << msg << std::flush; } );
//auto exp_obj=Expr::zeros();
for(std::size_t l=0;l<size;++l)
{
tmp_size=L[l].size();
X[l]=M->variable("X"+std::to_string(l),Domain::inPSDCone(tmp_size));
for(std::size_t i=0;i!=tmp_size;++i )
for(std::size_t j=i;j!=tmp_size;++j)
{
mono=points[L[l][i]]*points[L[l][j]];
tmp_it=dct.find(mono);
if (tmp_it==dct.end())
{
if (i==j)
exp.push_back(X[l]->index(i,j)->asExpr());
else
exp.push_back(Expr::add(X[l]->index(i,j),X[l]->index(j,i)));
dct[mono]=exp.size()-1;
value.push_back(p[mono]);
}
else
if (i==j)
exp[tmp_it->second]=Expr::add(exp[tmp_it->second],X[l]->index(i,j));
else
exp[tmp_it->second]=Expr::add(exp[tmp_it->second],
Expr::add(X[l]->index(i,j),X[l]->index(j,i)));
}
}
for(std::size_t i=0;i!=exp.size();i++)
{
M->constraint(exp[i],Domain::equalsTo(value[i]));
}
M->objective("obj",ObjectiveSense::Minimize,Expr::zeros(1));
M->solve();
//std::vector<std::vector<double>> ans(size);
bool tmp_b=(M->getPrimalSolutionStatus()==SolutionStatus::Optimal);
if (tmp_b)
{
ans.clear();
ans.resize(size);
for (int i=0;i<size;++i)
{
tmp_size=L[i].size();
ans[i].resize(tmp_size*tmp_size);
auto tmp_x=X[i]->level();
for (int k1=0;k1<tmp_size*tmp_size;++k1)
ans[i][k1]=(*tmp_x)[k1];
}
bool tmp_b=(M->getPrimalSolutionStatus()==SolutionStatus::Optimal);
}
M->dispose();
return tmp_b;
}
}
| 36.725664
| 174
| 0.441687
|
lihaokun
|
bf3f9af36c733040ca6a9e89811a3513e7ea6273
| 900
|
cpp
|
C++
|
#0382.linked-list-random-node.cpp
|
hosomi/LeetCode
|
aba8fae8e37102b33dba8fd4adf1f018c395a4db
|
[
"MIT"
] | null | null | null |
#0382.linked-list-random-node.cpp
|
hosomi/LeetCode
|
aba8fae8e37102b33dba8fd4adf1f018c395a4db
|
[
"MIT"
] | null | null | null |
#0382.linked-list-random-node.cpp
|
hosomi/LeetCode
|
aba8fae8e37102b33dba8fd4adf1f018c395a4db
|
[
"MIT"
] | null | null | null |
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
Solution(ListNode* head) {
this->head = head;
}
int getRandom() {
ListNode *cursor = head;
ListNode *probability = head;
int count = 0;
while (cursor != nullptr) {
if (rand() % (count + 1) == count) {
probability = cursor;
}
cursor = cursor->next;
count++;
}
return probability->val;
}
private:
ListNode *head;
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(head);
* int param_1 = obj->getRandom();
*/
| 21.95122
| 64
| 0.523333
|
hosomi
|
bf41fec8ddd30780a2e009e0bae7421426052a42
| 2,877
|
hpp
|
C++
|
CreateGraph_stats.hpp
|
ExcitedStates/CONTACT
|
536704447cee2b40021c85c6c1208d94abcbff9a
|
[
"MIT"
] | null | null | null |
CreateGraph_stats.hpp
|
ExcitedStates/CONTACT
|
536704447cee2b40021c85c6c1208d94abcbff9a
|
[
"MIT"
] | null | null | null |
CreateGraph_stats.hpp
|
ExcitedStates/CONTACT
|
536704447cee2b40021c85c6c1208d94abcbff9a
|
[
"MIT"
] | null | null | null |
/*
CONTACT: COntact Networks Through Alternate Conformation Transitions
Henry van den Bedem, Gira Bhabha, Kun Yang, Peter Wright, James S. Fraser
e-mail: vdbedem@stanford.edu, james.fraser@ucsf.edu
Copyright (C) 2013 Stanford University
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:
This entire text, including 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, CONTRIBUTORS 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 _CREATE_GRAPH_
#define _CREATE_GRAPH_
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cstdio>
#include <fstream>
#include <cfloat>
#include <stack>
#include <list>
#include <numeric>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <mmdb/mmdb_manager.h>
struct Node {
int ResInd;
PPCAtom atoms;
int atomNo;
AltLoc altLoc;
};
class Dynamic_Graph {
public:
Dynamic_Graph() {}
bool ReadFile(std::string);
bool SetParameter(std::string, double, int, std::string);
bool RunChains(int MolNo);
bool CreateGraph(int MolNo, ChainID);
void FindPath(std::multimap<int, int>&, std::vector<Node>&, std::vector<std::vector<double> >&, std::vector<std::vector<bool> >&, const std::vector<std::vector<double> >&, const std::vector<std::vector<std::pair < std::string, std::string > > >& );
void BuildPath(std::vector<Node>&, std::multimap<int, int>&, std::vector<std::vector<int> >&, std::vector<std::vector<bool> >&, std::vector<std::vector<double> >&, std::vector<std::pair<int, int> >, const std::vector<std::vector<double> >&, std::vector<double>&, const std::vector<std::vector<std::pair < std::string, std::string > > >& );
void ProProcess();
private:
PCMMDBManager myPCMMDBManager;
int uddHandle_relief, uddHandle_norelief;
bool isMChain(PCAtom);
int ModelNo;
std::vector<int> graph;
std::vector<PCResidue> pcresidues;
std::string file;
double ratio;
int length;
bool isSideChain;
};
#endif
| 37.363636
| 343
| 0.724713
|
ExcitedStates
|
bf433971dbb334aae3030e1fa709ae1cebae7d58
| 3,323
|
cpp
|
C++
|
Stereolabs/Source/SpatialMapping/Private/Core/SpatialMappingCubemapManager.cpp
|
stereolabs/zed-unreal-plugin
|
0fabf29edc84db1126f0c4f73b9ce501e322be96
|
[
"MIT"
] | 38
|
2018-02-27T22:53:56.000Z
|
2022-02-10T05:46:51.000Z
|
Stereolabs/Source/SpatialMapping/Private/Core/SpatialMappingCubemapManager.cpp
|
HuangArmagh/zed-unreal-plugin
|
3bd8872577f49e2eb5f6cb8a6a610a4c786f6104
|
[
"MIT"
] | 14
|
2018-05-26T03:15:16.000Z
|
2022-03-02T14:34:10.000Z
|
Stereolabs/Source/SpatialMapping/Private/Core/SpatialMappingCubemapManager.cpp
|
HuangArmagh/zed-unreal-plugin
|
3bd8872577f49e2eb5f6cb8a6a610a4c786f6104
|
[
"MIT"
] | 16
|
2018-01-23T22:55:34.000Z
|
2021-12-20T18:34:08.000Z
|
//======= Copyright (c) Stereolabs Corporation, All rights reserved. ===============
#include "SpatialMappingPrivatePCH.h"
#include "SpatialMapping/Public/Core/SpatialMappingCubemapManager.h"
ASpatialMappingCubemapManager::ASpatialMappingCubemapManager()
:
bCanUpdateTextureTarget(true),
CubemapWorker(nullptr),
Cubemap(nullptr),
TextureTarget(nullptr),
Camera(nullptr)
{
PrimaryActorTick.bCanEverTick = true;
PrimaryActorTick.TickGroup = ETickingGroup::TG_PrePhysics;
RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
Camera = CreateDefaultSubobject<USceneCaptureComponentCube>(TEXT("MainCamera"), true);
Camera->SetupAttachment(RootComponent);
Camera->bCaptureEveryFrame = false;
Camera->bCaptureOnMovement = false;
}
void ASpatialMappingCubemapManager::BeginPlay()
{
Super::BeginPlay();
if (TextureTarget && TextureTarget->IsValidLowLevel())
{
SetTextureTarget(TextureTarget);
}
CubemapWorker = new FSpatialMappingCubemapRunnable(&CubemapProxy);
CubemapWorker->Start(1.0f);
CubemapWorker->Sleep();
}
void ASpatialMappingCubemapManager::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
Super::EndPlay(EndPlayReason);
if (CubemapWorker)
{
CubemapWorker->EnsureCompletion();
delete CubemapWorker;
CubemapWorker = nullptr;
}
}
void ASpatialMappingCubemapManager::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
if (CubemapProxy.bComplete)
{
// Suspend thread
CubemapWorker->Sleep();
// Building complete can update texture target
bCanUpdateTextureTarget = true;
// Reset flag
CubemapProxy.bComplete = false;
// Reset proxy cubemap
CubemapProxy.Cubemap = nullptr;
// Update cubemap resource
Cubemap->UpdateResource();
// Notify
OnCubemapBuildComplete.Broadcast(Cubemap);
}
}
#if WITH_EDITOR
void ASpatialMappingCubemapManager::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
FName PropertyName = (PropertyChangedEvent.Property != NULL) ? PropertyChangedEvent.Property->GetFName() : NAME_None;
if (PropertyName == GET_MEMBER_NAME_CHECKED(ASpatialMappingCubemapManager, TextureTarget))
{
SetTextureTarget(TextureTarget);
}
Super::PostEditChangeProperty(PropertyChangedEvent);
}
bool ASpatialMappingCubemapManager::CanEditChange(const UProperty* InProperty) const
{
FName PropertyName = InProperty->GetFName();
if (PropertyName == GET_MEMBER_NAME_CHECKED(ASpatialMappingCubemapManager, TextureTarget))
{
return CubemapWorker == nullptr;
}
return Super::CanEditChange(InProperty);
}
#endif
bool ASpatialMappingCubemapManager::BuildCubemap(const FName& Name)
{
// Cubemap build not finished
if (!CubemapWorker->IsSleeping())
{
return false;
}
bCanUpdateTextureTarget = false;
// create the cube texture or retrieve the existing one
Cubemap = NewObject<UTextureCube>(
GetTransientPackage(),
Name,
RF_Transient);
CubemapProxy.Cubemap = Cubemap;
CubemapWorker->GetPixels();
CubemapWorker->Awake();
return true;
}
void ASpatialMappingCubemapManager::CaptureScene()
{
Camera->CaptureScene();
}
bool ASpatialMappingCubemapManager::SetTextureTarget(UTextureRenderTargetCube* NewTextureTarget)
{
if (!bCanUpdateTextureTarget)
{
return false;
}
Camera->TextureTarget = NewTextureTarget;
CubemapProxy.TextureTarget = NewTextureTarget;
return true;
}
| 24.07971
| 118
| 0.778814
|
stereolabs
|
bf533ec40a115310e3f2b43e1c70310801f29de8
| 919
|
cpp
|
C++
|
qt-ts-csv/3rdParty/xlsx/OpenXLSX/@library/@openxlsx/implementation/sources/XLFont_Impl.cpp
|
Stivvo/qt-ts-csv
|
5b262dbc1250fffd465c2114ffbb0a8e63c3c1ac
|
[
"MIT"
] | 2
|
2019-08-07T10:02:20.000Z
|
2021-11-03T17:09:42.000Z
|
@library/@openxlsx/implementation/sources/XLFont_Impl.cpp
|
tomay3000/OpenXLSX
|
a04b46e6af038b3cd1aa674839218608a1de2cdd
|
[
"BSD-3-Clause"
] | null | null | null |
@library/@openxlsx/implementation/sources/XLFont_Impl.cpp
|
tomay3000/OpenXLSX
|
a04b46e6af038b3cd1aa674839218608a1de2cdd
|
[
"BSD-3-Clause"
] | null | null | null |
//
// Created by Kenneth Balslev on 04/06/2017.
//
#include "XLFont_Impl.h"
#include <sstream>
#include <pugixml.hpp>
using namespace std;
using namespace OpenXLSX;
std::map<string, Impl::XLFont> Impl::XLFont::s_fonts = {};
/**
* @details
*/
Impl::XLFont::XLFont(const string& name, unsigned int size, const XLColor& color, bool bold, bool italics, bool underline)
: m_fontNode(XMLNode()),
m_name(name),
m_size(size),
m_color(color),
m_bold(bold),
m_italics(italics),
m_underline(underline),
m_theme(""),
m_family(""),
m_scheme("") {
}
/**
* @details
*/
std::string Impl::XLFont::UniqueId() const {
stringstream str;
str << m_name << m_size << m_color.Hex();
if (m_bold)
str << "b";
if (m_italics)
str << "i";
if (m_underline)
str << "u";
return str.str();
}
| 18.755102
| 122
| 0.56148
|
Stivvo
|
bf5cca506c190d13af8fed69b02f7a07cf3f0f96
| 5,716
|
cpp
|
C++
|
src/RModelMat.cpp
|
chilingg/Redopera
|
a898eb269d5d3eba9ba5b14ef9b4209f615f4547
|
[
"MIT"
] | null | null | null |
src/RModelMat.cpp
|
chilingg/Redopera
|
a898eb269d5d3eba9ba5b14ef9b4209f615f4547
|
[
"MIT"
] | null | null | null |
src/RModelMat.cpp
|
chilingg/Redopera
|
a898eb269d5d3eba9ba5b14ef9b4209f615f4547
|
[
"MIT"
] | null | null | null |
#include <RModelMat.h>
using namespace Redopera;
RModelMat::RModelMat():
model_(1)
{
model_[2].z = 0;
}
RModelMat::RModelMat(RModelMat &&model):
model_(std::move(model.model_))
{
}
RModelMat &RModelMat::operator=(RModelMat &&model)
{
model_ = std::move(model.model_);
return *this;
}
RModelMat::RModelMat(float x, float y, float z, float width, float height):
model_(1)
{
setModel(x, y, z, width, height);
}
RModelMat::RModelMat(const RPointF &pos, const RSizeF &size):
RModelMat(pos.x(), pos.y(), pos.z(), size.width(), size.height())
{
}
RModelMat::RModelMat(const RRectF &rect, float depth):
RModelMat(rect.x(), rect.y(), depth, rect.width(), rect.height())
{
}
const glm::mat4 &RModelMat::model() const
{
return model_;
}
float RModelMat::top() const
{
return model_[3].y + std::abs(model_[1].y / 2);
}
float RModelMat::bottom() const
{
return model_[3].y - std::abs(model_[1].y / 2);
}
float RModelMat::left() const
{
return model_[3].x - std::abs(model_[0].x) / 2;
}
float RModelMat::right() const
{
return model_[3].x + std::abs(model_[0].x) / 2;
}
float RModelMat::depth() const
{
return model_[3].z;
}
float RModelMat::x() const
{
return model_[3].x - std::abs(model_[0].x) / 2;
}
float RModelMat::y() const
{
return model_[3].y - std::abs(model_[1].y / 2);
}
float RModelMat::centerX() const
{
return model_[3].x;
}
float RModelMat::centerY() const
{
return model_[3].y;
}
RPoint2F RModelMat::center() const
{
return { model_[3].x, model_[3].y };
}
RPointF RModelMat::pos() const
{
return RPointF(model_[3].x - std::abs(model_[0].x) / 2,
model_[3].y - std::abs(model_[1].y / 2),
model_[3].z);
}
float RModelMat::width() const
{
return std::abs(model_[0].x);
}
float RModelMat::height() const
{
return std::abs(model_[1].y);
}
RSizeF RModelMat::size() const
{
return RSizeF(std::abs(model_[0].x), std::abs(model_[1].y));
}
RRectF RModelMat::rect() const
{
return RRectF(pos(), size());
}
bool RModelMat::isFlipH() const
{
return model_[0].x < 0;
}
bool RModelMat::isFlipV() const
{
return model_[1].y < 0;
}
void RModelMat::move(float x, float y, float z)
{
model_[3].x += x; model_[3].y += y; model_[3].z += z;
}
void RModelMat::move(const RPoint2F &pos, float depth)
{
move(pos.x(), pos.y(), depth);
}
void RModelMat::setPos(float x, float y)
{
setPos(x, y, model_[3].z);
}
void RModelMat::setPos(float x, float y, float z)
{
model_[3].x = x + std::abs(model_[0].x / 2);
model_[3].y = y + std::abs(model_[1].y / 2);
model_[3].z = z;
}
void RModelMat::setPos(const RPoint2F &pos)
{
setPos(pos.x(), pos.y(), model_[3].z);
}
void RModelMat::setPos(const RPoint2F &pos, float depth)
{
setPos(pos.x(), pos.y(), depth);
}
void RModelMat::setDepth(float depth)
{
model_[3].z = depth;
}
void RModelMat::setCenterX(float x)
{
model_[3].x = x;
}
void RModelMat::setCenterY(float y)
{
model_[3].y = y;
}
void RModelMat::setCenter(float x, float y)
{
model_[3].x = x;
model_[3].y = y;
}
void RModelMat::setCenter(const RPoint2F &pos)
{
setCenter(pos.x(), pos.y());
}
void RModelMat::setLeft(float left)
{
model_[3].x = left + std::abs(model_[0].x / 2);
}
void RModelMat::setRight(float right)
{
model_[3].x = right - std::abs(model_[0].x / 2);
}
void RModelMat::setTop(float top)
{
model_[3].y = top - std::abs(model_[1].y / 2);
}
void RModelMat::setBottom(float bottom)
{
model_[3].y = bottom + std::abs(model_[1].y / 2);
}
void RModelMat::setWidth(float width)
{
model_[0].x = width;
}
void RModelMat::setHeight(float height)
{
model_[1].y = height;
}
void RModelMat::setSize(float width, float height)
{
model_[0].x = width;
model_[1].y = height;
}
void RModelMat::setSize(const RSizeF &size)
{
setWidth(size.width());
setHeight(size.height());
}
void RModelMat::flipH()
{
model_[0][0] *= -1;
}
void RModelMat::flipV()
{
model_[1][1] *= -1;
}
void RModelMat::setModel(float x, float y, float z, float width, float height)
{
model_[0].x = width;
model_[1].y = height;
model_[2].z = 0;
model_[3] = { x + width / 2.f, y + height / 2.f, z, 1 };
}
void RModelMat::setModel(const RPoint2F &pos, const RSizeF &size)
{
setModel(pos.x(), pos.y(), model_[3].z, size.width(), size.height());
}
void RModelMat::setModel(const RPoint2F &pos, const RSizeF &size, float depth)
{
setModel(pos.x(), pos.y(), depth, size.width(), size.height());
}
void RModelMat::setModel(const RRectF &rect)
{
setModel(rect.x(), rect.y(), model_[3].z, rect.width(), rect.height());
}
void RModelMat::setModel(const RRectF &rect, float depth)
{
setModel(rect.x(), rect.y(), depth, rect.width(), rect.height());
}
void RModelMat::setModel(const glm::mat4 &model)
{
model_ = model;
}
static thread_local char buf[256];
std::string RModelMat::toString() const
{
std::snprintf(buf, sizeof(buf),
"mat:(%10.3f, %10.3f, %10.3f, %10.3f)\n"
" (%10.3f, %10.3f, %10.3f, %10.3f)\n"
" (%10.3f, %10.3f, %10.3f, %10.3f)\n"
" (%10.3f, %10.3f, %10.3f, %10.3f). ",
model_[0][0], model_[1][0], model_[2][0], model_[3][0],
model_[0][1], model_[1][1], model_[2][1], model_[3][1],
model_[0][2], model_[1][2], model_[2][2], model_[3][2],
model_[0][3], model_[1][3], model_[2][3], model_[3][3]);
return buf;
}
std::string RModelMat::info() const
{
std::snprintf(buf, sizeof(buf), "(%.1f, %.1f, %.1f | w:%.1f, h:%.1f)", x(), y(), depth(), width(), height());
return buf;
}
| 19.181208
| 113
| 0.592897
|
chilingg
|
bf61c2a351364c2773b6279e898147b5a48a7d60
| 1,553
|
cpp
|
C++
|
Days 021 - 030/Day 25/SimpleRegexImplementation.cpp
|
LucidSigma/Daily-Coding-Problems
|
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
|
[
"MIT"
] | null | null | null |
Days 021 - 030/Day 25/SimpleRegexImplementation.cpp
|
LucidSigma/Daily-Coding-Problems
|
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
|
[
"MIT"
] | null | null | null |
Days 021 - 030/Day 25/SimpleRegexImplementation.cpp
|
LucidSigma/Daily-Coding-Problems
|
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <vector>
bool MatchSimpleRegex(const std::string& regex, const std::string& text)
{
std::vector<std::vector<bool>> matches(text.length() + 1, std::vector<bool>(regex.length() + 1));
matches[0][0] = true;
static constexpr char SINGLE_CHARACTER = '.';
static constexpr char MULTIPLE_CHARACTERS = '*';
for (unsigned int i = 1; i < matches[0].size(); i++)
{
if (regex[i - 1] == MULTIPLE_CHARACTERS)
{
matches[0][i] = matches[0][i - 2];
}
}
for (unsigned int i = 1; i < matches.size(); i++)
{
for (unsigned int j = 1; j < matches[i].size(); j++)
{
if ((regex[j - 1] == SINGLE_CHARACTER) || (regex[j - 1] == text[i - 1]))
{
matches[i][j] = matches[i - 1][j - 1];
}
else if (regex[j - 1] == MULTIPLE_CHARACTERS)
{
matches[i][j] = matches[i][j - 2];
if ((regex[j - 2] == SINGLE_CHARACTER) || (regex[j - 2] == text[i - 1]))
{
matches[i][j] = matches[i][j] || matches[i - 1][j];
}
}
else
{
matches[i][j] = false;
}
}
}
return matches[text.length()][regex.length()];
}
int main(int argc, const char* argv[])
{
std::cout << std::boolalpha;
std::cout << MatchSimpleRegex(".*at", "chat") << "\n";
std::cout << MatchSimpleRegex(".*at", "chats") << "\n";
std::cout << MatchSimpleRegex("ra.", "ray") << "\n";
std::cout << MatchSimpleRegex("ra.", "raymond") << "\n";
std::cout << MatchSimpleRegex(".*", "aaaaaaaaaaaaaa") << "\n";
std::cout << MatchSimpleRegex(".", "aaaaaaaaaaaaaa") << "\n";
std::cin.get();
return 0;
}
| 23.892308
| 98
| 0.562138
|
LucidSigma
|
bf6474174cfbf361bba5d46c7e07058d24cb3124
| 1,139
|
cpp
|
C++
|
src/Plugins/MoviePlugin/Movie2DebugRender.cpp
|
irov/Mengine
|
b76e9f8037325dd826d4f2f17893ac2b236edad8
|
[
"MIT"
] | 39
|
2016-04-21T03:25:26.000Z
|
2022-01-19T14:16:38.000Z
|
src/Plugins/MoviePlugin/Movie2DebugRender.cpp
|
irov/Mengine
|
b76e9f8037325dd826d4f2f17893ac2b236edad8
|
[
"MIT"
] | 23
|
2016-06-28T13:03:17.000Z
|
2022-02-02T10:11:54.000Z
|
src/Plugins/MoviePlugin/Movie2DebugRender.cpp
|
irov/Mengine
|
b76e9f8037325dd826d4f2f17893ac2b236edad8
|
[
"MIT"
] | 14
|
2016-06-22T20:45:37.000Z
|
2021-07-05T12:25:19.000Z
|
#include "Movie2DebugRender.h"
#include "Interface/RenderServiceInterface.h"
#include "Kernel/RenderVertex2D.h"
#include "Plugins/NodeDebugRenderPlugin/NodeDebugRenderServiceInterface.h"
namespace Mengine
{
//////////////////////////////////////////////////////////////////////////
Movie2DebugRender::Movie2DebugRender()
{
}
//////////////////////////////////////////////////////////////////////////
Movie2DebugRender::~Movie2DebugRender()
{
}
//////////////////////////////////////////////////////////////////////////
void Movie2DebugRender::_render( const RenderPipelineInterfacePtr & _renderPipeline, const RenderContext * _context, const Movie2 * _node, bool _hide )
{
_node->foreachRenderSlots( _renderPipeline, _context, [_hide]( Node * _node, const RenderPipelineInterfacePtr & _renderPipeline, const RenderContext * _context )
{
NODEDEBUGRENDER_SERVICE()
->renderDebugNode( NodePtr::from( _node ), _renderPipeline, _context, true, _hide );
} );
}
//////////////////////////////////////////////////////////////////////////
}
| 39.275862
| 169
| 0.514486
|
irov
|
bf6612e45244b632fd0c9de05a9fb4400e4af6e3
| 918
|
cpp
|
C++
|
zinot-engine/zinot-engine/eng/Window.cpp
|
patrykbajos/zinot-project
|
f5ab158bce6855b25b7f23c873f64bc4a9c867ba
|
[
"MIT"
] | null | null | null |
zinot-engine/zinot-engine/eng/Window.cpp
|
patrykbajos/zinot-project
|
f5ab158bce6855b25b7f23c873f64bc4a9c867ba
|
[
"MIT"
] | null | null | null |
zinot-engine/zinot-engine/eng/Window.cpp
|
patrykbajos/zinot-project
|
f5ab158bce6855b25b7f23c873f64bc4a9c867ba
|
[
"MIT"
] | null | null | null |
//
// Created by patryk on 10.05.16.
//
#include <gl_core_3_3.hpp>
#include "Window.hpp"
namespace Zinot
{
Window::Window(Engine * enginePtr)
{
parentEnginePtr = enginePtr;
}
void Window::open()
{
sfWindow.reset(new sf::Window(sf::VideoMode(800, 600), "OpenGL",
sf::Style::Default,
sf::ContextSettings(24, 8, 0, 3, 3, sf::ContextSettings::Core)));
sfWindow->setVerticalSyncEnabled(true);
gl::sys::LoadFunctions();
}
bool Window::enterMainLoop()
{
bool running = true;
while (running)
{
sf::Event event;
while (sfWindow->pollEvent(event))
{
if (event.type == sf::Event::Closed)
running = false;
}
gl::Clear(gl::COLOR_BUFFER_BIT);
gl::ClearColor(0.0f, 0.0f, 0.0f, 1.0f);
sfWindow->display();
}
return true;
}
void Window::close()
{
sfWindow->close();
}
}
| 17.653846
| 96
| 0.569717
|
patrykbajos
|
bf6b8f4b85d25a59d97526c87a274cc1aa56fa22
| 1,692
|
cpp
|
C++
|
metroid-rat-clone/metroid-rat-clone/TileMap.cpp
|
TiltedClone/metroid-rat-clone
|
41849df1b0ab6f0cf526bae23f5759e9e0eba5af
|
[
"MIT"
] | 2
|
2020-03-09T09:55:24.000Z
|
2020-11-17T11:16:51.000Z
|
metroid-rat-clone/metroid-rat-clone/TileMap.cpp
|
TiltedClone/metroid-rat-clone
|
41849df1b0ab6f0cf526bae23f5759e9e0eba5af
|
[
"MIT"
] | null | null | null |
metroid-rat-clone/metroid-rat-clone/TileMap.cpp
|
TiltedClone/metroid-rat-clone
|
41849df1b0ab6f0cf526bae23f5759e9e0eba5af
|
[
"MIT"
] | null | null | null |
#include "TileMap.h"
void TileMap::draw(sf::RenderTarget & target, sf::RenderStates states) const
{
states.transform *= getTransform();
states.texture = &m_tileset;
target.draw(m_vertices, states);
}
bool TileMap::loadTexture(const std::string & tileTextFile, sf::Vector2u tileSize, std::vector<std::vector<Tile>> &mapTiles, sf::Vector2u screenSize)
{
unsigned int width = mapTiles[0].size();
unsigned int height = mapTiles.size();
if (!m_tileset.loadFromFile(tileTextFile))
return false;
m_vertices.setPrimitiveType(sf::Quads);
m_vertices.resize(width * height * 4);
for (int mapY = 0; mapY < mapTiles.size(); mapY++)
for (int mapX = 0; mapX < mapTiles[mapY].size(); mapX++)
{
int tileType = mapTiles[mapY][mapX].tileNumber;
int textX = tileType % (m_tileset.getSize().x / tileSize.x);
int textY = tileType / (m_tileset.getSize().x / tileSize.x);
sf::Vertex* quad = &m_vertices[(mapX + mapY * width) * 4];
quad[0].position = sf::Vector2f(mapX * screenSize.y / height, mapY * screenSize.y/height);
quad[1].position = sf::Vector2f((mapX + 1) * screenSize.y / height, mapY * screenSize.y / height);
quad[2].position = sf::Vector2f((mapX + 1) * screenSize.y / height, (mapY + 1) * screenSize.y / height);
quad[3].position = sf::Vector2f(mapX * screenSize.y / height, (mapY + 1) * screenSize.y / height);
quad[0].texCoords = sf::Vector2f(textX * tileSize.x, textY * tileSize.y);
quad[1].texCoords = sf::Vector2f((textX + 1) * tileSize.x, textY * tileSize.y);
quad[2].texCoords = sf::Vector2f((textX + 1) * tileSize.x, (textY + 1) * tileSize.y);
quad[3].texCoords = sf::Vector2f(textX * tileSize.x, (textY + 1) * tileSize.y);
}
}
| 36
| 149
| 0.667849
|
TiltedClone
|
bf6c62c4ac6a9ff3caeb246f08b278700904c341
| 541
|
cpp
|
C++
|
Algorithms/HeuristicFunctions.cpp
|
adar2/AI-Project
|
b50a096a4b35cde346ac0e45ed29a52ae27cf300
|
[
"MIT"
] | 2
|
2021-06-13T13:54:34.000Z
|
2021-10-16T07:13:31.000Z
|
Algorithms/HeuristicFunctions.cpp
|
adar2/AI-Project
|
b50a096a4b35cde346ac0e45ed29a52ae27cf300
|
[
"MIT"
] | 2
|
2021-08-17T11:22:20.000Z
|
2022-01-08T15:55:01.000Z
|
Algorithms/HeuristicFunctions.cpp
|
adar2/AI-Project
|
b50a096a4b35cde346ac0e45ed29a52ae27cf300
|
[
"MIT"
] | 3
|
2021-03-05T19:11:05.000Z
|
2021-08-16T05:35:06.000Z
|
#include <algorithm>
#include <cmath>
double chebyshev_distance(const std::pair<int, int> &p1, const std::pair<int, int> &p2, double min_val) {
return min_val * std::max(abs(p1.first - p2.first), abs(p1.second - p2.second));
}
double normalized_euclidean_distance(const std::pair<int, int> &p1, const std::pair<int, int> &p2, double min_val) {
static double square_root = sqrt(2);
int dx = abs(p1.first - p2.first);
int dy = abs(p1.second - p2.second);
return min_val * sqrt(pow(dx, 2) + pow(dy, 2)) / square_root;
}
| 33.8125
| 116
| 0.669131
|
adar2
|
bf6dc06947a80e1805e4f49b9a51a8f0a1b7e510
| 4,321
|
cpp
|
C++
|
snippets/cpp/VS_Snippets_Winforms/System.Drawing.ClassicRectangleFExamples/CPP/form1.cpp
|
BohdanMosiyuk/samples
|
59d435ba9e61e0fc19f5176c96b1cdbd53596142
|
[
"CC-BY-4.0",
"MIT"
] | 834
|
2017-06-24T10:40:36.000Z
|
2022-03-31T19:48:51.000Z
|
snippets/cpp/VS_Snippets_Winforms/System.Drawing.ClassicRectangleFExamples/CPP/form1.cpp
|
BohdanMosiyuk/samples
|
59d435ba9e61e0fc19f5176c96b1cdbd53596142
|
[
"CC-BY-4.0",
"MIT"
] | 7,042
|
2017-06-23T22:34:47.000Z
|
2022-03-31T23:05:23.000Z
|
snippets/cpp/VS_Snippets_Winforms/System.Drawing.ClassicRectangleFExamples/CPP/form1.cpp
|
BohdanMosiyuk/samples
|
59d435ba9e61e0fc19f5176c96b1cdbd53596142
|
[
"CC-BY-4.0",
"MIT"
] | 1,640
|
2017-06-23T22:31:39.000Z
|
2022-03-31T02:45:37.000Z
|
#using <System.Data.dll>
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Drawing;
using namespace System::Collections;
using namespace System::ComponentModel;
using namespace System::Windows::Forms;
using namespace System::Data;
/// <summary>
/// Summary description for Form1.
/// </summary>
public ref class Form1: public System::Windows::Forms::Form
{
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container^ components;
public:
Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~Form1()
{
if ( components != nullptr )
{
delete components;
}
}
private:
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent()
{
this->components = gcnew System::ComponentModel::Container;
this->Size = System::Drawing::Size( 300, 300 );
this->Text = "Form1";
}
// Snippet for: M:System.Drawing.RectangleF.Inflate(System.Drawing.SizeF)
// <snippet1>
public:
void RectangleFInflateExample( PaintEventArgs^ e )
{
// Create a RectangleF structure.
RectangleF myRectF = RectangleF(100,20,100,100);
// Draw myRect to the screen.
Rectangle myRect = Rectangle::Truncate( myRectF );
e->Graphics->DrawRectangle( Pens::Black, myRect );
// Create a Size structure.
SizeF inflateSize = SizeF(100,0);
// Inflate myRect.
myRectF.Inflate( inflateSize );
// Draw the inflated rectangle to the screen.
myRect = Rectangle::Truncate( myRectF );
e->Graphics->DrawRectangle( Pens::Red, myRect );
}
// </snippet1>
// Snippet for: M:System.Drawing.RectangleF.Intersect(System.Drawing.RectangleF,System.Drawing.RectangleF)
// <snippet2>
public:
void RectangleFIntersectExample( PaintEventArgs^ e )
{
// Create two rectangles.
RectangleF firstRectangleF = RectangleF(0,0,75,50);
RectangleF secondRectangleF = RectangleF(50,20,50,50);
// Convert the RectangleF structures to Rectangle structures and draw them to the
// screen.
Rectangle firstRect = Rectangle::Truncate( firstRectangleF );
Rectangle secondRect = Rectangle::Truncate( secondRectangleF );
e->Graphics->DrawRectangle( Pens::Black, firstRect );
e->Graphics->DrawRectangle( Pens::Red, secondRect );
// Get the intersection.
RectangleF intersectRectangleF = RectangleF::Intersect( firstRectangleF, secondRectangleF );
// Draw the intersectRectangleF to the screen.
Rectangle intersectRect = Rectangle::Truncate( intersectRectangleF );
e->Graphics->DrawRectangle( Pens::Blue, intersectRect );
}
// </snippet2>
// Snippet for: M:System.Drawing.RectangleF.Union(System.Drawing.RectangleF,System.Drawing.RectangleF)
// <snippet3>
public:
void RectangleFUnionExample( PaintEventArgs^ e )
{
// Create two rectangles and draw them to the screen.
RectangleF firstRectangleF = RectangleF(0,0,75,50);
RectangleF secondRectangleF = RectangleF(100,100,20,20);
// Convert the RectangleF structures to Rectangle structures and draw them to the
// screen.
Rectangle firstRect = Rectangle::Truncate( firstRectangleF );
Rectangle secondRect = Rectangle::Truncate( secondRectangleF );
e->Graphics->DrawRectangle( Pens::Black, firstRect );
e->Graphics->DrawRectangle( Pens::Red, secondRect );
// Get the union rectangle.
RectangleF unionRectangleF = RectangleF::Union( firstRectangleF, secondRectangleF );
// Draw the unionRectangleF to the screen.
Rectangle unionRect = Rectangle::Truncate( unionRectangleF );
e->Graphics->DrawRectangle( Pens::Blue, unionRect );
}
// </snippet3>
};
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
int main()
{
Application::Run( gcnew Form1 );
}
| 29.195946
| 109
| 0.670215
|
BohdanMosiyuk
|
bf6dc0838311bdda88523957fc29177c2463ef49
| 1,999
|
cpp
|
C++
|
src/_leetcode/leet_124.cpp
|
turesnake/leetPractice
|
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
|
[
"MIT"
] | null | null | null |
src/_leetcode/leet_124.cpp
|
turesnake/leetPractice
|
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
|
[
"MIT"
] | null | null | null |
src/_leetcode/leet_124.cpp
|
turesnake/leetPractice
|
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
|
[
"MIT"
] | null | null | null |
/*
* ====================== leet_124.cpp ==========================
* -- tpr --
* CREATE -- 2020.06.10
* MODIFY --
* ----------------------------------------------------------
* 124. 二叉树中的最大路径和
*/
#include "innLeet.h"
#include "TreeNode1.h"
#include "ListNode.h"
namespace leet_124 {//~
// 因为有负数的存在,实际要检测的情况 非常复杂,很容易出错
// 后序遍历 49% 7%
class S{
int maxSum {INT_MIN};
// tp not null
// ret: 包含自身节点的 最大单路径和
int work( TreeNode *tp ){
int tpVal = tp->val;
if( !tp->left && !tp->right ){// leaf
maxSum = std::max(maxSum, tpVal);
return tpVal;
}// 以下情况,must not leaf
int vl = tp->left ? work(tp->left) : INT_MIN;
int vr = tp->right ? work(tp->right) : INT_MIN;
int bigSon = std::max(vl,vr);
//== 本树内,路径最大和,不用考虑向上传递 ==//
int innSum {0};
if(tpVal>=0){
innSum = tpVal;
if(vl>0){ innSum += vl; }
if(vr>0){ innSum += vr; }
}else{// 自己就是 负数
if( bigSon < 0 ){
// 说明, tpVal, vl,vr 都是负数,选最大的就行
innSum = std::max(tpVal, bigSon);
}else{
// 说明 vl,vr 至少有一个值 大于等于 0
// 最大链,要么是包含 tpVal 的大链,要么是 不含 tpVal 的小链
int all = tpVal;
if(tp->left){ all+=vl; }
if(tp->right){ all+=vr; }
innSum = std::max( bigSon, all );
}
}
maxSum = std::max( maxSum, innSum ); // 登记
//== 需要传递给上级的单链 ==//
// 不管 tpVal 是否为正,都要包含
// 但不一定要包含 叶子链
return bigSon>0 ? (tpVal+bigSon) : tpVal;
}
public:
// root not null
int maxPathSum( TreeNode* root ){
work(root);
return maxSum;
}
};
//=========================================================//
void main_(){
debug::log( "\n~~~~ leet: 124 :end ~~~~\n" );
}
}//~
| 22.977011
| 65
| 0.395198
|
turesnake
|
bf7152a455749bb6020c6d7e491cc7ab5d314b24
| 2,409
|
cpp
|
C++
|
2004/samples/editor/palettes/boltUI/CComBoltCmd.cpp
|
kevinzhwl/ObjectARXMod
|
ef4c87db803a451c16213a7197470a3e9b40b1c6
|
[
"MIT"
] | 1
|
2021-06-25T02:58:47.000Z
|
2021-06-25T02:58:47.000Z
|
2004/samples/editor/palettes/boltUI/CComBoltCmd.cpp
|
kevinzhwl/ObjectARXMod
|
ef4c87db803a451c16213a7197470a3e9b40b1c6
|
[
"MIT"
] | null | null | null |
2004/samples/editor/palettes/boltUI/CComBoltCmd.cpp
|
kevinzhwl/ObjectARXMod
|
ef4c87db803a451c16213a7197470a3e9b40b1c6
|
[
"MIT"
] | 3
|
2020-05-23T02:47:44.000Z
|
2020-10-27T01:26:53.000Z
|
//
//
// (C) Copyright 2002 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
//
#include "CComBoltCmd.h"
HRESULT CComBoltCmd::OnChanged(DISPID dispId)
{
switch(dispId) {
case DISPID_ALIGNMENT:
bGotAlignment = true;
break;
case DISPID_HEADDIAMETER:
bGotHeadDiameter = true;
break;
case DISPID_HEADHEIGHT:
bGotHeadHeight = true;
break;
case DISPID_HEADSIDES:
bGotHeadSides = true;
break;
case DISPID_MATERIALNAME:
bGotMaterialName = true;
break;
case DISPID_POSITION:
bGotPosition = true;
break;
case DISPID_SHAFTDIAMETER:
bGotShaftDiameter = true;
break;
case DISPID_SHAFTLENGTH:
bGotShaftLength = true;
break;
case DISPID_PARTNUMBER:
bGotPartNumber = true;
break;
case DISPID_THREADLENGTH:
bGotThreadLength = true;
break;
case DISPID_THREADWIDTH:
bGotThreadWidth = true;
break;
default:
break;
}
InterruptPrompt();
return S_OK;
}
HRESULT CComBoltCmd::OnRequestEdit(DISPID dispId)
{
return S_OK;
}
void CComBoltCmd::InterruptPrompt()
{
if (NULL != m_pDoc)
{
acDocManager->sendModelessInterrupt(m_pDoc);
// CPH RTMODELESS workaround
bModelessInterrupt = true;
}
}
| 28.678571
| 73
| 0.625571
|
kevinzhwl
|
bf73cd4b852b222b69ab67ad63615b2f0dd96757
| 1,782
|
hpp
|
C++
|
engines/First OGL Engine/include/Utils/Delegate.hpp
|
sltn011/OpenGL-Learning
|
7f3b8cd730ba9d300406cdd6608afb1db6d23b31
|
[
"MIT"
] | 1
|
2020-10-26T17:53:33.000Z
|
2020-10-26T17:53:33.000Z
|
engines/First OGL Engine/include/Utils/Delegate.hpp
|
sltn011/OpenGL-Learning
|
7f3b8cd730ba9d300406cdd6608afb1db6d23b31
|
[
"MIT"
] | null | null | null |
engines/First OGL Engine/include/Utils/Delegate.hpp
|
sltn011/OpenGL-Learning
|
7f3b8cd730ba9d300406cdd6608afb1db6d23b31
|
[
"MIT"
] | null | null | null |
/**
* @file Delegate.hpp
*/
#ifndef OGL_E1_DELEGATE
#define OGL_E1_DELEGATE
#include <memory>
namespace OGL::E1 {
/**
* @brief Delegate class to call member function of objects
*/
template<typename... Args>
class Delegate {
public:
Delegate(
) = default;
template<typename T, typename F>
Delegate(
T *Object,
F Method
) {
bind(Object, Method);
}
template<typename T, typename F>
void bind(
T *Object,
F Method
) {
m_invoker = std::make_unique<Invoker<T, F, Args...>>(Object, Method);
}
void operator()(
Args... args
) const {
if (m_invoker) {
m_invoker->invoke(std::forward<Args>(args)...);
}
}
protected:
template<typename... FArgs>
class BaseInvoker {
public:
virtual void invoke(
FArgs... args
) const = 0;
};
template<typename T, typename F, typename... FArgs>
struct Invoker : public BaseInvoker<FArgs...> {
public:
Invoker(
T *Object,
F Method
) {
m_object = Object;
m_method = Method;
}
virtual void invoke(
FArgs... args
) const override {
if (m_object && m_method) {
(m_object->*m_method)(std::forward<FArgs>(args)...);
}
}
private:
T *m_object;
F m_method;
};
std::unique_ptr<BaseInvoker<Args...>> m_invoker;
};
}
#endif // OGL_E1_DELEGATE
| 20.25
| 81
| 0.449495
|
sltn011
|
bf75dd3252eed30d0d700e27a1e273865d09f242
| 1,243
|
cpp
|
C++
|
Sankore-API/customWidgets/UBDockPaletteWidget.cpp
|
eaglezzb/rsdc
|
cce881f6542ff206bf286cf798c8ec8da3b51d50
|
[
"MIT"
] | null | null | null |
Sankore-API/customWidgets/UBDockPaletteWidget.cpp
|
eaglezzb/rsdc
|
cce881f6542ff206bf286cf798c8ec8da3b51d50
|
[
"MIT"
] | null | null | null |
Sankore-API/customWidgets/UBDockPaletteWidget.cpp
|
eaglezzb/rsdc
|
cce881f6542ff206bf286cf798c8ec8da3b51d50
|
[
"MIT"
] | null | null | null |
#include "UBDockPaletteWidget.h"
#include "devtools/memcheck.h"
/**
* \brief Constructor
*/
UBDockPaletteWidget::UBDockPaletteWidget(QWidget *parent, const char *name):QWidget(parent)
{
setObjectName(name);
}
/**
* \brief Destructor
*/
UBDockPaletteWidget::~UBDockPaletteWidget()
{
}
/**
* \brief Get the icon to the right
* @returns the icon pixmap
*/
QPixmap UBDockPaletteWidget::iconToRight()
{
return mIconToRight;
}
/**
* \brief Get the icon to the left
* @returns the icon pixmap
*/
QPixmap UBDockPaletteWidget::iconToLeft()
{
return mIconToLeft;
}
/**
* \brief Get the dock palette name
* @returns the dock palette name
*/
QString UBDockPaletteWidget::name()
{
return mName;
}
/**
* \brief Register the mode. When a widget registers a mode it means that it would be displayed on that mode
* @param mode as the given mode
*/
void UBDockPaletteWidget::registerMode(eUBDockPaletteWidgetMode mode)
{
if(!mRegisteredModes.contains(mode))
mRegisteredModes.append(mode);
}
/**
* \brief Handles the mode change event
* @param newMode as the new mode
*/
void UBDockPaletteWidget::slot_changeMode(eUBDockPaletteWidgetMode newMode)
{
this->setVisible(this->visibleInMode( newMode ));
}
| 18.552239
| 108
| 0.71601
|
eaglezzb
|
bf7c4ffc5f6b8cf7528f1d728c0b5965a969b61b
| 948
|
cpp
|
C++
|
prj/Raytracer/EntryPoint.cpp
|
vicutrinu/pragma-studios
|
181fd14d072ccbb169fa786648dd942a3195d65a
|
[
"MIT"
] | null | null | null |
prj/Raytracer/EntryPoint.cpp
|
vicutrinu/pragma-studios
|
181fd14d072ccbb169fa786648dd942a3195d65a
|
[
"MIT"
] | null | null | null |
prj/Raytracer/EntryPoint.cpp
|
vicutrinu/pragma-studios
|
181fd14d072ccbb169fa786648dd942a3195d65a
|
[
"MIT"
] | null | null | null |
#include <pragma/graphics/Mesh.h>
#include <pragma/graphics/import/Parsers.h>
#include <pragma/graphics/Camera.h>
#include <pragma/graphics/Material.h>
#include <pragma/image/Image.h>
#include <pragma/image/functions.h>
#include "Raytracer.h"
#include <stdio.h>
using namespace pragma;
#define IMAGE_SIZE 512
int main(int argc, char* argv[])
{
// Load ASE file
pragma::Mesh lMesh;
MaterialLibrary lMaterialLibrary(32);
ParseOBJ("scenes/Cornell.obj", lMesh, lMaterialLibrary);
// Create camera
Vector lCameraPos(0,27.5,95);
Camera lCamera;
lCamera.SetProjection(math::type_traits<Real>::DoublePi * 45 / 360, 1, 1, 150);
lCamera.SetTransform( lCameraPos, Vector(0,27.5,0), Vector(0,1,0) );
Image lImage(IMAGE_SIZE, IMAGE_SIZE);
Raytracer lRaytracer( lMesh, Point(0,55,0), lMaterialLibrary, 1, 1, 10 );
lRaytracer.Render( lCamera, lImage );
ExportToTGA(lImage, "out.tga");
return 0;
}
| 24.307692
| 81
| 0.698312
|
vicutrinu
|
bf7ccd2553a68ba57163ad80821f6b5885db3a23
| 4,176
|
cpp
|
C++
|
src/rynx/scheduler/context.cpp
|
Apodus/rynx
|
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
|
[
"MIT"
] | 11
|
2019-08-19T08:44:14.000Z
|
2020-09-22T20:04:46.000Z
|
src/rynx/scheduler/context.cpp
|
Apodus/rynx
|
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
|
[
"MIT"
] | null | null | null |
src/rynx/scheduler/context.cpp
|
Apodus/rynx
|
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
|
[
"MIT"
] | null | null | null |
#include <rynx/scheduler/task_scheduler.hpp>
#include <rynx/scheduler/context.hpp>
#include <rynx/scheduler/task.hpp>
#include <rynx/scheduler/barrier.hpp>
#include <iostream>
rynx::scheduler::context::context(context_id id, task_scheduler* scheduler) : m_id(id), m_scheduler(scheduler), m_tasks_parallel_for(rynx::scheduler::task_scheduler::numThreads+1){
m_resource_counters.resize(1024);
}
rynx::scheduler::task rynx::scheduler::context::findWork() {
rynx_profile("Profiler", "Find work self");
bool task_was_completed = false;
auto try_get_free_task = [this, &task_was_completed]() -> rynx::scheduler::task
{
task t;
if (m_tasks_parallel_for.deque(t)) {
if (t.is_for_each()) {
if (t.for_each_no_work_available()) {
if (t.for_each_all_work_completed()) {
task_was_completed = true;
if (t.m_enable_logging) {
logmsg("end parfor %s", t.name().c_str());
}
t.barriers().on_complete();
t = task();
task_finished();
}
else {
m_tasks_parallel_for.enque(std::move(t));
}
}
else {
rynx::scheduler::task copy = t;
t.completion_blocked_by(copy);
m_tasks_parallel_for.enque(std::move(t));
return copy;
}
}
else {
return t;
}
}
return {};
};
auto try_get_protected_task = [this]() -> rynx::scheduler::task
{
for (size_t i = 0; i < m_tasks.size(); ++i) {
auto& task = m_tasks[i];
if (task.barriers().can_start() & resourcesAvailableFor(task)) {
rynx::scheduler::task t(std::move(task));
m_tasks[i] = std::move(m_tasks.back());
m_tasks.pop_back();
reserve_resources(t.resources());
if (t.is_for_each()) {
rynx::scheduler::task copy = t;
m_tasks_parallel_for.enque(std::move(t));
return copy;
}
return t;
}
}
return {};
};
do {
task_was_completed = false;
if (m_taskMutex.try_lock())
{
{
task t = try_get_protected_task();
m_taskMutex.unlock();
if (t) {
return t;
}
}
{
task t = try_get_free_task();
if (t) {
return t;
}
}
}
else
{
{
task t = try_get_free_task();
if (t) {
return t;
}
}
{
m_taskMutex.lock();
task t = try_get_protected_task();
m_taskMutex.unlock();
if (t) {
return t;
}
}
}
} while (!m_tasks_parallel_for.empty() | task_was_completed);
return {};
}
rynx::scheduler::task_token rynx::scheduler::context::add_task(task task) {
return task_token(std::move(task));
}
bool rynx::scheduler::context::resourcesAvailableFor(const task& t) const {
int resources_in_use = 0;
for (uint64_t readResource : t.resources().read_requirements()) {
resources_in_use += m_resource_counters[readResource].writers.load();
}
for (uint64_t writeResource : t.resources().write_requirements()) {
resources_in_use += m_resource_counters[writeResource].writers.load();
resources_in_use += m_resource_counters[writeResource].readers.load();
}
return resources_in_use == 0;
}
void rynx::scheduler::context::schedule_task(task task) {
++m_task_counter;
++m_tasks_per_frame;
if (task.resources().empty() && task.barriers().can_start())
{
m_tasks_parallel_for.enque(std::move(task));
}
else
{
std::scoped_lock lock(m_taskMutex);
m_tasks.emplace_back(std::move(task));
}
}
void rynx::scheduler::context::dump() {
std::lock_guard<std::mutex> lock(m_taskMutex);
std::cout << m_tasks.size() << " tasks remaining" << std::endl;
for (auto&& task : m_tasks) {
(void)task;
std::cout << " barriers: " << task.barriers().can_start() << ", resources: " << resourcesAvailableFor(task) << " -- " << task.name() << std::endl;
task.barriers().dump();
// logmsg("%s barriers: %d, resources: %d", task.name().c_str(), task.barriers().can_start(), resourcesAvailableFor(task));
}
while (!m_tasks_parallel_for.empty()) {
task t;
m_tasks_parallel_for.deque(t);
if (t.is_for_each()) {
std::cout << "for each (" << t.name() << ")\n\tno work available: " << t.for_each_no_work_available() << "\n\tall work done: " << t.for_each_all_work_completed() << "\n";
}
else {
std::cout << "free task: " << t.name() << "\n";
}
}
}
| 24.857143
| 180
| 0.636015
|
Apodus
|
bf864a021de9a4e7c57229cfdf56bff986df13e8
| 7,163
|
cpp
|
C++
|
SuperPixel/readsuperpixeldat.cpp
|
netbeen/UncleZhou_UI
|
69ad47d1b6d41a63984e6448ef412afc1481bb89
|
[
"MIT"
] | 1
|
2019-06-06T02:26:27.000Z
|
2019-06-06T02:26:27.000Z
|
SuperPixel/readsuperpixeldat.cpp
|
netbeen/UncleZhou_UI
|
69ad47d1b6d41a63984e6448ef412afc1481bb89
|
[
"MIT"
] | null | null | null |
SuperPixel/readsuperpixeldat.cpp
|
netbeen/UncleZhou_UI
|
69ad47d1b6d41a63984e6448ef412afc1481bb89
|
[
"MIT"
] | null | null | null |
#include "readsuperpixeldat.h"
#include <cmath>
#include <fstream>
ReadSuperPixelDat::ReadSuperPixelDat()
{
}
#include <string>
#include "SuperPixel/SLICSuperpixels/SLIC.h"
#include "util.h"
void ReadSuperPixelDat::authorSegment(int superPixelCount)
{
const int width = this->image.cols;
const int height = this->image.rows;
// unsigned int (32 bits) to hold a pixel in ARGB format as follows:
// from left to right,
// the first 8 bits are for the alpha channel (and are ignored)
// the next 8 bits are for the red channel
// the next 8 bits are for the green channel
// the last 8 bits are for the blue channel
//unsigned int* pbuff = new UINT[sz];
ReadImage(pbuff, width, height);//YOUR own function to read an image into the ARGB format
//----------------------------------
// Initialize parameters
//----------------------------------
int k = superPixelCount;//Desired number of superpixels. 在此修改分成多少个super pixel
double m = 40;//Compactness factor. use a value ranging from 10 to 40 depending on your needs. Default is 10
int* klabels = new int[width*height];
int numlabels(0);
string filename = "yourfilename.jpg";
string savepath = "yourpathname";
//----------------------------------
// Perform SLIC on the image buffer
//----------------------------------
SLIC segment;
segment.PerformSLICO_ForGivenK(pbuff, width, height, klabels, numlabels, k, m);
// Alternately one can also use the function PerformSLICO_ForGivenStepSize() for a desired superpixel size
//----------------------------------
// Save the labels to a text file
//----------------------------------
segment.SaveSuperpixelLabels(klabels, width, height, filename, savepath);
//----------------------------------
// Draw boundaries around segments
//----------------------------------
segment.DrawContoursAroundSegments(pbuff, klabels, width, height, 0xff0000);
//----------------------------------
// Save the image with segment boundaries.
//----------------------------------
SaveSegmentedImageFile(pbuff, width, height);//YOUR own function to save an ARGB buffer as an image
//----------------------------------
// Clean up
//----------------------------------
if(pbuff) delete [] pbuff;
if(klabels) delete [] klabels;
}
void ReadSuperPixelDat::segmentSourceImage(){
this->image = cv::imread((Util::dirName+"/sourceImage.png").toUtf8().data());
this->size = this->image.cols * this->image.rows;
this->authorSegment();
this->authorRead();
}
void ReadSuperPixelDat::ReadImage(unsigned int* pbuff, int width,int height){//YOUR own function to read an image into the ARGB format
//std::cout << "ReadImage start" << std::endl;
const int sz = this->size;
this->pbuff = new unsigned int[sz];
//std::cout << "pbuff's address = " <<(pbuff) << std::endl;
unsigned int* ptr = this->pbuff;
for(int y_offset = 0; y_offset < this->image.rows; y_offset++){
for(int x_offset = 0; x_offset < this->image.cols; x_offset++){
cv::Vec3b color = this->image.at<cv::Vec3b>(y_offset,x_offset);
unsigned int tempResult = 1;
tempResult += color[0];
tempResult += color[1]*std::pow(2,8);
tempResult += color[2]*std::pow(2,16);
(*ptr) = (unsigned int)tempResult;
ptr++;
}
}
//std::cout << "ReadImage end" << std::endl;
}
void ReadSuperPixelDat::SaveSegmentedImageFile(unsigned int* pbuff, int width,int height){//YOUR own function to save an ARGB buffer as an image
std::cout << "SaveSegmentedImageFile start" << std::endl;
this->result = cv::Mat(this->image.size(), CV_8UC3);
unsigned int* ptr = this->pbuff;
for(int y_offset = 0; y_offset < this->image.rows; y_offset++){
for(int x_offset = 0; x_offset < this->image.cols; x_offset++){
//std::cout << y_offset << " " << x_offset << std::endl;
unsigned int tempResult1 = *ptr;
int blue = tempResult1%(int)std::pow(2,8);
int green = (tempResult1/(int)std::pow(2,8))%(int)std::pow(2,8);
int red = (tempResult1/(int)std::pow(2,16))%(int)std::pow(2,8);
this->result.at<cv::Vec3b>(y_offset,x_offset) = cv::Vec3b(blue,green,red);
ptr++;
}
}
std::cout << "SaveSegmentedImageFile end" << std::endl;
}
void ReadSuperPixelDat::authorRead(){
FILE* pf = fopen((Util::dirName+"/SLICOutput.dat").toUtf8().data(), "r");
int sz = this->size;
int* vals = new int[sz];
int elread = fread((char*)vals, sizeof(int), sz, pf);
for( int j = 0; j < this->image.rows; j++ ){
for( int k = 0; k < this->image.cols; k++ ){
int i = j*this->image.cols+k;
labels[i] = vals[i];
}
}
delete [] vals;
fclose(pf);
}
int ReadSuperPixelDat::cvtRGB2ColorCode(int red, int green, int blue){
int result = 0;
result += (red/127)*9;
result += (green/127)*3;
result += blue/127;
return result;
}
void ReadSuperPixelDat::searchUnwhiteArea(){
for(int y_offset = 0; y_offset < this->maskDFS.rows; y_offset++){
for(int x_offset = 0; x_offset < this->maskDFS.cols; x_offset++){
cv::Vec3b currentColor = this->maskDFS.at<cv::Vec3b>(y_offset,x_offset);
cv::Vec3b white = cv::Vec3b(255,255,255);
if(currentColor != white){
int colorCode = this->cvtRGB2ColorCode(currentColor[2],currentColor[1],currentColor[0]);
this->colorCodeVector.push_back(colorCode);
std::cout << "Find unwhite area: " << y_offset << " " << x_offset << " ColorCode = " << colorCode<< std::endl;
this->coordinates = std::vector< std::pair<int,int> >();
this->dfs(std::pair<int,int>(y_offset,x_offset));
this->maskID2Coodinates.push_back(this->coordinates);
}
}
}
}
void ReadSuperPixelDat::dfs(std::pair<int,int> coordinate){
this->coordinates.push_back(coordinate);
cv::Vec3b currentMaskColor = this->maskDFS.at<cv::Vec3b>(coordinate.first, coordinate.second);
cv::Vec3b white = cv::Vec3b(255,255,255);
this->maskDFS.at<cv::Vec3b>(coordinate.first,coordinate.second) = white;
if(coordinate.first+1 < this->maskDFS.rows && this->maskDFS.at<cv::Vec3b>(coordinate.first+1,coordinate.second) == currentMaskColor)
this->dfs(std::pair<int,int>(coordinate.first+1,coordinate.second));
if(coordinate.second-1 >=0 && this->maskDFS.at<cv::Vec3b>(coordinate.first,coordinate.second-1) == currentMaskColor)
this->dfs(std::pair<int,int>(coordinate.first,coordinate.second-1));
if(coordinate.first-1 >= 0 && this->maskDFS.at<cv::Vec3b>(coordinate.first-1,coordinate.second) == currentMaskColor)
this->dfs(std::pair<int,int>(coordinate.first-1,coordinate.second));
if(coordinate.second+1 < this->maskDFS.cols && this->maskDFS.at<cv::Vec3b>(coordinate.first,coordinate.second+1) == currentMaskColor)
this->dfs(std::pair<int,int>(coordinate.first,coordinate.second+1));
}
| 41.404624
| 144
| 0.596817
|
netbeen
|
bf8672cfedf52fd0f733bd4a83347dfa10a4d85c
| 10,474
|
cpp
|
C++
|
kflat/flat_track_bar.cpp
|
lulimin/KongFrame-0.1.0
|
2721a433fe089539621f53c71e26b21a8a293b63
|
[
"MIT"
] | null | null | null |
kflat/flat_track_bar.cpp
|
lulimin/KongFrame-0.1.0
|
2721a433fe089539621f53c71e26b21a8a293b63
|
[
"MIT"
] | null | null | null |
kflat/flat_track_bar.cpp
|
lulimin/KongFrame-0.1.0
|
2721a433fe089539621f53c71e26b21a8a293b63
|
[
"MIT"
] | null | null | null |
// flat_track_bar.cpp
// Created by lulimin on 2020/9/11.
#include "flat_track_bar.h"
#include "flat_button.h"
#include "flat_ui.h"
/// \file flat_track_bar.cpp
/// \brief User interface track bar.
/// object: FlatTrackBar
/// \brief User interface track bar object.
DEF_OBJECT(FlatTrackBar, FlatWidget);
/// readonly: object TrackButton
/// \brief Get track button object.
DEF_READ_F(uniqid_t, FlatTrackBar, TrackButton, GetTrackButtonID);
/// property: int Minimum
/// \brief Minimum horizontal value.
DEF_PROP(int, FlatTrackBar, Minimum);
/// property: int Maximum
/// \brief Maximum horizontal value.
DEF_PROP(int, FlatTrackBar, Maximum);
/// property: int Value
/// \brief Current horizontal value.
DEF_PROP(int, FlatTrackBar, Value);
/// property: int VerticalMinimum
/// \brief Minimum vertical value.
DEF_PROP(int, FlatTrackBar, VerticalMinimum);
/// property: int VerticalMaximum
/// \brief Maximum vertical value.
DEF_PROP(int, FlatTrackBar, VerticalMaximum);
/// property: int VerticalValue
/// \brief Current vertical value.
DEF_PROP(int, FlatTrackBar, VerticalValue);
// FlatTrackBar
FlatTrackBar::FlatTrackBar()
{
m_pTrackButton = NULL;
m_nMinimum = 0;
m_nMaximum = 100;
m_nValue = 0;
m_nVerticalMinimum = 0;
m_nVerticalMaximum = 0;
m_nVerticalValue = 0;
}
FlatTrackBar::~FlatTrackBar()
{
}
bool FlatTrackBar::Startup(const IArgList& args)
{
if (!FlatWidget::Startup(args))
{
return false;
}
this->SetCanFocus(true);
this->CreateParts();
FlatUI* pFlatUI = this->GetFlatUI();
m_pTrackButton = (FlatButton*)pFlatUI->CreatePartWidget(this, "FlatButton");
m_pTrackButton->SetSize(20, 20);
return true;
}
bool FlatTrackBar::Shutdown()
{
return FlatWidget::Shutdown();
}
void FlatTrackBar::Draw(flat_canvas_t* pCanvas)
{
Assert(pCanvas != NULL);
if (!this->GetVisible())
{
return;
}
int width = this->GetWidth();
int height = this->GetHeight();
int x1 = this->GetGlobalLeft();
int y1 = this->GetGlobalTop();
int x2 = x1 + width;
int y2 = y1 + height;
if (this->ExistBackImage())
{
this->DrawBackImage(pCanvas, x1, y1, x2, y2);
}
else
{
canvas_draw_block(pCanvas, x1, y1, x2, y2, this->GetBackColorValue());
canvas_draw_frame(pCanvas, x1, y1, x2, y2, this->GetForeColorValue());
}
if (m_pTrackButton)
{
m_pTrackButton->Draw(pCanvas);
}
}
void FlatTrackBar::SetMetadata(flat_metadata_t* pMD)
{
Assert(pMD != NULL);
FlatWidget::SetMetadata(pMD);
FrameArgData def_zero_int32(DT_INT32, 0);
FrameArgData def_maximum(DT_INT32, 100);
flat_metadata_add_prop(pMD, "Minimum", FLAT_METATYPE_INT32,
&def_zero_int32);
flat_metadata_add_prop(pMD, "Maximum", FLAT_METATYPE_INT32,
&def_maximum);
flat_metadata_add_prop(pMD, "Value", FLAT_METATYPE_INT32,
&def_zero_int32);
flat_metadata_add_prop(pMD, "VerticalMinimum", FLAT_METATYPE_INT32,
&def_zero_int32);
flat_metadata_add_prop(pMD, "VerticalMaximum", FLAT_METATYPE_INT32,
&def_zero_int32);
flat_metadata_add_prop(pMD, "VerticalValue", FLAT_METATYPE_INT32,
&def_zero_int32);
flat_metadata_add_event(pMD, "changed");
flat_metadata_add_part(pMD, "TrackButton", "FlatButton");
}
FlatWidget* FlatTrackBar::GetRegionOf(int x, int y)
{
if (!this->GetVisible())
{
return NULL;
}
if (this->GetDesignMode())
{
if (!this->InSelfRegion(x, y))
{
// Not in region of widget.
return NULL;
}
// In design status.
return this;
}
FlatWidget* pWidget = this->InPartRegion(x, y);
if (pWidget)
{
return pWidget;
}
if (!this->InSelfRegion(x, y))
{
// Not in region of widget.
return NULL;
}
if (this->OnTestTransparency(x, y))
{
// Is transparency part.
return NULL;
}
return this;
}
int FlatTrackBar::OnLeftDown(int x, int y, unsigned int flags)
{
bool track_horizontal = (m_nMaximum > m_nMinimum);
bool track_vertical = (m_nVerticalMaximum > m_nMinimum);
if (track_horizontal)
{
int half_track_width = m_pTrackButton->GetWidth() / 2;
int beg_x = 0;
int end_x = this->GetWidth();
int track_x = x - this->GetGlobalLeft();
if (track_x < beg_x)
{
track_x = beg_x;
}
if (track_x > end_x)
{
track_x = end_x;
}
m_pTrackButton->SetLeft(track_x - half_track_width);
int stride = m_nMaximum - m_nMinimum;
double rate = (double)(track_x - beg_x) / (double)(end_x - beg_x);
int new_value = m_nMinimum + (int)(rate * (double)stride);
int old_value = m_nValue;
if (new_value != old_value)
{
m_nValue = new_value;
this->ValueChanged(old_value);
this->AdjustValue();
}
}
if (track_vertical)
{
int half_track_height = m_pTrackButton->GetHeight() / 2;
int beg_y = 0;
int end_y = this->GetHeight();
int track_y = y - this->GetGlobalTop();
if (track_y < beg_y)
{
track_y = beg_y;
}
if (track_y > end_y)
{
track_y = end_y;
}
m_pTrackButton->SetTop(track_y - half_track_height);
int stride = m_nVerticalMaximum - m_nVerticalMinimum;
double rate = (double)(track_y - beg_y) / (double)(end_y - beg_y);
int new_value = m_nVerticalMinimum + (int)(rate * (double)stride);
int old_value = m_nVerticalValue;
if (new_value != old_value)
{
m_nVerticalValue = new_value;
this->VerticalValueChanged(old_value);
this->AdjustVerticalValue();
}
}
return 1;
}
int FlatTrackBar::OnSizeChanged()
{
this->PerformLayout();
return 1;
}
int FlatTrackBar::OnPartDrag(FlatWidget* pPart, int x, int y, int cx, int cy,
unsigned int flags)
{
Assert(pPart != NULL);
if (pPart != m_pTrackButton)
{
return 0;
}
bool track_horizontal = (m_nMaximum > m_nMinimum);
bool track_vertical = (m_nVerticalMaximum > m_nMinimum);
if (track_horizontal)
{
int half_track_width = m_pTrackButton->GetWidth() / 2;
int beg_x = 0;
int end_x = this->GetWidth();
int track_x = x - this->GetGlobalLeft() - cx + half_track_width;
if (track_x < beg_x)
{
track_x = beg_x;
}
if (track_x > end_x)
{
track_x = end_x;
}
m_pTrackButton->SetLeft(track_x - half_track_width);
int stride = m_nMaximum - m_nMinimum;
double rate = (double)(track_x - beg_x) / (double)(end_x - beg_x);
int new_value = m_nMinimum + (int)(rate * (double)stride);
int old_value = m_nValue;
if (new_value != old_value)
{
m_nValue = new_value;
this->ValueChanged(old_value);
this->AdjustValue();
}
}
if (track_vertical)
{
int half_track_height = m_pTrackButton->GetHeight() / 2;
int beg_y = 0;
int end_y = this->GetHeight();
int track_y = y - this->GetGlobalTop() - cy + half_track_height;
if (track_y < beg_y)
{
track_y = beg_y;
}
if (track_y > end_y)
{
track_y = end_y;
}
m_pTrackButton->SetTop(track_y - half_track_height);
int stride = m_nVerticalMaximum - m_nVerticalMinimum;
double rate = (double)(track_y - beg_y) / (double)(end_y - beg_y);
int new_value = m_nVerticalMinimum + (int)(rate * (double)stride);
int old_value = m_nVerticalValue;
if (new_value != old_value)
{
m_nVerticalValue = new_value;
this->VerticalValueChanged(old_value);
this->AdjustVerticalValue();
}
}
return 1;
}
void FlatTrackBar::SetMinimum(int value)
{
m_nMinimum = value;
this->AdjustValue();
}
int FlatTrackBar::GetMinimum() const
{
return m_nMinimum;
}
void FlatTrackBar::SetMaximum(int value)
{
m_nMaximum = value;
this->AdjustValue();
}
int FlatTrackBar::GetMaximum() const
{
return m_nMaximum;
}
void FlatTrackBar::SetValue(int value)
{
int old_value = m_nValue;
m_nValue = value;
this->ValueChanged(old_value);
this->AdjustValue();
this->LocateTrackButton();
}
int FlatTrackBar::GetValue() const
{
return m_nValue;
}
void FlatTrackBar::SetVerticalMinimum(int value)
{
m_nVerticalMinimum = value;
this->AdjustVerticalValue();
}
int FlatTrackBar::GetVerticalMinimum() const
{
return m_nVerticalMinimum;
}
void FlatTrackBar::SetVerticalMaximum(int value)
{
m_nVerticalMaximum = value;
this->AdjustVerticalValue();
}
int FlatTrackBar::GetVerticalMaximum() const
{
return m_nVerticalMaximum;
}
void FlatTrackBar::SetVerticalValue(int value)
{
int old_value = m_nVerticalValue;
m_nVerticalValue = value;
this->ValueChanged(old_value);
this->AdjustVerticalValue();
this->LocateTrackButton();
}
int FlatTrackBar::GetVerticalValue() const
{
return m_nVerticalValue;
}
uniqid_t FlatTrackBar::GetTrackButtonID() const
{
if (NULL == m_pTrackButton)
{
return uniqid_t();
}
return m_pTrackButton->GetUID();
}
void FlatTrackBar::AdjustValue()
{
if (m_nValue < m_nMinimum)
{
m_nValue = m_nMinimum;
}
if (m_nValue > m_nMaximum)
{
m_nValue = m_nMaximum;
}
}
void FlatTrackBar::AdjustVerticalValue()
{
if (m_nVerticalValue < m_nVerticalMinimum)
{
m_nVerticalValue = m_nVerticalMinimum;
}
if (m_nVerticalValue > m_nVerticalMaximum)
{
m_nVerticalValue = m_nVerticalMaximum;
}
}
void FlatTrackBar::PerformLayout()
{
this->LocateTrackButton();
}
void FlatTrackBar::ValueChanged(int old_value)
{
if (this->GetEnabled())
{
frame_process_event(this, 0, "changed", FrameArgList(), NULL);
}
}
void FlatTrackBar::VerticalValueChanged(int old_value)
{
if (this->GetEnabled())
{
frame_process_event(this, 0, "changed", FrameArgList(), NULL);
}
}
void FlatTrackBar::LocateTrackButton()
{
bool track_horizontal = (m_nMaximum > m_nMinimum);
bool track_vertical = (m_nVerticalMaximum > m_nVerticalMinimum);
int width = this->GetWidth();
int height = this->GetHeight();
int half_track_width = m_pTrackButton->GetWidth() / 2;
int half_track_height = m_pTrackButton->GetHeight() / 2;
int cx;
int cy;
if (track_horizontal)
{
double rate = (double)(m_nValue - m_nMinimum) /
(double)(m_nMaximum - m_nMinimum);
cx = (int)(rate * width + 0.5);
}
else
{
cx = width / 2;
}
if (track_vertical)
{
double rate = (double)(m_nVerticalValue - m_nVerticalMinimum) /
(double)(m_nVerticalMaximum - m_nVerticalMinimum);
cy = (int)(rate * height + 0.5);
}
else
{
cy = height / 2;
}
m_pTrackButton->SetLeft(cx - half_track_width);
m_pTrackButton->SetTop(cy - half_track_height);
}
| 20.864542
| 78
| 0.668608
|
lulimin
|
bf8773edc754a462a41f3add8d681bcdde481528
| 238
|
cpp
|
C++
|
Chef and Operators.cpp
|
dhairya2019/codechef-c-c-
|
4d11aa6b92c28fa69e562acd4e1f836dffe34113
|
[
"Apache-2.0"
] | null | null | null |
Chef and Operators.cpp
|
dhairya2019/codechef-c-c-
|
4d11aa6b92c28fa69e562acd4e1f836dffe34113
|
[
"Apache-2.0"
] | null | null | null |
Chef and Operators.cpp
|
dhairya2019/codechef-c-c-
|
4d11aa6b92c28fa69e562acd4e1f836dffe34113
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
using namespace std;
int main() {
int t=0;
cin>>t;
int a=0,b=0;
for(int i=0;i<t;i++){
cin>>a>>b;
if(a==b)
cout<<"="<<endl;
else if(a<b)
cout<<"<"<<endl;
else
cout<<">"<<endl;
}
return 0;
}
| 12.526316
| 22
| 0.495798
|
dhairya2019
|
bf8a20e5c108af162e0fbd283c6a9b208caf6445
| 6,179
|
cpp
|
C++
|
src/particle.cpp
|
jwrdegoede/abuse
|
77a34f69569815e73b95d99268fb7ba1cd64c17b
|
[
"WTFPL"
] | null | null | null |
src/particle.cpp
|
jwrdegoede/abuse
|
77a34f69569815e73b95d99268fb7ba1cd64c17b
|
[
"WTFPL"
] | null | null | null |
src/particle.cpp
|
jwrdegoede/abuse
|
77a34f69569815e73b95d99268fb7ba1cd64c17b
|
[
"WTFPL"
] | null | null | null |
/*
* Abuse - dark 2D side-scrolling platform game
* Copyright (c) 1995 Crack dot Com
* Copyright (c) 2005-2011 Sam Hocevar <sam@hocevar.net>
*
* This software was released into the Public Domain. As with most public
* domain software, no warranty is made or implied by Crack dot Com, by
* Jonathan Clark, or by Sam Hocevar.
*/
#if defined HAVE_CONFIG_H
# include "config.h"
#endif
#include "common.h"
#include "particle.h"
#include "view.h"
#include "lisp.h"
#include "cache.h"
#include "jrand.h"
static int total_pseqs=0;
static part_sequence **pseqs=NULL;
static part_animation *first_anim=NULL,*last_anim=NULL;
void free_pframes()
{
for (int i=0; i<total_pseqs; i++)
delete pseqs[i];
if (total_pseqs)
free(pseqs);
}
part_frame::~part_frame()
{
free(data);
}
void add_panim(int id, long x, long y, int dir)
{
CONDITION(id>=0 && id<total_pseqs,"bad id for particle animation");
part_animation *pan=new part_animation(pseqs[id],x,y,dir,NULL);
if (!first_anim)
first_anim=last_anim=pan;
else
{
last_anim->next=pan;
last_anim=pan;
}
}
void delete_panims()
{
while (first_anim)
{
last_anim=first_anim;
first_anim=first_anim->next;
delete last_anim;
}
last_anim=NULL;
}
int defun_pseq(void *args)
{
LSymbol *sym=(LSymbol *)lcar(args);
if (item_type(sym)!=L_SYMBOL)
{
((LObject *)args)->Print();
printf("expecting first arg to def-particle to be a symbol!\n");
exit(0);
}
LSpace *sp = LSpace::Current;
LSpace::Current = &LSpace::Perm;
sym->SetNumber(total_pseqs); // set the symbol value to the object number
LSpace::Current = sp;
pseqs=(part_sequence **)realloc(pseqs,sizeof(part_sequence *)*(total_pseqs+1));
args=lcdr(args);
pseqs[total_pseqs]=new part_sequence(args);
total_pseqs++;
return total_pseqs;
}
extern int total_files_open;
part_sequence::part_sequence(void *args)
{
char *fn=lstring_value(lcar(args));
bFILE *fp=open_file(fn,"rb");
if (fp->open_failure())
{
delete fp;
((LObject *)args)->Print();
fprintf(stderr,"\nparticle sequence : Unable to open %s for reading\n",fn);
fprintf(stderr,"total files open=%d\n",total_files_open);
FILE *fp=fopen(fn,"rb");
printf("convet = %d\n",fp!=NULL);
exit(1);
}
// count how many frames are in the file
spec_directory sd(fp);
delete fp;
tframes=0;
int i=0;
for (; i<sd.total; i++)
if (sd.entries[i]->type==SPEC_PARTICLE) tframes++;
frames=(int *)malloc(sizeof(int)*tframes);
int on=0;
for (i=0; i<sd.total; i++)
if (sd.entries[i]->type==SPEC_PARTICLE)
frames[on++]=cache.reg(fn,sd.entries[i]->name,SPEC_PARTICLE,1);
}
part_frame::part_frame(bFILE *fp)
{
t=fp->read_uint32();
data=(part *)malloc(sizeof(part)*t);
x1=y1=100000; x2=y2=-100000;
for (int i=0; i<t; i++)
{
int16_t x=fp->read_uint16();
int16_t y=fp->read_uint16();
if (x<x1) x1=x;
if (y<y1) y1=y;
if (x>x2) x2=x;
if (y>y2) y2=x;
data[i].x=x;
data[i].y=y;
data[i].color=fp->read_uint8();
}
}
void tick_panims()
{
part_animation *last=NULL;
for (part_animation *p=first_anim; p; )
{
p->frame++;
if (p->frame>=p->seq->tframes)
{
if (last)
last->next=p->next;
else first_anim=first_anim->next;
if (last_anim==p) last_anim=last;
part_animation *d=p;
p=p->next;
delete d;
} else
{
last=p;
p=p->next;
}
}
}
void draw_panims(view *v)
{
for (part_animation *p=first_anim; p; p=p->next)
{
cache.part(p->seq->frames[p->frame])->draw(main_screen,p->x-v->xoff()+v->m_aa.x,p->y-v->yoff()+v->m_aa.y,p->dir);
}
}
void part_frame::draw(image *screen, int x, int y, int dir)
{
ivec2 caa, cbb;
screen->GetClip(caa, cbb);
if (x + x1 >= cbb.x || x + x2 < caa.x || y + y1 >= cbb.y || y + y2 < caa.y)
return;
part *pon=data;
caa.y -= y;
cbb.y -= y;
int i=t;
while (i && pon->y<caa.y) { pon++; i--; }
if (!i) return ;
screen->Lock();
if (dir>0)
{
while (i && pon->y < cbb.y)
{
long dx=x-pon->x;
if (dx >= caa.x && dx < cbb.x)
*(screen->scan_line(pon->y+y)+dx)=pon->color;
i--;
pon++;
}
} else
{
while (i && pon->y < cbb.y)
{
long dx=pon->x+x;
if (dx >= caa.x && dx < cbb.x)
*(screen->scan_line(pon->y+y)+dx)=pon->color;
i--;
pon++;
}
}
screen->Unlock();
}
void ScatterLine(ivec2 p1, ivec2 p2, int c, int s)
{
ivec2 caa, cbb;
main_screen->GetClip(caa, cbb);
int t = 1 + Max(abs(p2.x - p1.x), abs(p2.y - p1.y));
int xo = p1.x << 16,
yo = p1.y << 16,
dx = ((p2.x - p1.x) << 16) / t,
dy = ((p2.y - p1.y) << 16) / t;
int xm = (1 << s);
int ym = (1 << s);
s = (15 - s);
main_screen->Lock();
while(t--)
{
int x = (xo >> 16) + (jrand() >> s) - xm;
int y = (yo >> 16) + (jrand() >> s) - ym;
if(!(x < caa.x || y < caa.y || x >= cbb.x || y >= cbb.y))
{
*(main_screen->scan_line(y) + x) = c;
}
xo += dx;
yo += dy;
}
main_screen->Unlock();
}
void AScatterLine(ivec2 p1, ivec2 p2, int c1, int c2, int s)
{
ivec2 caa, cbb;
main_screen->GetClip(caa, cbb);
int t = 1 + Max(abs(p2.x - p1.x), abs(p2.y - p1.y));
int xo = p1.x << 16,
yo = p1.y << 16,
dx = ((p2.x - p1.x) << 16) / t,
dy = ((p2.y - p1.y) << 16) / t;
int xm = (1 << s);
int ym = (1 << s);
s = (15 - s);
main_screen->Lock();
int w = main_screen->Size().x;
uint8_t *addr;
while(t--)
{
int x = (xo >> 16) + (jrand() >> s) - xm;
int y = (yo >> 16) + (jrand() >> s) - ym;
// FIXME: these clip values seemed wrong to me before the GetClip
// refactoring.
if(!(x <= caa.x || y <= caa.y || x >= cbb.x - 1 || y >= cbb.y - 1))
{
addr = main_screen->scan_line(y) + x;
*addr = c1;
*(addr + w) = c2;
*(addr - w) = c2;
*(addr - 1) = c2;
*(addr + 1) = c2;
}
xo += dx;
yo += dy;
}
main_screen->Unlock();
}
| 21.833922
| 117
| 0.542806
|
jwrdegoede
|
bf8f2aefa182bd47aab7b2789b0eabcabc55e67e
| 1,751
|
cpp
|
C++
|
hxemu/src/fakeslave.cpp
|
Frigolit/HXEmu
|
9764886879309d58cde125aeb0d3523a8983c17a
|
[
"MIT"
] | 9
|
2015-03-07T22:45:36.000Z
|
2022-01-03T22:54:00.000Z
|
hxemu/src/fakeslave.cpp
|
Frigolit/HXEmu
|
9764886879309d58cde125aeb0d3523a8983c17a
|
[
"MIT"
] | null | null | null |
hxemu/src/fakeslave.cpp
|
Frigolit/HXEmu
|
9764886879309d58cde125aeb0d3523a8983c17a
|
[
"MIT"
] | 1
|
2018-08-23T17:55:31.000Z
|
2018-08-23T17:55:31.000Z
|
// =============================================================================
// @author Pontus Rodling <frigolit@frigolit.net>
// @license MIT license - See LICENSE for more information
// =============================================================================
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "fakeslave.h"
FakeSlave::FakeSlave() {
serial0 = new VirtualSerial();
serial1 = new VirtualSerial();
}
FakeSlave::~FakeSlave() {
delete(serial0);
delete(serial1);
}
void FakeSlave::reset() {
state = 0;
serial0->reset();
serial1->reset();
}
void FakeSlave::step() {
if (!serial0->peek()) return;
uint8_t c = serial0->recv();
printf("FakeSlave::think(): debug: received command %02X\n", c);
if (state == 0) {
if (c == 0x00) {
// Slave MCU ready check
serial0->send(0x01); // ACK
}
else if (c == 0x02) {
// Initialize
serial0->send(0x01); // ACK
}
else if (c == 0x03) {
// Open special command mask
serial0->send(0x01); // ACK
}
else if (c == 0x04) {
// Close special command mask
serial0->send(0x01); // ACK
}
else if (c == 0x0C) {
// Stop processing and enter WAIT state
serial0->send(0x02); // ACK
}
else if (c == 0x0D) {
// Cut off power supply
serial0->send(0x01);
state = 1;
}
else if (c == 0x50) {
// Detect plug-in options
printf("FakeSlave::think(): fixme: plugin options are not yet supported\n");
serial0->send(0x00);
}
// Unknown command
else {
printf("FakeSlave::think(): fixme: unhandled command %02X\n", c);
}
}
else if (state == 1) {
state = 0;
if (c == 0xAA) {
printf("FakeSlave::think(): debug: power supply cut-off requested\n");
serial0->send(0x01);
}
}
}
| 21.096386
| 80
| 0.546545
|
Frigolit
|
bf96ccd2ffb54e97b6cc84cd03c8b0765f7c9fa4
| 1,912
|
cpp
|
C++
|
chapter21/chapter21_ex06.cpp
|
TingeOGinge/stroustrup_ppp
|
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
|
[
"MIT"
] | 170
|
2015-05-02T18:08:38.000Z
|
2018-07-31T11:35:17.000Z
|
chapter21/chapter21_ex06.cpp
|
TingeOGinge/stroustrup_ppp
|
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
|
[
"MIT"
] | 7
|
2017-01-16T02:25:20.000Z
|
2018-07-20T12:57:30.000Z
|
chapter21/chapter21_ex06.cpp
|
TingeOGinge/stroustrup_ppp
|
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
|
[
"MIT"
] | 105
|
2015-05-28T11:52:19.000Z
|
2018-07-17T14:11:25.000Z
|
// Chapter 21, Exercise 6: implement the Fruit example (set) using a
// set<Fruit*,Fruit_comparison> (pointers instead of copies), i.e., define a
// comparison operation for Fruit*
#include "../lib_files/std_lib_facilities.h"
#include<set>
//------------------------------------------------------------------------------
struct Fruit {
string name;
int count;
double unit_price;
Fruit(string n, int c, double up = 0.0)
:name(n), count(c), unit_price(up) { }
};
//------------------------------------------------------------------------------
ostream& operator<<(ostream& os, const Fruit* f)
{
os << setw(7) << left << f->name;
os << f->count << '\t' << f->unit_price;
return os;
}
//------------------------------------------------------------------------------
struct Fruit_comparison {
bool operator()(const Fruit* a, const Fruit* b) const
{
return a->name < b->name;
}
};
//------------------------------------------------------------------------------
int main()
try {
set<Fruit*,Fruit_comparison> inventory;
inventory.insert(new Fruit("Quince",5)); // test default parameter
inventory.insert(new Fruit("Apple",200,0.37));
inventory.insert(new Fruit("Orange",150,0.45));
inventory.insert(new Fruit("Grape",13,0.99));
inventory.insert(new Fruit("Kiwi",512,1.15));
inventory.insert(new Fruit("Plum",750,2.33));
typedef set<Fruit*,Fruit_comparison>::const_iterator Si;
for (Si p = inventory.begin(); p!=inventory.end(); ++p) cout << *p << '\n';
// Clean up
for (Si p = inventory.begin(); p!=inventory.end(); ++p) delete *p;
}
catch (Range_error& re) {
cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
cerr << "exception: " << e.what() << endl;
}
catch (...) {
cerr << "exception\n";
}
//------------------------------------------------------------------------------
| 29.875
| 80
| 0.480649
|
TingeOGinge
|
bf974402fdcdf28cf20356cbb7ced9184965a96d
| 7,300
|
cpp
|
C++
|
RagiMagick/src/main.cpp
|
kuroxuta/RagiMagick
|
6a06bfe6fb8852dd5947e068c38b3ed1458d0b6a
|
[
"MIT"
] | null | null | null |
RagiMagick/src/main.cpp
|
kuroxuta/RagiMagick
|
6a06bfe6fb8852dd5947e068c38b3ed1458d0b6a
|
[
"MIT"
] | null | null | null |
RagiMagick/src/main.cpp
|
kuroxuta/RagiMagick
|
6a06bfe6fb8852dd5947e068c38b3ed1458d0b6a
|
[
"MIT"
] | null | null | null |
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
#include "ragii/include/text/text.h"
#include "ragii/include/hardware/cpu_info.h"
#include "ragii-image/include/Bitmap.h"
#include "ragii-image/include/BitmapConverter.h"
#include "ragii-image/include/util.h"
using namespace std;
using namespace ragii::image;
using namespace ragii::text;
using namespace ragii::hardware;
struct CommandOption
{
string_view name;
string_view value;
};
void dumpSystemInfo();
int process(int argc, char* argv[]);
int convert(vector<CommandOption>& opts);
int create(vector<CommandOption>& opts);
int main(int argc, char* argv[])
{
dumpSystemInfo();
return process(argc, argv);
}
void dumpSystemInfo()
{
CpuInfo info;
cout << CpuVendor(info.load(0)).getName() << endl;
auto reg = info.load(1);
CpuAvailableFeatures features(reg);
cout << "sse: " << features.sse() << endl;
cout << "sse2: " << features.sse2() << endl;
cout << "sse3: " << features.sse3() << endl;
cout << "sse41: " << features.sse41() << endl;
cout << "sse42: " << features.sse42() << endl;
cout << "avx: " << features.avx() << endl;
cout << "avx2: " << features.avx2() << endl;
}
int process(int argc, char* argv[])
{
if (argc < 2) {
cout << "コマンドを指定してください。 convert, etc." << endl;
return EXIT_FAILURE;
}
vector<CommandOption> opts;
for (int i = 1; i < argc;) {
auto opt = string_view(argv[i]);
if (opt[0] == '-') {
auto value = i + 1 < argc ? argv[i + 1] : "";
opts.emplace_back(CommandOption { argv[i], value });
i += 2;
}
else {
opts.emplace_back(CommandOption { argv[i], "" });
i++;
}
}
for (auto i : opts) {
cout << i.name.data() << ": " << i.value.data() << endl;
}
if (opts.empty()) {
cout << "コマンドを指定してください。 convert, etc." << endl;
return EXIT_FAILURE;
}
auto command = opts[0].name;
opts.erase(opts.begin());
if (command == "convert") {
return convert(opts);
}
if (command == "create") {
return create(opts);
}
cout << "コマンドを指定してください。 convert, etc." << endl;
return EXIT_FAILURE;
}
int convert(vector<CommandOption>& opts)
{
if (opts.empty()) {
cout << "変換方法を指定してください。 negative, grayscale, etc." << endl;
return EXIT_FAILURE;
}
auto in_file = find_if(opts.begin(), opts.end(), [&](auto i) { return i.name == "-i"; });
if (in_file == opts.end()) {
cout << "入力ファイル名を指定してください。" << endl;
return EXIT_FAILURE;
}
if (in_file->value.empty()) {
cout << "入力ファイル名を指定してください。" << endl;
return EXIT_FAILURE;
}
auto out_file = find_if(opts.begin(), opts.end(), [&](auto i) { return i.name == "-o"; });
if (out_file == opts.end()) {
cout << "出力ファイル名を指定してください。" << endl;
return EXIT_FAILURE;
}
if (out_file->value.empty()) {
cout << "出力ファイル名を指定してください。" << endl;
return EXIT_FAILURE;
}
unique_ptr<Bitmap> bmp;
if (ends_with(in_file->value.data(), ".bmp")) {
bmp = Bitmap::loadFromFile(in_file->value.data());
}
else if (ends_with(in_file->value.data(), ".jpg")) {
bmp = jpeg_to_bmp(in_file->value.data());
}
else if (ends_with(in_file->value.data(), ".png")) {
bmp = png_to_bmp(in_file->value.data());
}
else {
cout << ".bmp, .jpg, .png 以外は非対応です。" << endl;
return EXIT_FAILURE;
}
if (!bmp) {
cout << "ファイルのロードに失敗しました。" << endl;
return EXIT_FAILURE;
}
cout << "width: " << bmp->getWidth() << ", height: " << bmp->getHeight() << ", depth: " << bmp->getBitCount() / 8
<< endl;
auto filter = opts[0].name;
if (filter == "negative") {
BitmapConverter::applyFilter(bmp.get(), FilterType::Negative);
}
else if (filter == "binary") {
BitmapConverter::applyFilter(bmp.get(), FilterType::Binary);
}
else if (filter == "grayscale") {
BitmapConverter::applyFilter(bmp.get(), FilterType::Grayscale);
}
else if (filter == "laplacian") {
// BitmapConverter::applyFilter(bmp.get(), FilterType::Grayscale);
BitmapConverter::applyFilter(bmp.get(), FilterType::Binary);
BitmapConverter::applyFilter(bmp.get(), FilterType::Laplacian);
}
else if (filter == "gaussian") {
BitmapConverter::applyFilter(bmp.get(), FilterType::Gaussian);
}
else if (filter == "mosaic") {
BitmapConverter::applyFilter(bmp.get(), FilterType::Mosaic);
}
else {
cout << "未知のコマンドが指定されています!" << endl;
return EXIT_FAILURE;
}
bmp->save(out_file->value.data());
cout << "converted." << endl;
return EXIT_SUCCESS;
}
// RagiMagick create -w 32 -h 32 -d 3 -p checkered -o out.bmp
int create(vector<CommandOption>& opts)
{
if (opts.empty()) {
cout << "オプションが不足しています。" << endl;
return EXIT_FAILURE;
}
auto out_file = find_if(opts.begin(), opts.end(), [&](auto i) { return i.name == "-o"; });
if (out_file == opts.end()) {
cout << "出力ファイル名を指定してください。" << endl;
return EXIT_FAILURE;
}
if (out_file->value.empty()) {
cout << "出力ファイル名を指定してください。" << endl;
return EXIT_FAILURE;
}
auto w = find_if(opts.begin(), opts.end(), [&](auto i) { return i.name == "-w"; });
if (w == opts.end()) {
cout << "-w (幅) を指定してください。" << endl;
return EXIT_FAILURE;
}
if (w->value.empty()) {
cout << "幅の値を指定してください。" << endl;
return EXIT_FAILURE;
}
auto h = find_if(opts.begin(), opts.end(), [&](auto i) { return i.name == "-h"; });
if (h == opts.end()) {
cout << "-h (高さ) を指定してください。" << endl;
return EXIT_FAILURE;
}
if (h->value.empty()) {
cout << "高さの値を指定してください。" << endl;
return EXIT_FAILURE;
}
auto d = find_if(opts.begin(), opts.end(), [&](auto i) { return i.name == "-d"; });
if (d == opts.end()) {
cout << "-d (ビット深度 3: 24bit, 4: 32bit) を指定してください。" << endl;
return EXIT_FAILURE;
}
if (d->value.empty()) {
cout << "ビット深度の値を指定してください。" << endl;
return EXIT_FAILURE;
}
if (!is_digit(d->value[0])) {
cout << "ビット深度の値が不正です。" << endl;
return EXIT_FAILURE;
}
auto p = find_if(opts.begin(), opts.end(), [&](auto i) { return i.name == "-p"; });
if (p == opts.end()) {
cout << "-p (パターン) を指定してください。" << endl;
return EXIT_FAILURE;
}
auto bmp = Bitmap::create(str_to_arithmetic<int32_t>(w->value.data()), str_to_arithmetic<int32_t>(h->value.data()),
str_to_arithmetic<int16_t>(d->value.data()) * 8);
if (p->value == "checkered") {
auto data = bmp->getData();
auto depth = bmp->getBitCount() / 8;
for (int y = 0; y < bmp->getHeight(); y++) {
for (int x = 0; x < bmp->getWidth(); x++) {
for (int i = 0; i < depth; i++) {
*data++ = static_cast<uint8_t>(y ^ x);
}
}
}
}
bmp->save(out_file->value.data());
cout << "created." << endl;
return EXIT_SUCCESS;
}
| 28.294574
| 119
| 0.543973
|
kuroxuta
|
bcc9e2fffe671af684848c05ceb01abcc4a20812
| 1,416
|
hpp
|
C++
|
TrainTravelling/Station.hpp
|
anttijuu/Graphs
|
0765b8e5ef4bfb7a885a0df7c70b353466c83801
|
[
"MIT"
] | null | null | null |
TrainTravelling/Station.hpp
|
anttijuu/Graphs
|
0765b8e5ef4bfb7a885a0df7c70b353466c83801
|
[
"MIT"
] | null | null | null |
TrainTravelling/Station.hpp
|
anttijuu/Graphs
|
0765b8e5ef4bfb7a885a0df7c70b353466c83801
|
[
"MIT"
] | null | null | null |
//
// Station.hpp
// TrainTravelling
//
// Created by Antti Juustila on 27.11.2020.
//
#ifndef Station_hpp
#define Station_hpp
#include <ostream>
#include <string>
struct Station {
public:
Station()
:name("Unknown"), phone("unknown"), opens(0), closes(0) {
}
Station(const std::string & aName)
: name(aName), phone("unknown"), opens(0), closes(0) {
}
Station(const std::string & aName, const std::string & aPhone, int open, int close)
: name(aName), phone(aPhone), opens(open), closes(close) {
}
Station(const Station & another) {
this->name = another.name;
this->phone = another.phone;
this->opens = another.opens;
this->closes = another.closes;
}
const Station & operator = (const Station & another) {
if (this != &another) {
this->name = another.name;
this->phone = another.phone;
this->opens = another.opens;
this->closes = another.closes;
}
return *this;
}
std::string name;
std::string phone;
int opens;
int closes;
};
bool operator == (const Station & lhs, const Station & rhs) {
return lhs.name == rhs.name;
}
bool operator < (const Station & lhs, const Station & rhs) {
return lhs.name < rhs.name;
}
std::ostream & operator << (std::ostream & stream, const Station & vertex) {
stream << vertex.name << " ";
return stream;
}
#endif /* Station_hpp */
| 21.454545
| 86
| 0.608051
|
anttijuu
|
bccf512525ee5d2f5b59cb687c10811e255ef983
| 588
|
cpp
|
C++
|
login.cpp
|
debbech-esprit/b_fast
|
8497621ae2ff2fee7dd6d305a16cf1c123c9b074
|
[
"Unlicense"
] | 1
|
2020-10-23T22:03:29.000Z
|
2020-10-23T22:03:29.000Z
|
login.cpp
|
debbech-esprit/b_fast
|
8497621ae2ff2fee7dd6d305a16cf1c123c9b074
|
[
"Unlicense"
] | null | null | null |
login.cpp
|
debbech-esprit/b_fast
|
8497621ae2ff2fee7dd6d305a16cf1c123c9b074
|
[
"Unlicense"
] | null | null | null |
#include "login.h"
#include "ui_login.h"
#include<QMessageBox>
Login::Login(QWidget *parent) :
QDialog(parent),
ui(new Ui::Login)
{
ui->setupUi(this);
}
Login::~Login()
{
delete ui;
}
void Login::on_Login_2_clicked()
{
QString username = ui->username->text();
QString password = ui->password->text();
if((username=="admin")&&(password=="admin"))
{
G=new Gestion ;
this->hide();
G->show() ;
}
else
{
QMessageBox::information(this,"Erreur","Verifier vos informations");
}
}
| 15.891892
| 77
| 0.547619
|
debbech-esprit
|
bcd12dfeeaab197940950285e5ea7e031c02b25d
| 5,071
|
cpp
|
C++
|
test/unit/src/metal/value/fold_right.cpp
|
brunocodutra/MPL2
|
9db9b403e58e0be0bbd295ff64f01e700965f25d
|
[
"MIT"
] | 320
|
2015-09-28T19:55:56.000Z
|
2022-03-09T03:00:23.000Z
|
test/unit/src/metal/value/fold_right.cpp
|
brunocodutra/MPL2
|
9db9b403e58e0be0bbd295ff64f01e700965f25d
|
[
"MIT"
] | 80
|
2015-09-09T16:45:55.000Z
|
2021-08-08T21:06:00.000Z
|
test/unit/src/metal/value/fold_right.cpp
|
brunocodutra/MPL2
|
9db9b403e58e0be0bbd295ff64f01e700965f25d
|
[
"MIT"
] | 26
|
2016-02-29T16:16:37.000Z
|
2020-12-14T05:49:24.000Z
|
#include <metal.hpp>
#include "test.hpp"
#define ENTRY(M, N, ...) EXPR(_)<ENUM(N, VALUE FIX(M)), __VA_ARGS__>
#define MATRIX(M, N) \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, VALUE(M) COMMA(N) VALUES(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, VALUE(M) COMMA(N) NUMBERS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, VALUE(M) COMMA(N) PAIRS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, VALUE(M) COMMA(N) LISTS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, VALUE(M) COMMA(N) MAPS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, VALUE(M) COMMA(N) LAMBDAS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, NUMBER(M) COMMA(N) VALUES(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, NUMBER(M) COMMA(N) NUMBERS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, NUMBER(M) COMMA(N) PAIRS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, NUMBER(M) COMMA(N) LISTS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, NUMBER(M) COMMA(N) MAPS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, NUMBER(M) COMMA(N) LAMBDAS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, PAIR(M) COMMA(N) VALUES(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, PAIR(M) COMMA(N) NUMBERS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, PAIR(M) COMMA(N) PAIRS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, PAIR(M) COMMA(N) LISTS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, PAIR(M) COMMA(N) MAPS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, PAIR(M) COMMA(N) LAMBDAS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LIST(M) COMMA(N) VALUES(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LIST(M) COMMA(N) NUMBERS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LIST(M) COMMA(N) PAIRS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LIST(M) COMMA(N) LISTS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LIST(M) COMMA(N) MAPS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LIST(M) COMMA(N) LAMBDAS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, MAP(M) COMMA(N) VALUES(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, MAP(M) COMMA(N) NUMBERS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, MAP(M) COMMA(N) PAIRS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, MAP(M) COMMA(N) LISTS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, MAP(M) COMMA(N) MAPS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, MAP(M) COMMA(N) LAMBDAS(N)>), (FALSE)); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LAMBDA(M) COMMA(N) VALUES(N)>), (BOOL(N == 1 || (M == 2 && N)))); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LAMBDA(M) COMMA(N) NUMBERS(N)>), (BOOL(N == 1 || (M == 2 && N)))); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LAMBDA(M) COMMA(N) PAIRS(N)>), (BOOL(N == 1 || (M == 2 && N)))); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LAMBDA(M) COMMA(N) LISTS(N)>), (BOOL(N == 1 || (M == 2 && N)))); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LAMBDA(M) COMMA(N) MAPS(N)>), (BOOL(N == 1 || (M == 2 && N)))); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LAMBDA(M) COMMA(N) LAMBDAS(N)>), (BOOL(N == 1 || (M == 2 && N)))); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LAMBDA(_) COMMA(N) VALUES(N)>), (BOOL(N > 0))); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LAMBDA(_) COMMA(N) NUMBERS(N)>), (BOOL(N > 0))); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LAMBDA(_) COMMA(N) PAIRS(N)>), (BOOL(N > 0))); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LAMBDA(_) COMMA(N) LISTS(N)>), (BOOL(N > 0))); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LAMBDA(_) COMMA(N) MAPS(N)>), (BOOL(N > 0))); \
CHECK((metal::is_invocable<metal::lambda<metal::fold_right>, LAMBDA(_) COMMA(N) LAMBDAS(N)>), (BOOL(N > 0))); \
CHECK((metal::fold_right<LAMBDA(_) COMMA(N) VALUES(N), VALUE(M)>), (FOLD_RIGHT(N, 1, ENTRY, VALUE(M)))); \
CHECK((metal::fold_right<LAMBDA(2) COMMA(M) TAGSX20(M) COMMA(N) TAGSX20(N), NUMBER(2)>), (NUMBER(2))); \
/**/
GEN(MATRIX)
| 90.553571
| 133
| 0.644252
|
brunocodutra
|
bcd5bd06fd1a55cb57eaf9ff6525494682d0334c
| 2,044
|
cpp
|
C++
|
leetcode/leetcode1560.cpp
|
KevinYang515/C-Projects
|
1bf95a09a0ffc18102f12263c9163619ce6dba55
|
[
"MIT"
] | null | null | null |
leetcode/leetcode1560.cpp
|
KevinYang515/C-Projects
|
1bf95a09a0ffc18102f12263c9163619ce6dba55
|
[
"MIT"
] | null | null | null |
leetcode/leetcode1560.cpp
|
KevinYang515/C-Projects
|
1bf95a09a0ffc18102f12263c9163619ce6dba55
|
[
"MIT"
] | null | null | null |
#include <vector>
#include <iostream>
#include <vector>
#include <map>
using namespace std;
vector<int> mostVisited_1(int n, vector<int>& rounds);
vector<int> mostVisited_2(int n, vector<int>& rounds);
int main(){
vector<int> n_v ={4, 2, 7, 3};
vector<vector<int>> rounds_v = {{1,3,1,2},
{2,1,2,1,2,1,2,1,2},
{1,3,5,7},
{3,2,1,2,1,3,2,1,2,1,3,2,3,1}};
for (int i = 0; i < n_v.size(); i++){
for (int ans : mostVisited_1(n_v[i], rounds_v[i])){
printf("%d, ", ans);
}
printf("\n");
}
printf("==================\n");
for (int i = 0; i < n_v.size(); i++){
for (int ans : mostVisited_2(n_v[i], rounds_v[i])){
printf("%d, ", ans);
}
printf("\n");
}
return 0;
}
vector<int> mostVisited_1(int n, vector<int>& rounds) {
map<int, int> count;
vector<int> result;
for (int i = 0; i < n; i++){
count[i + 1] = 0;
}
for (int i = 0; i < rounds.size() - 1; i++){
int start = rounds[i];
int end = rounds[i + 1];
if(i == 0) count[start] += 1;
while (start != end){
start ++;
start %= n;
if (start == 0) start = n;
count[start] += 1;
}
}
int max = count[rounds[0]];
for(map<int,int>::iterator it = count.begin(); it != count.end(); ++it) {
if (it->second == max){
result.push_back(it->first);
}
}
return result;
}
// Time Complexity: O(n)
// Space Complexity: O(n)
vector<int> mostVisited_2(int n, vector<int>& rounds){
vector<int> result;
for (int i = rounds[0]; i <= rounds[rounds.size() - 1]; i++){
result.push_back(i);
}
if (result.size() > 0) return result;
for (int i = 1; i <= rounds[rounds.size() - 1]; i++)
result.push_back(i);
for (int i = rounds[0]; i <= n; i++)
result.push_back(i);
return result;
}
| 24.926829
| 77
| 0.460861
|
KevinYang515
|
bcdb2b45a4bfbc19f6425145d14cd70b8b10a915
| 315
|
cpp
|
C++
|
firstCppCourse/reversingNumberWhileLoop.cpp
|
Nickeron-dev/Basics-Of-CPP
|
84e2cd50c9bd466830054715a1cd708f87311e7b
|
[
"Apache-2.0"
] | 1
|
2021-09-15T15:11:39.000Z
|
2021-09-15T15:11:39.000Z
|
firstCppCourse/reversingNumberWhileLoop.cpp
|
Nickeron-dev/Basics-Of-CPP
|
84e2cd50c9bd466830054715a1cd708f87311e7b
|
[
"Apache-2.0"
] | null | null | null |
firstCppCourse/reversingNumberWhileLoop.cpp
|
Nickeron-dev/Basics-Of-CPP
|
84e2cd50c9bd466830054715a1cd708f87311e7b
|
[
"Apache-2.0"
] | null | null | null |
#include<iostream>
int main() {
int number, reversedNumber = 0;
std::cout << "Input number to reverse: " << std::endl;
std::cin >> number;
while (number != 0) {
reversedNumber *= 10;
reversedNumber += number % 10;
number /= 10;
}
std::cout << "Answer: " << reversedNumber << std::endl;
}
| 19.6875
| 57
| 0.584127
|
Nickeron-dev
|
bcdc4ff628e1d88215768b81d1e4651e15dc0822
| 1,162
|
cpp
|
C++
|
tests/bitonic_sort/simple_test.cpp
|
llpm/SpatialC
|
618d86fe948a7839fe4903a77da08941e169ae2e
|
[
"Apache-2.0"
] | null | null | null |
tests/bitonic_sort/simple_test.cpp
|
llpm/SpatialC
|
618d86fe948a7839fe4903a77da08941e169ae2e
|
[
"Apache-2.0"
] | null | null | null |
tests/bitonic_sort/simple_test.cpp
|
llpm/SpatialC
|
618d86fe948a7839fe4903a77da08941e169ae2e
|
[
"Apache-2.0"
] | null | null | null |
#include "Simple.hpp"
#include "obj/verilator_extra.h"
#include <cstdio>
#include <stdint.h>
#include <cassert>
#include <cstdlib>
#define NUM 4
int main() {
Simple* s = new Simple();
s->trace("debug.vcd");
s->reset();
uint32_t tmp;
start_debug(fopen("debug.txt", "w"));
srand(time(NULL));
for (int32_t i=0; i<NUM; i++) {
unsigned val = rand() % 1000;
printf("[%lu] %d: %u\n", s->cycles(), i, val);
s->write(i, val);
// s->run(5);
}
for (int32_t i=0; i<NUM; i++) {
s->read(i);
int32_t n;
s->val((uint32_t*)&n);
printf("%d\n", n);
}
printf("Sorting!\n");
uint64_t start = s->cycles();
s->sort();
s->sortDone(&tmp);
uint64_t stop = s->cycles();
printf("Took %lu cycles to run\n", stop - start);
int32_t last;
for (int32_t i=0; i<NUM; i++) {
s->read(i);
int32_t n;
s->val((uint32_t*)&n);
if (i > 1 && n > last) {
printf("%d FAIL\n", n);
} else {
printf("%d\n", n);
}
last = n;
}
close_debug();
delete s;
return 0;
}
| 17.876923
| 54
| 0.471601
|
llpm
|
bcdfa3f6478b6122a5fcee0d53aef5f6a2e1732f
| 3,239
|
cpp
|
C++
|
library/log.cpp
|
atzom/messagesparser
|
13942b2d8d3ccc05f1f1e118506c113b57552b3e
|
[
"BSD-3-Clause"
] | 1
|
2020-07-07T09:17:05.000Z
|
2020-07-07T09:17:05.000Z
|
library/log.cpp
|
atzom/messagesparser
|
13942b2d8d3ccc05f1f1e118506c113b57552b3e
|
[
"BSD-3-Clause"
] | null | null | null |
library/log.cpp
|
atzom/messagesparser
|
13942b2d8d3ccc05f1f1e118506c113b57552b3e
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2015, Andreas Tzomakas
* 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 messagesparser nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "log.h"
#include "strutil.h"
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
namespace MessagesParser
{
Log::Log()
{
}
Log::~Log()
{
Clear();
}
void Log::Add(std::string &data)
{
Msg *pMsg = new (std::nothrow) Msg(data, m_cfg.Get_Parts()->size());
Msg::Msg_Part *p;
if ( ! pMsg)
{
std::cerr << "Couldn't allocate memory, aborting adding log line..." << std::endl;
return;
}
for (Config::Formats_t::iterator iter = m_cfg.Get_Formats()->begin(); iter != m_cfg.Get_Formats()->end(); iter++)
{
Config::LogFormat *_format = *iter;
pMsg->Add_Format(_format);
}
pMsg->Set_Identifier(m_cfg.Get_Identifier());
size_t _part_number = 0;
for (Config::Parts_t::iterator iter = m_cfg.Get_Parts()->begin(); iter != m_cfg.Get_Parts()->end(); iter++)
{
pMsg->Set_Part_Name(_part_number, *iter);
_part_number++;
}
///////////////////////////////////////////////////////
pMsg->Extract();
p = pMsg->Get_Part(pMsg->Get_Identifier());
if (p)
{
m_log.insert(std::pair<std::string, Msg *>(p->_data, pMsg));
}
else
{
delete pMsg;
}
}
void Log::Clear()
{
Log_t::iterator iter;
for (iter = m_log.begin(); iter != m_log.end(); ++iter)
{
Msg *p = iter->second;
if (p)
delete p;
}
m_log.clear();
}
}
| 29.18018
| 121
| 0.609447
|
atzom
|
bcdfa5232d28d728127dce528f0d986149f6de51
| 13,976
|
cpp
|
C++
|
Tools/RichToolTipCtrl.cpp
|
lcsteyn/DSS
|
7991c8ddbeb7b2626234cd8ba1e9cb336bbf97c9
|
[
"BSD-3-Clause"
] | 497
|
2019-06-20T09:52:58.000Z
|
2022-03-31T12:56:49.000Z
|
Tools/RichToolTipCtrl.cpp
|
lcsteyn/DSS
|
7991c8ddbeb7b2626234cd8ba1e9cb336bbf97c9
|
[
"BSD-3-Clause"
] | 58
|
2019-06-19T10:53:49.000Z
|
2022-02-14T22:43:18.000Z
|
Tools/RichToolTipCtrl.cpp
|
lcsteyn/DSS
|
7991c8ddbeb7b2626234cd8ba1e9cb336bbf97c9
|
[
"BSD-3-Clause"
] | 57
|
2019-07-08T16:08:01.000Z
|
2022-03-12T15:00:04.000Z
|
////////////////////////////////////////////////////////////////////////////
// File: RichToolTipCtrl.cpp
// Version: 1.1
// Created: 22-Mar-2005
//
// Author: Paul S. Vickery
// E-mail: developer@vickeryhome.freeserve.co.uk
//
// Class to provide a means of using rich text in a tool-tip, without using
// the newer styles only available in later systems. Based on CToolTipCtrl.
//
// You are free to use or modify this code, with no restrictions, other than
// you continue to acknowledge me as the original author in this source code,
// or any code derived from it.
//
// If you use this code, or use it as a base for your own code, it would be
// nice to hear from you simply so I know it's not been a waste of time!
//
// Copyright (c) 2005 Paul S. Vickery
//
////////////////////////////////////////////////////////////////////////////
// Version History:
//
// Version 1.1 - 22-Mar-2005
// =========================
// - Added static method for escaping plain text to make it RTF safe
// - Modified the positioning to work on multi-monitor systems
// - Removed dependency on RichToolTipCtrlDemo.h
//
// Version 1.0 - 14-Mar-2005
// =========================
// Initial version
//
////////////////////////////////////////////////////////////////////////////
// PLEASE LEAVE THIS HEADER INTACT
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "RichToolTipCtrl.h"
#ifndef __AFXDISP_H__
#error You need to #include <afxdisp.h> here or in your stdafx.h
#endif
#include "atlconv.h" // for Unicode conversion - requires #include <afxdisp.h> // MFC OLE automation classes
#include <afxole.h> // for COleClientItem
// #define COMPILE_MULTIMON_STUBS // for late-binding to multi-monitor functions
// #include <multimon.h> // for multi-monitor support
/////////////////////////////////////////////////////////////////////////////
// CRichToolTipCtrl::CRichToolTipRichEditCtrl
CRichToolTipCtrl::CRichToolTipRichEditCtrl::CRichToolTipRichEditCtrl()
{
}
CRichToolTipCtrl::CRichToolTipRichEditCtrl::~CRichToolTipRichEditCtrl()
{
}
BEGIN_MESSAGE_MAP(CRichToolTipCtrl::CRichToolTipRichEditCtrl, CRichEditCtrl)
//{{AFX_MSG_MAP(CRichToolTipCtrl::CRichToolTipRichEditCtrl)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CRichToolTipCtrl::CRichToolTipRichEditCtrl message handlers
// cookie class to assist with streaming a CString into the richedit control
class _RichToolTipCtrlCookie
{
public:
_RichToolTipCtrlCookie(CString sText) : m_sText(sText) { m_dwCount = 0; m_dwLength = m_sText.GetLength(); }
DWORD Read(LPSTR lpszBuffer, DWORD dwCount);
void Reset() { m_dwCount = 0; m_dwLength = m_sText.GetLength(); }
protected:
CString m_sText;
DWORD m_dwLength;
DWORD m_dwCount;
};
// read dwCount bytes into lpszBuffer, and return number read
// stop if source is empty, or when end of string reached
DWORD _RichToolTipCtrlCookie::Read(LPSTR lpszBuffer, DWORD dwCount)
{
if (lpszBuffer == nullptr)
return -1;
// have we already had it all?
DWORD dwLeft = m_dwLength - m_dwCount;
if (dwLeft <= 0) // all done
return 0;
// start the source string from where we left off
USES_CONVERSION;
LPCSTR lpszText = (LPCSTR)T2A(m_sText.GetBuffer(0)) + m_dwCount;
// only copy what we've got left
if (dwLeft < dwCount)
dwCount = dwLeft;
// copy the text
strncpy(lpszBuffer, lpszText, dwCount);
// keep where we got to
m_dwCount += dwCount;
// return how many we copied
return dwCount;
}
static DWORD CALLBACK RichTextCtrlCallbackIn(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb)
{
// the cookie is a pointer to the text data struct
_RichToolTipCtrlCookie* pBuf = (_RichToolTipCtrlCookie*)dwCookie;
if (pBuf == nullptr)
return 1;
*pcb = pBuf->Read((LPSTR)pbBuff, cb);
return 0;
}
int CRichToolTipCtrl::CRichToolTipRichEditCtrl::StreamTextIn(LPCTSTR lpszText)
{
EDITSTREAM es;
_RichToolTipCtrlCookie data(lpszText);
es.dwCookie = (DWORD_PTR)&data;
es.pfnCallback = RichTextCtrlCallbackIn;
int n = StreamIn(SF_RTF, es);
if (n <= 0)
{
data.Reset();
n = StreamIn(SF_TEXT, es);
}
return n;
}
/////////////////////////////////////////////////////////////////////////////
// CRichToolTipCtrl::XRichEditOleCallback
BEGIN_INTERFACE_MAP(CRichToolTipCtrl, CToolTipCtrl)
// we use IID_IUnknown because richedit doesn't define an IID
INTERFACE_PART(CRichToolTipCtrl, IID_IUnknown, RichEditOleCallback)
END_INTERFACE_MAP()
STDMETHODIMP CRichToolTipCtrl::XRichEditOleCallback::GetNewStorage(LPSTORAGE* ppstg)
{
// Create a flat storage and steal it from the client item
// the client item is only used for creating the storage
COleClientItem item;
item.GetItemStorageFlat();
*ppstg = item.m_lpStorage;
HRESULT hRes = E_OUTOFMEMORY;
if (item.m_lpStorage != nullptr)
{
item.m_lpStorage = nullptr;
hRes = S_OK;
}
return hRes;
}
/////////////////////////////////////////////////////////////////////////////
// CRichToolTipCtrl
IMPLEMENT_DYNAMIC(CRichToolTipCtrl, CToolTipCtrl)
CRichToolTipCtrl::CRichToolTipCtrl()
{
AfxInitRichEdit();
}
CRichToolTipCtrl::~CRichToolTipCtrl()
{
}
BEGIN_MESSAGE_MAP(CRichToolTipCtrl, CToolTipCtrl)
//{{AFX_MSG_MAP(CRichToolTipCtrl)
ON_WM_CREATE()
//}}AFX_MSG_MAP
ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnCustomDraw)
ON_NOTIFY_REFLECT(TTN_SHOW, OnShow)
END_MESSAGE_MAP()
/*static*/
CString CRichToolTipCtrl::MakeTextRTFSafe(LPCTSTR lpszText)
{
// modify the specified text to make it safe for use in a rich-edit
// control, by escaping special RTF characters '\', '{' and '}'
CString sRTF;
if (lpszText != nullptr)
{
while (*lpszText != '\0')
{
if (*lpszText == _T('\\') || *lpszText == _T('{') || *lpszText == _T('}'))
sRTF += _T('\\');
else if (*lpszText == _T('\r') && *(lpszText+1) == _T('\n') ||
(*lpszText == _T('\n') && *(lpszText+1) == _T('\r')))
{
sRTF += _T("{\\par}");
sRTF += *lpszText;
lpszText++;
}
else if (*(lpszText) == _T('\n') || *(lpszText) == _T('\r'))
sRTF += _T("{\\par}");
sRTF += *lpszText;
lpszText++;
}
}
return sRTF;
}
/////////////////////////////////////////////////////////////////////////////
// CRichToolTipCtrl message handlers
int CRichToolTipCtrl::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CToolTipCtrl::OnCreate(lpCreateStruct) == -1)
return -1;
// set the max width to half of the screen width, and
// force the ability to use CRLFs to make multi-line tips
SetMaxTipWidth(::GetSystemMetrics(SM_CXSCREEN) / 2);
// create a hidden child richedit control
m_edit.Create(WS_CHILD | ES_MULTILINE | ES_READONLY, CRect(0, 0, 0, 0), this, 1);
// set the edit control's ole callback handler
VERIFY(m_edit.SetOLECallback(&m_xRichEditOleCallback));
return 0;
}
BOOL CRichToolTipCtrl::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult)
{
NMHDR* pnmhdr = (NMHDR*)lParam;
if (pnmhdr != nullptr)
{
if (pnmhdr->code == EN_REQUESTRESIZE)
{
REQRESIZE* prr = (REQRESIZE*)pnmhdr;
m_sizeEditMin.cx = prr->rc.right - prr->rc.left;
m_sizeEditMin.cy = prr->rc.bottom - prr->rc.top;
}
}
return CToolTipCtrl::OnNotify(wParam, lParam, pResult);
}
// this code gets the minimium size for a rich edit control, and is
// taken from http://www.codeproject.com/richedit/richeditsize.asp
CSize CRichToolTipCtrl::CalculateMinimiumRichEditSize()
{
m_edit.SetEventMask(ENM_REQUESTRESIZE);
// m_sizeEditMin is a CSize object that stores m_edit required size
m_sizeEditMin.cx = m_sizeEditMin.cy = 0;
// Performing the binary search for the best dimension
int cxFirst = 0;
int cxLast = GetMaxTipWidth();
if (cxLast < 0)
cxLast = ::GetSystemMetrics(SM_CXSCREEN);
int cyMin = 0;
cxLast *= 2; // cos the first thing we do it divide it by two
do
{
// Taking a guess
int cx = (cxFirst + cxLast) / 2;
// Testing this guess
CRect rc(0, 0, cx, 1);
m_edit.MoveWindow(rc);
m_edit.SetRect(rc);
m_edit.RequestResize();
// If it's the first time, take the result anyway.
// This is the minimum height the control needs
if (cyMin == 0)
cyMin = m_sizeEditMin.cy;
// Iterating
if (m_sizeEditMin.cy > cyMin)
{
// If the control required a larger height, then
// it's too narrow.
cxFirst = cx + 1;
}
else
{
// If the control didn't required a larger height,
// then it's too wide.
cxLast = cx - 1;
}
}
while (cxFirst < cxLast);
if (m_sizeEditMin.cy > cyMin)
{
// it's gone wrong. so add one to the last width, and do it again
// it does this sometimes, depending on the exact figures
CRect rc(0, 0, cxLast + 1, 1);
m_edit.MoveWindow(rc);
m_edit.SetRect(rc);
m_edit.RequestResize();
_ASSERTE(m_sizeEditMin.cy == cyMin);
// if the above assert fails, then remove it: we're probably not going to get it any better
}
// Giving it a few pixels extra width for safety
m_sizeEditMin.cx += 2;
m_sizeEditMin.cy += 2;
// Moving the control
m_edit.MoveWindow(0, 0, m_sizeEditMin.cx, m_sizeEditMin.cy);
return m_sizeEditMin;
}
void CRichToolTipCtrl::OnShow(NMHDR* pNMHDR, LRESULT* pResult)
{
*pResult = 0;
// the control is about to be displayed
// we can update the edit control, and re-set the text
// make sure the edit control is using the correct font and colours
// and make sure we don't have any formatting effects set
m_edit.SetBackgroundColor(FALSE, GetTipBkColor());
m_edit.SetWindowText(_T(""));
CHARFORMAT cf;
ZeroMemory(&cf, sizeof(CHARFORMAT));
cf.cbSize = sizeof(CHARFORMAT);
cf.dwMask = CFM_BOLD | CFM_COLOR | CFM_ITALIC | CFM_PROTECTED | CFM_STRIKEOUT | CFM_UNDERLINE;
cf.crTextColor = GetTipTextColor();
m_edit.SetDefaultCharFormat(cf);
m_edit.SetFont(GetFont());
CString sText;
GetWindowText(sText);
m_edit.StreamTextIn(sText);
SetWindowText(_T(""));
// find out how big the tip window should be
CSize size = CalculateMinimiumRichEditSize();
// set the tool-tip's drawing rect
size.cx += 5; // add a few more on, cos we'll use them for a margin later
size.cy += 5;
// it seems that if any text is right-aligned, or centered, then
// it just creeps over the right-hand edge
// the best we can do to see if it has any right or centre text
// is to see if the RTF contains "\qr" or "\qc" tags, and add a bit on
// (we don't cater for text having "\qr" or "\qc" somewhere in it;
// in this case we add on the extra anyway. If we cared we could look for
// a "\qr" which is not really a "\\qr", but that could be quite expensive)
int nPos = sText.Find(_T("\\q"));
if (nPos >= 0 && (sText[nPos + 2] == _T('r') || sText[nPos + 2] == _T('c')))
size.cx += 5;
// calc the new tip window size and position, and move it
CRect rc;
GetWindowRect(rc);
// position the tip with its left edge at the mouse's x
CPoint ptCursor;
GetCursorPos(&ptCursor);
rc.left = ptCursor.x;
rc.top = ptCursor.y + 16;
// move it to the left if it's going to go off the edge of the screen
// but don't move it off the left of the current desktop
int cxScreen = ::GetSystemMetrics(SM_CXSCREEN);
int cyScreen = ::GetSystemMetrics(SM_CYSCREEN);
CRect rcDesktop(0, 0, cxScreen, cyScreen);
// adjust the desktop rect for the monitor that contains the cursor
if (! rcDesktop.PtInRect(ptCursor))
{
HMONITOR hMonitor = MonitorFromPoint(ptCursor, MONITOR_DEFAULTTONEAREST);
if (hMonitor != nullptr)
{
MONITORINFO mi;
mi.cbSize = sizeof(MONITORINFO);
if (GetMonitorInfo(hMonitor, &mi))
rcDesktop = mi.rcMonitor;
}
}
if ((size.cx + rc.left) > rcDesktop.Width())
rc.left = max(rcDesktop.left, rc.left - ((rc.left + size.cx) - rcDesktop.Width()));
// position it above the mouse if it would go off the bottom of the screen
// but don't move it off the top of the screen
if ((size.cy + rc.top) > rcDesktop.Height())
rc.top = max(rcDesktop.top, (ptCursor.y - 16) - size.cy);
rc.right = rc.left + (size.cx);
rc.bottom = rc.top + (size.cy);
MoveWindow(&rc);
*pResult = TRUE; // we've moved it
}
void CRichToolTipCtrl::OnCustomDraw(NMHDR* pNMHDR, LRESULT* pResult)
{
LPNMTTCUSTOMDRAW lpttcd = (LPNMTTCUSTOMDRAW)pNMHDR;
*pResult = CDRF_DODEFAULT;
if (! ::IsWindow(m_edit.m_hWnd))
return; // can't do it!
switch (lpttcd->nmcd.dwDrawStage)
{
case CDDS_PREPAINT:
{
*pResult = CDRF_NOTIFYPOSTPAINT; // we want post-paint notifications
// set the text and back colours of the default text
// so it becomes invisible
COLORREF crTipBk = GetTipBkColor();
::SetTextColor(lpttcd->nmcd.hdc, crTipBk);
::SetBkColor(lpttcd->nmcd.hdc, crTipBk);
}
break;
case CDDS_POSTPAINT:
{
// FormatRange needs its rect in twips
// a twip is 1/20 of a printer's point (1,440 twips equal one inch)
int nLogPixelsX = ::GetDeviceCaps(lpttcd->nmcd.hdc, LOGPIXELSX);
int nLogPixelsY = ::GetDeviceCaps(lpttcd->nmcd.hdc, LOGPIXELSY);
// get the drawing rect, and convert to twips
CRect rc(lpttcd->nmcd.rc);
rc.DeflateRect(1, 1, 1, 1); // give it a small margin
rc.left = MulDiv(rc.left, 1440, nLogPixelsX);
rc.right = MulDiv(rc.right, 1440, nLogPixelsX);
rc.top = MulDiv(rc.top, 1440, nLogPixelsY);
rc.bottom = MulDiv(rc.bottom, 1440, nLogPixelsY);
// use the rich edit control to draw to our device context
FORMATRANGE fr;
fr.hdc = lpttcd->nmcd.hdc;
fr.hdcTarget = lpttcd->nmcd.hdc;
fr.chrg.cpMin = 0;
fr.chrg.cpMax = -1;
fr.rc = rc; // in twips
fr.rcPage = fr.rc;
m_edit.FormatRange(&fr, TRUE);
m_edit.FormatRange(nullptr, FALSE); // get the control to free its cached info
*pResult = CDRF_SKIPDEFAULT; // we don't want the default drawing
}
break;
}
}
| 30.852097
| 111
| 0.64668
|
lcsteyn
|
bce57a9f41bdc490f92c308b399eb8c8ead3d8e8
| 1,683
|
cpp
|
C++
|
src/TP1/Rectangle.cpp
|
PierreAlexandreGarneau/ProgAvI_H17_TP1_Vector2D3D_444
|
7c6978ec269ef4a3c77237dcf20602c74c0aceae
|
[
"MIT"
] | null | null | null |
src/TP1/Rectangle.cpp
|
PierreAlexandreGarneau/ProgAvI_H17_TP1_Vector2D3D_444
|
7c6978ec269ef4a3c77237dcf20602c74c0aceae
|
[
"MIT"
] | null | null | null |
src/TP1/Rectangle.cpp
|
PierreAlexandreGarneau/ProgAvI_H17_TP1_Vector2D3D_444
|
7c6978ec269ef4a3c77237dcf20602c74c0aceae
|
[
"MIT"
] | null | null | null |
#include "Rectangle.h"
Rectangle::Rectangle(float x, float y, float width, float height)
{
_x = x;
_y = y;
_w = width;
_h = height;
}
Rectangle::Rectangle(Vector2D* topLeft, Vector2D* btmRight) :
Rectangle::Rectangle(topLeft->x, topLeft->y, btmRight->x - topLeft->x, topLeft->y - btmRight->y)
{
}
float Rectangle::GetX() const
{
return _x;
}
//Retourne la position y du coin top left du rectangle
float Rectangle::GetY() const
{
return _y;
}
//Retourne la largeur du rectangle
float Rectangle::GetWidth() const
{
return _w;
}
//Retourne la hauteur du rectangle
float Rectangle::GetHeight() const
{
return _h;
}
//Determine si le point est dans le rectangle
bool Rectangle::Contains(float x, float y) const
{
return x >= _x && x <= _x + _w &&
y >= _y - _h && y <= _y;
}
//Determine si le point est dans le rectangle
bool Rectangle::Contains(Vector2D* point)
{
return this->Contains(point->x, point->y);
}
//Definit le coin top left du rectangle
void Rectangle::SetPosition(float x, float y)
{
_x = x;
_y = y;
}
//Definit le coin top left du rectangle
void Rectangle::SetPosition(Vector2D* vect)
{
this->SetPosition(vect->x, vect->y);
}
//Deplace le regtangle
void Rectangle::MoveBy(float x, float y)
{
_x += x;
_y += y;
}
//Deplace le regtangle
void Rectangle::MoveBy(Vector2D* vect)
{
this->MoveBy(vect->x, vect->y);
}
//Pour la collision un des 4 coins d un des retangles doit etre contenu dans l autre
bool Rectangle::CollidesWith(Rectangle* rect) const
{
return Contains(rect->_x, rect->_y) ||
Contains(rect->_x + rect->_w, rect->_y) ||
Contains(rect->_x, rect->_y - rect->_h) ||
Contains(rect->_x + rect->_w, rect->_y - rect->_h);
}
| 19.344828
| 97
| 0.67855
|
PierreAlexandreGarneau
|
bce9341e9f9bc7f3bc775b751b73c9728862f71d
| 1,686
|
cpp
|
C++
|
sdk/storage/azure-storage-common/src/storage_per_retry_policy.cpp
|
ku-sourav/azure-sdk-for-cpp
|
1abb101fde485cc6a0a0a22681a5dc005db9fba6
|
[
"MIT"
] | 1
|
2020-12-19T11:58:53.000Z
|
2020-12-19T11:58:53.000Z
|
sdk/storage/azure-storage-common/src/storage_per_retry_policy.cpp
|
ku-sourav/azure-sdk-for-cpp
|
1abb101fde485cc6a0a0a22681a5dc005db9fba6
|
[
"MIT"
] | null | null | null |
sdk/storage/azure-storage-common/src/storage_per_retry_policy.cpp
|
ku-sourav/azure-sdk-for-cpp
|
1abb101fde485cc6a0a0a22681a5dc005db9fba6
|
[
"MIT"
] | null | null | null |
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
#include <azure/core/platform.hpp>
#include "azure/storage/common/storage_per_retry_policy.hpp"
#include <ctime>
namespace Azure { namespace Storage { namespace Details {
std::unique_ptr<Core::Http::RawResponse> StoragePerRetryPolicy::Send(
Core::Context const& ctx,
Core::Http::Request& request,
Core::Http::NextHttpPolicy nextHttpPolicy) const
{
const char* HttpHeaderDate = "Date";
const char* HttpHeaderXMsDate = "x-ms-date";
const auto& headers = request.GetHeaders();
if (headers.find(HttpHeaderDate) == headers.end())
{
// add x-ms-date header in RFC1123 format
// TODO: call helper function provided by Azure Core when they provide one.
time_t t = std::time(nullptr);
struct tm ct;
#if defined(AZ_PLATFORM_WINDOWS)
gmtime_s(&ct, &t);
#elif defined(AZ_PLATFORM_POSIX)
gmtime_r(&t, &ct);
#endif
static const char* weekdays[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
static const char* months[]
= {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
std::string rfc1123Format = "%a, %d %b %Y %H:%M:%S GMT";
rfc1123Format.replace(rfc1123Format.find("%a"), 2, weekdays[ct.tm_wday]);
rfc1123Format.replace(rfc1123Format.find("%b"), 2, months[ct.tm_mon]);
char datetimeStr[32];
std::strftime(datetimeStr, sizeof(datetimeStr), rfc1123Format.data(), &ct);
request.AddHeader(HttpHeaderXMsDate, datetimeStr);
}
return nextHttpPolicy.Send(ctx, request);
}
}}} // namespace Azure::Storage::Details
| 35.125
| 97
| 0.654804
|
ku-sourav
|
bcf2571630aec3818f72154b13ce2e9af57cd33c
| 577
|
cpp
|
C++
|
gdw_project/gdw/src/utilities/GitRevision.cpp
|
GDW2018/GDW
|
a57cff2cf49a7f052d0dac0d2b532dfb82de4d0d
|
[
"MIT"
] | 3
|
2018-08-12T06:51:44.000Z
|
2019-05-18T04:10:33.000Z
|
gdw_project/gdw/src/utilities/GitRevision.cpp
|
GDW2018/GDW
|
a57cff2cf49a7f052d0dac0d2b532dfb82de4d0d
|
[
"MIT"
] | null | null | null |
gdw_project/gdw/src/utilities/GitRevision.cpp
|
GDW2018/GDW
|
a57cff2cf49a7f052d0dac0d2b532dfb82de4d0d
|
[
"MIT"
] | null | null | null |
#include <stdint.h>
#include <utilities/GitRevision.hpp>
#define GDWCORE_GIT_REVISION_SHA "7e7f255f185ffaf53397084f6ca747674088f176"
#define GDWCORE_GIT_REVISION_UNIX_TIMESTAMP 1488663957
#define GDWCORE_GIT_REVISION_DESCRIPTION "GDW"
namespace gdwcore {
namespace utilities {
const char* const git_revision_sha = GDWCORE_GIT_REVISION_SHA;
const uint32_t git_revision_unix_timestamp = GDWCORE_GIT_REVISION_UNIX_TIMESTAMP;
const char* const git_revision_description = GDWCORE_GIT_REVISION_DESCRIPTION;
}
} // end namespace gdwcore::utilities
| 33.941176
| 89
| 0.809359
|
GDW2018
|
bcf366d7bb468926c741fabf08681d3696ca02b7
| 1,967
|
cpp
|
C++
|
src/database/overlay/ftgl/src/FTOutlineGlyph.cpp
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | 2
|
2020-05-21T07:06:07.000Z
|
2021-06-28T02:14:34.000Z
|
src/database/overlay/ftgl/src/FTOutlineGlyph.cpp
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | null | null | null |
src/database/overlay/ftgl/src/FTOutlineGlyph.cpp
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | 6
|
2016-03-21T19:53:18.000Z
|
2021-06-08T18:06:03.000Z
|
/*
Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation
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 "FTOutlineGlyph.h"
#include "FTVectoriser.h"
FTOutlineGlyph::FTOutlineGlyph( FT_GlyphSlot glyph, bool useDisplayList)
: FTGlyph( glyph),
glList(0)
{
if( ft_glyph_format_outline != glyph->format)
{
err = 0x14; // Invalid_Outline
return;
}
FTVectoriser vectoriser( glyph);
size_t numContours = vectoriser.ContourCount();
if ( ( numContours < 1) || ( vectoriser.PointCount() < 3))
{
return;
}
if(useDisplayList)
{
glList = glGenLists(1);
glNewList( glList, GL_COMPILE);
}
for( unsigned int c = 0; c < numContours; ++c)
{
const FTContour* contour = vectoriser.Contour(c);
glBegin( GL_LINE_LOOP);
for( unsigned int pointIndex = 0; pointIndex < contour->PointCount(); ++pointIndex)
{
FTPoint point = contour->Point(pointIndex);
glVertex2f( point.X() / 64.0f, point.Y() / 64.0f);
}
glEnd();
}
if(useDisplayList)
{
glEndList();
}
}
FTOutlineGlyph::~FTOutlineGlyph()
{
glDeleteLists( glList, 1);
}
const FTPoint& FTOutlineGlyph::Render( const FTPoint& pen)
{
glTranslatef( pen.X(), pen.Y(), 0.0f);
if( glList)
{
glCallList( glList);
}
return advance;
}
| 23.987805
| 95
| 0.635994
|
OpenXIP
|
bcfa05d228e854b30acded0a2cc72dfb1793c617
| 745
|
cpp
|
C++
|
backup/2/interviewbit/c++/highest-product.cpp
|
yangyanzhan/code-camp
|
4272564e916fc230a4a488f92ae32c07d355dee0
|
[
"Apache-2.0"
] | 21
|
2019-11-16T19:08:35.000Z
|
2021-11-12T12:26:01.000Z
|
backup/2/interviewbit/c++/highest-product.cpp
|
yangyanzhan/code-camp
|
4272564e916fc230a4a488f92ae32c07d355dee0
|
[
"Apache-2.0"
] | 1
|
2022-02-04T16:02:53.000Z
|
2022-02-04T16:02:53.000Z
|
backup/2/interviewbit/c++/highest-product.cpp
|
yangyanzhan/code-camp
|
4272564e916fc230a4a488f92ae32c07d355dee0
|
[
"Apache-2.0"
] | 4
|
2020-05-15T19:39:41.000Z
|
2021-10-30T06:40:31.000Z
|
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site .
// For this specific algothmic problem, visit my Youtube Video : .
// It's fascinating to solve algothmic problems, follow Yanzhan to learn more!
// Blog URL for this problem: https://yanzhan.site/interviewbit/highest-product.html .
int Solution::maxp3(vector<int> &A) {
int n = A.size();
sort(A.begin(), A.end());
return max(A[0] * A[1] * A[n - 1], A[n - 3] * A[n - 2] * A[n - 1]);
}
| 67.727273
| 345
| 0.702013
|
yangyanzhan
|
bcfa1edb78abc60f6eb5baae1239ca2742072a28
| 364
|
cpp
|
C++
|
Long September Challenge 2021/1. Airline Restrictions.cpp
|
MadanParth786/Codeshef-Problems
|
64ec3b9849992f3350dfe67f2dbc6332a665b471
|
[
"MIT"
] | 1
|
2021-07-09T16:44:41.000Z
|
2021-07-09T16:44:41.000Z
|
Long September Challenge 2021/1. Airline Restrictions.cpp
|
MadanParth786/Codeshef-Problems
|
64ec3b9849992f3350dfe67f2dbc6332a665b471
|
[
"MIT"
] | null | null | null |
Long September Challenge 2021/1. Airline Restrictions.cpp
|
MadanParth786/Codeshef-Problems
|
64ec3b9849992f3350dfe67f2dbc6332a665b471
|
[
"MIT"
] | null | null | null |
#include<iostream>
using namespace std;
int main(void)
{
int n;
cin>>n;
int a,b,c,d,e;
while(n--){
cin>>a>>b>>c>>d>>e;
if(a+b<=d and c<=e){
cout<<"YES"<<"\n";
}
else if(b+c<=d and a<=e){
cout<<"YES"<<"\n";
}
else if(c+a<=d and b<=e){
cout<<"YES"<<"\n";
}
else{
cout<<"NO"<<"\n";
}
}
}
| 13.481481
| 31
| 0.401099
|
MadanParth786
|
4c0018f6f1219e487afa8fd12632241bd7c6e5b5
| 2,277
|
cpp
|
C++
|
src/rfx/graphics/Buffer.cpp
|
rfruesmer/rfx
|
96c15a11ee8e2192c9d2ff233924eee884835f17
|
[
"MIT"
] | null | null | null |
src/rfx/graphics/Buffer.cpp
|
rfruesmer/rfx
|
96c15a11ee8e2192c9d2ff233924eee884835f17
|
[
"MIT"
] | null | null | null |
src/rfx/graphics/Buffer.cpp
|
rfruesmer/rfx
|
96c15a11ee8e2192c9d2ff233924eee884835f17
|
[
"MIT"
] | null | null | null |
#include "rfx/pch.h"
#include "rfx/graphics/Buffer.h"
using namespace rfx;
using namespace std;
// ---------------------------------------------------------------------------------------------------------------------
Buffer::Buffer(
VkDeviceSize size,
VkDevice device,
VkBuffer buffer,
VkDeviceMemory deviceMemory)
: size_(size),
device_(device),
buffer_(buffer),
deviceMemory_(deviceMemory)
{
// TODO: support for sub-buffer allocation
descriptorBufferInfo_ = {
.buffer = buffer,
.offset = 0,
.range = VK_WHOLE_SIZE
};
}
// ---------------------------------------------------------------------------------------------------------------------
Buffer::~Buffer()
{
vkFreeMemory(device_, deviceMemory_, nullptr);
vkDestroyBuffer(device_, buffer_, nullptr);
}
// ---------------------------------------------------------------------------------------------------------------------
void Buffer::load(size_t size, const void* data) const
{
RFX_CHECK_ARGUMENT(size <= size_);
uint8_t* mappedMemory = nullptr;
ThrowIfFailed(vkMapMemory(
device_,
deviceMemory_,
0,
size,
0,
reinterpret_cast<void**>(&mappedMemory)));
memcpy(mappedMemory, data, size);
vkUnmapMemory(device_, deviceMemory_);
}
// ---------------------------------------------------------------------------------------------------------------------
VkBuffer Buffer::getHandle() const
{
return buffer_;
}
// ---------------------------------------------------------------------------------------------------------------------
VkDeviceMemory Buffer::getDeviceMemory() const
{
return deviceMemory_;
}
// ---------------------------------------------------------------------------------------------------------------------
VkDeviceSize Buffer::getSize() const
{
return size_;
}
// ---------------------------------------------------------------------------------------------------------------------
const VkDescriptorBufferInfo& Buffer::getDescriptorBufferInfo() const
{
return descriptorBufferInfo_;
}
// ---------------------------------------------------------------------------------------------------------------------
| 26.788235
| 120
| 0.376812
|
rfruesmer
|
4c03fe1439c63e517d58466b9494415e15f384f6
| 5,443
|
cpp
|
C++
|
examples/text-overlap/text-overlap-example.cpp
|
Coquinho/dali-demo
|
6307bc22f92c7aaf333125282464bcb8abec3852
|
[
"Apache-2.0"
] | 8
|
2016-11-18T10:26:56.000Z
|
2021-05-03T10:26:30.000Z
|
examples/text-overlap/text-overlap-example.cpp
|
Coquinho/dali-demo
|
6307bc22f92c7aaf333125282464bcb8abec3852
|
[
"Apache-2.0"
] | 2
|
2020-07-26T11:54:24.000Z
|
2021-06-06T19:37:36.000Z
|
examples/text-overlap/text-overlap-example.cpp
|
Coquinho/dali-demo
|
6307bc22f92c7aaf333125282464bcb8abec3852
|
[
"Apache-2.0"
] | 6
|
2019-05-24T11:59:15.000Z
|
2021-05-24T07:34:39.000Z
|
/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* 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 "text-overlap-example.h"
#include <dali-toolkit/dali-toolkit.h>
#include <dali/devel-api/actors/actor-devel.h>
#include <iostream>
using namespace Dali;
using namespace Dali::Toolkit;
static const int NUMBER_OF_LABELS(2);
namespace Demo
{
TextOverlapController::TextOverlapController(Application& app)
: mApplication(app),
mTopmostLabel(1)
{
app.InitSignal().Connect(this, &TextOverlapController::Create);
app.TerminateSignal().Connect(this, &TextOverlapController::Destroy);
}
void TextOverlapController::Create(Application& app)
{
Window window = app.GetWindow();
window.KeyEventSignal().Connect(this, &TextOverlapController::OnKeyEvent);
Vector2 windowSize = window.GetSize();
mLabels[0] = TextLabel::New("Text Label 1");
mLabels[1] = TextLabel::New("Text Label 2");
mLabels[0].SetProperty(Dali::Actor::Property::NAME, "Label1");
mLabels[1].SetProperty(Dali::Actor::Property::NAME, "Label2");
mLabels[0].SetProperty(Dali::DevelActor::Property::SIBLING_ORDER, 1);
mLabels[1].SetProperty(Dali::DevelActor::Property::SIBLING_ORDER, 2);
mLabels[0].SetProperty(Control::Property::BACKGROUND, Color::RED);
mLabels[1].SetProperty(Control::Property::BACKGROUND, Color::YELLOW);
for(int i = 0; i < NUMBER_OF_LABELS; ++i)
{
mLabels[i].SetProperty(TextLabel::Property::HORIZONTAL_ALIGNMENT, "CENTER");
mLabels[i].SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
mLabels[i].SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
mLabels[i].SetProperty(Actor::Property::POSITION, Vector2(0, (i * 2 + 1) * windowSize.height * 0.25f));
}
window.Add(mLabels[0]);
window.Add(mLabels[1]);
mSwapButton = PushButton::New();
mSwapButton.SetProperty(Button::Property::LABEL, "Swap depth order");
mSwapButton.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_CENTER);
mSwapButton.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER);
mSwapButton.ClickedSignal().Connect(this, &TextOverlapController::OnClicked);
mSwapButton.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH);
mSwapButton.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT);
window.Add(mSwapButton);
Layer rootLayer = window.GetRootLayer();
rootLayer.SetProperty(Dali::Actor::Property::NAME, "RootLayer");
mPanDetector = PanGestureDetector::New();
mPanDetector.Attach(rootLayer);
mPanDetector.AddAngle(Radian(-0.5f * Math::PI));
mPanDetector.AddAngle(Radian(0.5f * Math::PI));
mPanDetector.DetectedSignal().Connect(this, &TextOverlapController::OnPan);
}
void TextOverlapController::OnPan(Actor actor, const PanGesture& gesture)
{
const GestureState state = gesture.GetState();
if(!mGrabbedActor || state == GestureState::STARTED)
{
const Vector2& gesturePosition = gesture.GetPosition();
for(int i = 0; i < NUMBER_OF_LABELS; ++i)
{
Vector3 position = mLabels[i].GetCurrentProperty<Vector3>(Actor::Property::POSITION);
Vector3 size = mLabels[i].GetCurrentProperty<Vector3>(Actor::Property::SIZE);
if(gesturePosition.y > position.y - size.y * 0.5f &&
gesturePosition.y <= position.y + size.y * 0.5f)
{
mGrabbedActor = mLabels[i];
break;
}
}
}
else if(mGrabbedActor && state == GestureState::CONTINUING)
{
Vector2 windowSize = mApplication.GetWindow().GetSize();
Vector3 size = mGrabbedActor.GetCurrentProperty<Vector3>(Actor::Property::SIZE);
const Vector2& gesturePosition = gesture.GetPosition();
float y = Clamp(gesturePosition.y, size.y * 0.5f, windowSize.y - size.y * 0.5f);
mGrabbedActor.SetProperty(Actor::Property::POSITION, Vector2(0, y));
}
else
{
mGrabbedActor.Reset();
}
}
void TextOverlapController::Destroy(Application& app)
{
mPanDetector.DetachAll();
UnparentAndReset(mLabels[0]);
UnparentAndReset(mLabels[1]);
mGrabbedActor.Reset();
}
bool TextOverlapController::OnClicked(Button button)
{
mTopmostLabel = 1 - mTopmostLabel; // toggles between 0 and 1
mLabels[mTopmostLabel].RaiseToTop();
return false;
}
void TextOverlapController::OnKeyEvent(const KeyEvent& keyEvent)
{
if(keyEvent.GetState() == KeyEvent::DOWN &&
(IsKey(keyEvent, DALI_KEY_BACK) ||
IsKey(keyEvent, DALI_KEY_ESCAPE)))
{
mApplication.Quit();
}
else
{
Dali::Layer l = mApplication.GetWindow().GetRootLayer();
int so = l.GetProperty<int>(Dali::DevelActor::Property::SIBLING_ORDER);
l.SetProperty(Dali::DevelActor::Property::SIBLING_ORDER, so + 1);
}
}
} // namespace Demo
int DALI_EXPORT_API main(int argc, char** argv)
{
{
Application app = Application::New(&argc, &argv);
Demo::TextOverlapController controller(app);
app.MainLoop();
}
exit(0);
}
| 33.392638
| 107
| 0.714312
|
Coquinho
|
4c04f0302d46e356038a5926b6954a3ad703d06c
| 555
|
cpp
|
C++
|
lab/Lab11/q6.cpp
|
B33pl0p/ioe-oop
|
87162561e0ced7e7e9cc7c7a8354d535de16e1f5
|
[
"MIT"
] | 4
|
2021-02-19T12:19:06.000Z
|
2022-02-11T14:15:49.000Z
|
lab/Lab11/q6.cpp
|
B33pl0p/ioe-oop
|
87162561e0ced7e7e9cc7c7a8354d535de16e1f5
|
[
"MIT"
] | null | null | null |
lab/Lab11/q6.cpp
|
B33pl0p/ioe-oop
|
87162561e0ced7e7e9cc7c7a8354d535de16e1f5
|
[
"MIT"
] | 12
|
2018-01-29T15:37:51.000Z
|
2022-02-10T06:45:03.000Z
|
// Write a meaningful program that can handle multiple exceptions.
#include<iostream>
using namespace std;
void test(int b){
if(b == 0)
throw 1;
if(b == 1)
throw 1.0;
if(b == 2)
throw 'e';
cout << "Value of b is: " << b << endl;
}
int main(){
try{
test(3);
test(4);
test(0);
test(1);
}
catch(int c) {
cout<<"Integer exception";
}
catch(double a) {
cout<<"Double exception";
}
catch(char e) {
cout<<"Character exception";
}
return 0;
}
| 15.857143
| 67
| 0.499099
|
B33pl0p
|
4c08256d2e2424a9689dd94e7348d870aea893d2
| 5,956
|
cpp
|
C++
|
src/aimp_dotnet/SDK/AimpConfig.cpp
|
F8ER/aimp_dotnet
|
2e93b9eda44cd77337b45f008d29eec574774064
|
[
"Apache-2.0"
] | null | null | null |
src/aimp_dotnet/SDK/AimpConfig.cpp
|
F8ER/aimp_dotnet
|
2e93b9eda44cd77337b45f008d29eec574774064
|
[
"Apache-2.0"
] | null | null | null |
src/aimp_dotnet/SDK/AimpConfig.cpp
|
F8ER/aimp_dotnet
|
2e93b9eda44cd77337b45f008d29eec574774064
|
[
"Apache-2.0"
] | null | null | null |
// ----------------------------------------------------
// AIMP DotNet SDK
// Copyright (c) 2014 - 2020 Evgeniy Bogdan
// https://github.com/martin211/aimp_dotnet
// Mail: mail4evgeniy@gmail.com
// ----------------------------------------------------
#include "Stdafx.h"
#include "AimpConfig.h"
using namespace AIMP::SDK;
AimpConfig::AimpConfig(IAIMPConfig* aimpPlayList) : AimpObject(aimpPlayList) {
}
ActionResult AimpConfig::Delete(String^ keyPath) {
IAIMPString* str = nullptr;
auto result = ActionResultType::Fail;
try {
str = AimpConverter::ToAimpString(keyPath);
result = CheckResult(InternalAimpObject->Delete(str));
}
finally {
if (str != nullptr) {
str->Release();
str = nullptr;
}
}
return gcnew AimpActionResult(result);
}
FloatResult AimpConfig::GetValueAsFloat(String^ keyPath) {
IAIMPString* str = nullptr;
double val = 0;
auto result = ActionResultType::Fail;
try {
str = AimpConverter::ToAimpString(keyPath);
InternalAimpObject->GetValueAsFloat(str, &val);
}
finally {
if (str != nullptr) {
str->Release();
str = nullptr;
}
}
return gcnew AimpActionResult<float>(result, val);
}
IntResult AimpConfig::GetValueAsInt32(String^ keyPath) {
IAIMPString* str = nullptr;
int val = 0;
auto result = ActionResultType::Fail;
try {
str = AimpConverter::ToAimpString(keyPath);
InternalAimpObject->GetValueAsInt32(str, &val);
}
finally {
if (str != nullptr) {
str->Release();
str = nullptr;
}
}
return gcnew AimpActionResult<int>(result, val);
}
Int64Result AimpConfig::GetValueAsInt64(String^ keyPath) {
IAIMPString* str = nullptr;
Int64 val = 0;
auto result = ActionResultType::Fail;
try {
str = AimpConverter::ToAimpString(keyPath);
InternalAimpObject->GetValueAsInt64(str, &val);
}
finally {
if (str != nullptr) {
str->Release();
str = nullptr;
}
}
return gcnew AimpActionResult<long long>(result, val);
}
StreamResult AimpConfig::GetValueAsStream(String^ keyPath) {
IAIMPString* str = nullptr;
IAIMPStream* stream = nullptr;
auto result = ActionResultType::Fail;
try {
str = AimpConverter::ToAimpString(keyPath);
result = CheckResult(InternalAimpObject->GetValueAsStream(str, &stream));
}
finally {
if (str != nullptr) {
str->Release();
str = nullptr;
}
}
return gcnew AimpActionResult<IAimpStream^>(result, gcnew AimpStream(stream));
}
StringResult AimpConfig::GetValueAsString(String^ keyPath) {
IAIMPString* str = nullptr;
IAIMPString* val = nullptr;
auto result = ActionResultType::Fail;
try {
str = AimpConverter::ToAimpString(keyPath);
result = CheckResult(InternalAimpObject->GetValueAsString(str, &val));
}
finally {
// TODO Release val?
if (str != nullptr) {
str->Release();
str = nullptr;
}
}
return gcnew AimpActionResult<String^>(result, gcnew String(val->GetData()));
}
ActionResult AimpConfig::SetValueAsFloat(String^ keyPath, float value) {
IAIMPString* str = nullptr;
auto result = ActionResultType::Fail;
try {
str = AimpConverter::ToAimpString(keyPath);
result = CheckResult(InternalAimpObject->SetValueAsFloat(str, value));
}
finally {
if (str != nullptr) {
str->Release();
str = nullptr;
}
}
return ACTION_RESULT(result)
}
ActionResult AimpConfig::SetValueAsInt32(String^ keyPath, int value) {
IAIMPString* str = nullptr;
auto result = ActionResultType::Fail;
try {
str = AimpConverter::ToAimpString(keyPath);
result = CheckResult(InternalAimpObject->SetValueAsInt32(str, value));
}
finally {
if (str != nullptr) {
str->Release();
str = nullptr;
}
}
return ACTION_RESULT(result)
}
ActionResult AimpConfig::SetValueAsInt64(String^ keyPath, Int64 value) {
IAIMPString* str = nullptr;
auto result = ActionResultType::Fail;
try {
str = AimpConverter::ToAimpString(keyPath);
result = CheckResult(InternalAimpObject->SetValueAsInt64(str, value));
}
finally {
if (str != nullptr) {
str->Release();
str = nullptr;
}
}
return ACTION_RESULT(result)
}
ActionResult AimpConfig::SetValueAsStream(String^ keyPath, IAimpStream^ stream) {
IAIMPString* str = nullptr;
auto result = ActionResultType::Fail;
try {
str = AimpConverter::ToAimpString(keyPath);
result = CheckResult(
InternalAimpObject->SetValueAsStream(str, static_cast<AimpStream^>(stream)->InternalAimpObject));
}
finally {
if (str != nullptr) {
str->Release();
str = nullptr;
}
}
return ACTION_RESULT(result);
}
ActionResult AimpConfig::SetValueAsString(String^ keyPath, String^ value) {
IAIMPString* str = nullptr;
IAIMPString* val = nullptr;
auto result = ActionResultType::Fail;
try {
str = AimpConverter::ToAimpString(keyPath);
val = AimpConverter::ToAimpString(value);
result = CheckResult(InternalAimpObject->SetValueAsString(str, val));
}
finally {
if (str != nullptr) {
str->Release();
str = nullptr;
}
if (val != nullptr) {
val->Release();
val = nullptr;
}
}
return ACTION_RESULT(result);
}
| 26.237885
| 110
| 0.572532
|
F8ER
|
4c083bc9f39e238b979f53e2af70146f24b2a948
| 5,007
|
cpp
|
C++
|
_more/case/c4rv/_more/rvcpp/riscv.cpp
|
al2698/sp
|
fceabadef49ffe6ed25dfef38e3dc418f309e128
|
[
"MIT"
] | null | null | null |
_more/case/c4rv/_more/rvcpp/riscv.cpp
|
al2698/sp
|
fceabadef49ffe6ed25dfef38e3dc418f309e128
|
[
"MIT"
] | null | null | null |
_more/case/c4rv/_more/rvcpp/riscv.cpp
|
al2698/sp
|
fceabadef49ffe6ed25dfef38e3dc418f309e128
|
[
"MIT"
] | null | null | null |
#include "riscv.hpp"
//================================
Op opList[] = {
// 運算指令
{Sll, "sll", 'R',0x33,0x1,0x0},
{Slli, "slli", 'I',0x13,0x1,0x0},
{Srl, "srl", 'R',0x33,0x5,0x0},
{Srli, "srli", 'I',0x13,0x5,0x0},
{Sra, "sra", 'R',0x33,0x5,0x20},
{Srai, "srai", 'I',0x13,0x5,0x20},
{Add, "add", 'R',0x33,0x0,0x0},
{Addi, "addi", 'I',0x13,0x0,0x0},
{Sub, "sub", 'R',0x33,0x0,0x20},
{Xor, "xor", 'R',0x33,0x4},
{Xori, "xori", 'I',0x13,0x4},
{Or, "or", 'R',0x33,0x6},
{Ori, "ori", 'I',0x13,0x6},
{And, "and", 'R',0x33,0x7},
{Andi, "andi", 'I',0x13,0x7},
// 比較設定
{Slt, "slt", 'R',0x33,0x2},
{Slti, "slti", 'I',0x13,0x2},
{Sltu, "sltu", 'R',0x33,0x3},
{Sltiu, "sltiu", 'I',0x13,0x3},
// 跳躍指令
{Beq, "beq", 'B',0x63,0x0},
{Bne, "bne", 'B',0x63,0x1},
{Blt, "blt", 'B',0x63,0x4},
{Bge, "bge", 'B',0x63,0x5},
{Bltu, "bltu", 'B',0x63,0x6},
{Bgeu, "bgeu", 'B',0x63,0x7},
{Jal, "jal", 'J',0x6F},
{Jalr, "jalr", 'I',0x67},
// 載入儲存
{Lb, "lb", 'I',0x03,0x0},
{Lh, "lh", 'I',0x03,0x1},
{Lw, "lw", 'I',0x03,0x2},
{Lbu, "lbu", 'I',0x03,0x4},
{Lhu, "lhu", 'I',0x03,0x5},
{Sb, "sb", 'S',0x23,0x0},
{Sh, "sh", 'S',0x23,0x1},
{Sw, "sw", 'S',0x23,0x2},
// 控制暫存器指令
{Csrrw, "csrrw", 'I',0x73,0x1},
{Csrrs, "csrrs", 'I',0x73,0x2},
{Csrrc, "csrrc", 'I',0x73,0x3},
{Csrrwi, "csrrwi", 'I',0x73,0x5}, // csrrXi 格式是把 rs1 改為 uimm
{Csrrsi, "csrrsi", 'I',0x73,0x6},
{Csrrci, "csrrci", 'I',0x73,0x7},
// 特殊指令
{Lui, "lui", 'U',0x37},
{Auipc, "auipc", 'U',0x17},
{Fence, "fence", 'I',0x0F,0x0},
{Fencei, "fence.i", 'I',0x0F,0x1},
{Ecall, "ecall", 'I',0x73},
{Ebreak, "ebreak", 'I',0x73}
};
map<string, Op*> opMap;
map<enum Id, Op*> opIdMap;
map<string, int> rMap {
// 暫存器 x0-x31
{"x0",0},{"x1",1},{"x2",2},{"x3",3},{"x4",4},{"x5",5},{"x6",6},{"x7",7},
{"x8",8}, {"x9",9}, {"x10",10}, {"x11",11},{"x12",12}, {"x13",13}, {"x14",14}, {"x15",15},
{"x16",16}, {"x17",17}, {"x18",18}, {"x19",19},{"x20",20}, {"x21",21}, {"x22",22}, {"x23",23},
{"x24",24}, {"x25",25}, {"x26",26}, {"x27",27},{"x28",28}, {"x29",29}, {"x30",30}, {"x31",31},
// 暫存器別名
{"zero",0},{"ra",1},{"sp",2},{"gp",3},{"tp",4},{"t0",5},{"t1",6},{"t2",7},
{"s0",8}, {"fp",8}, {"s1",9}, {"a0",10}, {"a1",11},{"a2",12}, {"a3",13}, {"a4",14}, {"a5",15},
{"a6",16}, {"a7",17}, {"s2",18}, {"s3",19},{"s4",20}, {"s5",21}, {"s6",22}, {"s7",23},
{"s8",24}, {"s9",25}, {"s10",26}, {"s11",27},{"t3",28}, {"t4",29}, {"t5",30}, {"t6",31}
};
map<string, int> csrMap {
// 特權暫存器
{"ustatus",0x0},{"uie",0x4},{"utvec",0x5},{"uscratch",0x40},{"uepc",0x41},{"ucause",0x42},{"ubadaddr",0x43},
{"uip",0x44},{"fflag",0x1},{"frm",0x2},{"fcsr",0x3},
{"cycle",0xC00},{"time",0xC01},{"instret",0xC02},
{"hpmcounter3",0xC03},{"hpmcounter4",0xC04},/* ...*/ {"hpmcounter31",0xC1F},
{"cycleh",0xC80},{"timeh",0xC81},{"instreth",0xC82},
{"hpmcounter3h",0xC83},{"hpmcounter4h",0xC84},/*...*/{"hpmcounter31h",0xC9F},
{"sstatus",0x100},{"sedeleg",0x102},{"sideleg",0x103},{"sie",0x104},{"stvec",0x105},
{"sscratch",0x140},{"sepc",0x141},{"scause",0x142},{"sbadaddr",0x143},{"sip",0x144},{"sptbr",0x180},
{"hstatus",0x200},{"hedeleg",0x202},{"hideleg",0x203},{"hie",0x204},{"htvec",0x205},
{"hscratch",0x240},{"hepc",0x241},{"hcause",0x242},{"hbadaddr",0x243},{"hip",0x244},
{"mvendorid",0xF11},{"marchid",0xF12},{"mimpid",0xF13},{"mhartid",0xF14},
{"mstatus",0x300},{"misa",0x301},{"medeleg",0x302},{"mideleg",0x303},{"mie",0x304},{"mtvec",0x305},
{"mscratch",0x340},{"mepc",0x341},{"mcause",0x342},{"mbadaddr",0x343},{"mip",0x344},
{"mbase",0x380},{"mbound",0x381},{"mibase",0x382},{"mibound",0x383},{"mdbase",0x384},{"mdbound",0x385},
{"mcycle",0xB00},{"minstret",0xB02},{"mhpmcounter3",0xB03},{"mhpmcounter4",0xB04},/*...*/{"mhpmcounter31",0xB1F},
{"mcycleh",0xB80},{"minstreth",0xB82},{"mhpmcounter3h",0xB83},{"mhpmcounter4h",0xB84},/*...*/{"mhpmcounter31h",0xB9F},
{"mucounteren",0x320},{"mscounteren",0x321},{"mhcounteren",0x322},{"mhpmevent3",0x323},{"mhpmevent4",0x324},/*...*/{"mhpmevent31",0x33F},
{"tselect",0x7A0},{"tdata1",0x7A1},{"tdata2",0x7A2},{"tdata3",0x7A3},
{"dcsr",0x7B0},{"dpc",0x7B1},{"dscratch",0x7B2},
};
map<int, string> i2csrMap {}; // 透過代號取出 csr 名稱的 map
Op *opFind(char *name) {
string op0(name);
map<string, Op*>::const_iterator pos = opMap.find(op0);
if (pos == opMap.end()) {
printf("pos==opMap.end()\n");
return NULL;
}
return pos->second;
}
int rFind(char *name) { return mapFind(&rMap, name); }
int csrFind(char *name) { return mapFind(&csrMap, name); }
const char *csrName(uint32_t csr) {
map<int, string>::const_iterator pos = i2csrMap.find(csr);
if (pos == i2csrMap.end()) return NULL;
return pos->second.c_str();
}
void riscv_init() {
// printf("riscv_init() start!\n");
for (int i=Sll; i<sizeof(opList)/sizeof(Op); i++) {
Op *op = &opList[i];
// printf("i=%d op:id=%d name=%s\n", i, op->id, op->name.c_str());
opMap[op->name] = op;
opIdMap[op->id] = op;
}
// printf("riscv_init() 2\n");
mapReverse(&csrMap, &i2csrMap);
// printf("riscv_init() complete!\n");
}
| 37.931818
| 139
| 0.551827
|
al2698
|
4c157c40118fd1421c7d76190ae98fe9127e04a7
| 28,153
|
cpp
|
C++
|
Lorem Ipsum/Chinchetario.cpp
|
NicoPast/P2
|
2f68dd4d254b9d3ae096e25b0cfe2e780e9922fc
|
[
"MIT"
] | null | null | null |
Lorem Ipsum/Chinchetario.cpp
|
NicoPast/P2
|
2f68dd4d254b9d3ae096e25b0cfe2e780e9922fc
|
[
"MIT"
] | null | null | null |
Lorem Ipsum/Chinchetario.cpp
|
NicoPast/P2
|
2f68dd4d254b9d3ae096e25b0cfe2e780e9922fc
|
[
"MIT"
] | 1
|
2021-09-30T09:56:46.000Z
|
2021-09-30T09:56:46.000Z
|
#include "Chinchetario.h"
#include "LoremIpsum.h"
#include "DragDrop.h"
#include "ScrollerLimited.h"
#include "Rectangle.h"
#include "Camera.h"
#include "CameraController.h"
#include "Sprite.h"
#include "Line.h"
#include "ClueCallbacks.h"
Chinchetario::Chinchetario(LoremIpsum* game) : State(game)
{
camera_->setPos(0, 0);
camera_->setWidth(game_->getGame()->getWindowWidth());
camera_->setHeight(game_->getGame()->getWindowHeight());
camera_->setLeftMargin(0); camera_->setRightMargin(0);
Texture* bckgrndTexture = game_->getGame()->getTextureMngr()->getTexture(Resources::CorkBG);
camera_->setLimitX(bckgrndTexture->getWidth());
camera_->setLimitY(bckgrndTexture->getHeight());
mng_ = entityManager_->addEntity();
background_ = entityManager_->addEntity();
background_->addComponent<Transform>(0, 0, 2560, 1440);
background_->addComponent<Sprite>(bckgrndTexture);
createPanels();
updateClues();
auto goBackButton = entityManager_->addEntity(Layers::LastLayer);
goBackButton->addComponent<Transform>(0, 0, 64, 64);
//goBackButton->addComponent<Rectangle>(SDL_Color{ COLOR(0xffccccff) });
auto sp = goBackButton->addComponent<Sprite>(game_->getGame()->getTextureMngr()->getTexture(Resources::GoBackButton));
goBackButton->setUI(true);
auto b = goBackButton->addComponent<ButtonOneParametter<Chinchetario*>>(std::function<void(Chinchetario*)>([](Chinchetario* ch) {ch->close(); }), this);
b->setMouseOverCallback([sp]() {sp->setTint(111, 111, 111); });
b->setMouseOutCallback([sp]() {sp->setTint(255, 255, 255); });
showPopUpMessage("En el panel inferior se guardan las pistas que has recogido. Arr\u00e1stralas al corcho y une hilos entre las chinchetas seg\u00fan tus conclusiones para avanzar en el caso");
}
void Chinchetario::update()
{
State::update();
if (game_->getStoryManager()->getInvestigableChanges()) {
updateClues();
}
InputHandler* ih = InputHandler::instance();
//if (ih->mouseButtonEvent() && ih->getMouseButtonState(InputHandler::LEFT) && ih->getMousePos().getY() < bottomPanel_->getComponent<Transform>(ecs::Transform)->getPos().getY())
}
void Chinchetario::updateClues() {
for (int i = 0; i < game_->getStoryManager()->getPlayerCentralClues().size(); i++) {
auto it = find(playerClues_.begin(), playerClues_.end(), game_->getStoryManager()->getPlayerCentralClues()[i]);
if (it == playerClues_.end()) {//Si no encuentra esa pista en el vector, la añade
playerClues_.push_back(game_->getStoryManager()->getPlayerCentralClues()[i]);
createClues(game_->getStoryManager()->getPlayerCentralClues()[i], playerClues_.size() - 1);
showBottomPanel();
}
}
for (int i = 0; i < game_->getStoryManager()->getPlayerClues().size(); i++) {
auto it = find(playerClues_.begin(), playerClues_.end(), game_->getStoryManager()->getPlayerClues()[i]);
if (it == playerClues_.end()) {//Si no encuentra esa pista en el vector, la añade
playerClues_.push_back(game_->getStoryManager()->getPlayerClues()[i]);
createClues(game_->getStoryManager()->getPlayerClues()[i], playerClues_.size()-1);
showBottomPanel();
}
}
relocateClues();
game_->getStoryManager()->setInvestigableChanges(false);
}
void Chinchetario::removeClue(Resources::ClueID id) {
int i = 0; bool found = false;
while (i < playerClues_.size() && !found) {
Clue* clue = playerClues_[i];
if (clue->id_ == id) {
playerClues_.erase(playerClues_.begin() + i);
clue->entity_->setActive(false);
if (clue->id_ > Resources::lastClueID) {
Transform* tratra = GETCMP2(clue->entity_, Transform);
auto tratravector = tratra->getChildren();
for (auto p : static_cast<CentralClue*>(clue)->pins_) {
Pin* pin = p->getComponent<Pin>(ecs::Drag);
pin->eliminateLine();
}
tratra->setActiveChildren(false);
}
found = true;
}
else i++;
}
}
void Chinchetario::render()
{
State::render();
}
//Determina si es el objeto con componente Drag m�s arriba en la jerarqu�a de capas
bool Chinchetario::isHigherDragable(Drag* d) {
bool higher;
if (draggedItem_ == nullptr) { //Si no hay ninguno agarrado, este se guarda
higher = true;
draggedItem_ = d;
}
else {
//Se aceptan ideas a los nombres de estas variables
int dl = d->getEntity()->getLayer();
int dil = draggedItem_->getEntity()->getLayer();
int dli = d->getEntity()->getLayerIndex();
int dili = draggedItem_->getEntity()->getLayerIndex();
higher = (dl > dil || (dl == dil && dli > dili)); //Si est� en una capa superior o en la misma pero con �ndice mayor
if (higher) {
entityManager_->getEntity(dil, dili)->getComponent<Drag>(ecs::Drag)->deactivateDrag();
draggedItem_ = d;
}
}
return higher;
}
void Chinchetario::resetWrongClue(CentralClue* cc) {
int i = 0;
while (cc->entity_ != playerClues_[i]->entity_)
{
i++;
}
scroll_->addItem(cc->entity_->getComponent<Transform>(ecs::Transform),i);
cc->isEvent_ = false;
cc->isCorrect_ = false;
cc->actualDescription_ = " ";
game_->getStoryManager()->setEventChanges(true);
if (ClueCallbacks::centralClueCBs.find(cc->id_) != ClueCallbacks::centralClueCBs.end())
{
ClueCallbacks::centralClueCBs[cc->id_]();
}
cc->placed_ = false;
Transform* cTR = GETCMP2(cc->entity_, Transform);
cTR->setActiveChildren(false);
//resetDraggedItem();
//Mira todos sus hijos y actualiza la l�nea, cambiar si va a haber otros tipos de hijos diferentes
auto chldrn = cTR->getChildren();
for (Transform* t : chldrn) {
Pin* p = static_cast<Pin*>(t->getEntity()->getComponent<Drag>(ecs::Drag));
Line* l = p->getLine();
if (l != nullptr) {
Vector2D newPos = { t->getPos().getX() + t->getW() / 2, t->getPos().getY() + t->getH() / 2 };
l->moveTo(newPos);
l->eraseLine();
auto grchldrn = t->getChildren()[0];
static_cast<DragDrop*>(GETCMP2(grchldrn->getEntity(), Drag))->detachLine();
grchldrn->eliminateParent();
int i = 0;
Entity* c = grchldrn->getEntity();
while (c != playerClues_[i]->entity_)
{
i++;
}
scroll_->addItem(grchldrn, i);
playerClues_[i]->placed_ = false;
p->eliminateLine(); p->resetActualLink();
}
}
relocateClues();
}
void Chinchetario::clueDropped(Entity* e)
{
int i = 0;
while (e != playerClues_[i]->entity_)
{
i++;
}
Transform* parent = GETCMP2(playerClues_[i]->entity_, Transform)->getParent();
if (parent)
return; //más vale return bien puesto que error de ejecución. Cleon, si lees esto, que sepas que nos merecemos buena nota igualmente besitos <3
bool b = !checkClueInBottomPanel(e);
if (b && !playerClues_[i]->placed_) {
scroll_->removeItem(e->getComponent<Transform>(ecs::Transform), i);
SDLGame::instance()->getAudioMngr()->playChannel(Resources::ClueDropped, 0, 1);
}
else if (!b && playerClues_[i]->placed_) {
scroll_->addItem(e->getComponent<Transform>(ecs::Transform), i);
//Si tiene un evento, lo resetea
if (playerClues_[i]->id_ > Resources::lastClueID) {
CentralClue* cc = static_cast<CentralClue*>(playerClues_[i]);
cc->isEvent_ = false;
cc->isCorrect_ = false;
cc->actualDescription_ = " ";
game_->getStoryManager()->setEventChanges(true);
if (ClueCallbacks::centralClueCBs.find(cc->id_) != ClueCallbacks::centralClueCBs.end())
{
ClueCallbacks::centralClueCBs[cc->id_]();
}
}
}
playerClues_[i]->placed_ = b;
relocateClues();
Transform* cTR = GETCMP2(playerClues_[i]->entity_, Transform);
cTR->setActiveChildren(b);
if (playerClues_[i]->entity_->isUI())//wtf donde se cambia el ui arriba
{
Transform* tr = playerClues_[i]->entity_->getComponent<Transform>(ecs::Transform);
tr->setPos(tr->getPos() + camera_->getPos());
}
resetDraggedItem();
//Mira todos sus hijos y actualiza la l�nea, cambiar si va a haber otros tipos de hijos diferentes
auto chldrn = cTR->getChildren();
for (Transform* t : chldrn) {
Pin* p = static_cast<Pin*>(t->getEntity()->getComponent<Drag>(ecs::Drag));
Line* l = p->getLine();
if (l != nullptr) {
Vector2D newPos = { t->getPos().getX() + t->getW() / 2, t->getPos().getY() + t->getH() / 2 };
if (p->getState())
{
l->moveTo(newPos);
}
else l->setIniFin(newPos);
if (!b) {
l->eraseLine();
if (t->getChildren().size() > 0) {
auto grchldrn = t->getChildren()[0];
static_cast<DragDrop*>(GETCMP2(grchldrn->getEntity(), Drag))->detachLine();
grchldrn->eliminateParent();
int i = 0;
Entity* c = grchldrn->getEntity();
while (c != playerClues_[i]->entity_)
{
i++;
}
scroll_->addItem(grchldrn, i);
playerClues_[i]->placed_ = b;
}
}
}
}
//if (!clues[i]->placed_)
// clues[i]->entity_->setLayer(Layers::LastLayer);
}
void Chinchetario::pinDropped(Entity* e) {
InputHandler* ih = InputHandler::instance();
Vector2D mpos = ih->getMousePos();
SDL_Point point = { (int)mpos.getX(),(int)mpos.getY() };
Transform* CCtr = GETCMP2(e, Transform);
Drag* d = GETCMP2(e, Drag);
Pin* p = static_cast<Pin*>(d);
Clue* linked = p->getActualLink();
CentralClue* cc = p->getCentralClue();
Transform* tr;
SDL_Rect rect;
Entity* prevE = nullptr;
Transform* prevTR = nullptr;
bool was = false;
//Si estaba conectada a otra pista, corta la union
if (p->getState()) {
prevE = p->getActualLink()->entity_;
prevTR = GETCMP2(prevE, Transform);
if (prevTR->getParent() != nullptr)
prevTR->eliminateParent();
p->setState(false);
was = true;
}
DragDrop* lastCorrectDD = nullptr;
for (Clue* c : playerClues_) {
if (c->placed_ && c->id_ < Resources::ClueID::lastClueID) { //Si est� en el tablero y no es principal
tr = c->entity_->getComponent<Transform>(ecs::Transform);
Vector2D pos = tr->getPos() - camera_->getPos();
rect = SDL_Rect RECT(pos.getX(), pos.getY(), tr->getW(), tr->getH());
DragDrop* dd = static_cast<DragDrop*>(c->entity_->getComponent<Drag>(ecs::Drag));
if (SDL_PointInRect(&point, &rect) && isHigherDragable(dd)) { //Si hace clic en ella y es la que est� m�s adelante
if (lastCorrectDD != nullptr) { //Si la anterior en entrar aqu� era del tipo correcto, deshace
lastCorrectDD->detachLine();
lastCorrectDD->getEntity()->getComponent<Transform>(ecs::Transform)->eliminateParent();
tr->eliminateParent();
p->resetActualLink();
}
if (p->isSameType(c->type_)) { //Si es del tipo correcto
if (p->getActualLink() != nullptr && p->getActualLink()->id_ == c->id_) { //Si es LA MISMA pista [Feisimo]
if (was) {
prevTR->setParent(CCtr);
p->setState(true);
}
}
else {
if (tr->getParent() != nullptr) {//si la pista ya está conectada a otra coisa
//borra esa linea
Pin* pf = static_cast<Pin*>(tr->getParent()->getEntity()->getComponent<Drag>(ecs::Drag));
pf->eliminateLine();
pf->resetActualLink();
tr->eliminateParent();
//resetea la información de evento
CentralClue* that = pf->getCentralClue();
that->isEvent_ = false; that->isCorrect_ = false;
that->actualDescription_ = " ";
Rectangle* cRec = GETCMP2(that->entity_, Rectangle);
if(cRec)
cRec->setBorder(SDL_Color{ COLOR(0x01010100) });
game_->getStoryManager()->setEventChanges(true);
if (ClueCallbacks::centralClueCBs.find(cc->id_) != ClueCallbacks::centralClueCBs.end())
{
ClueCallbacks::centralClueCBs[cc->id_]();
}
}
//Feisimo, lo se
if (was) { //Si estaba enganchado a algo lo desengancha
if (prevTR->getParent() != nullptr)
prevTR->eliminateParent();
p->setState(false);
static_cast<DragDrop*>(prevE->getComponent<Drag>(ecs::Drag))->detachLine();
if (cc->isEvent_) {
cc->isEvent_ = false; cc->isCorrect_ = false;
cc->actualDescription_ = " ";
changeText(cc);
game_->getStoryManager()->setEventChanges(true);
if (ClueCallbacks::centralClueCBs.find(cc->id_) != ClueCallbacks::centralClueCBs.end())
{
ClueCallbacks::centralClueCBs[cc->id_]();
}
}
}
p->setActualLink(c);
tr->setParent(CCtr);
p->associateLine(static_cast<DragDrop*>(c->entity_->getComponent<Drag>(ecs::Drag)));
lastCorrectDD = dd;
checkEvent(cc);
SDLGame::instance()->getAudioMngr()->playChannel(Resources::PinDropped, 0, 1);
}
}
else lastCorrectDD = nullptr;
}
}
}
if (!p->getState()) { //Si se queda sin enganchar, borra la l�nea
p->eliminateLine();
p->resetActualLink();
if (prevE != nullptr) {
static_cast<DragDrop*>(prevE->getComponent<Drag>(ecs::Drag))->detachLine();
if (cc->isEvent_) {
cc->isEvent_ = false; cc->actualDescription_ = " "; cc->isCorrect_ = false;
changeText(cc);
game_->getStoryManager()->setEventChanges(true);
}
}
}
resetDraggedItem();
}
void Chinchetario::relocateClues()
{
size_t size = playerClues_.size();
int numPlaced = 0;
for (size_t i = 0; i < size; i++)
{
//(clueSize + (2 * clueSize) * i, game_->getGame()->getWindowHeight() - (bottomPanelH / 2 + clueSize / 2));
if (playerClues_[i]->placed_)
{
numPlaced++;
//clues[i]->entity_->getComponent(ecs)
playerClues_[i]->entity_->setUI(false);
}
else
{
Transform* t = playerClues_[i]->entity_->getComponent<Transform>(ecs::Transform);
t->setPos(t->getW() + (2 * t->getW()) * (i - numPlaced), game_->getGame()->getWindowHeight() - (GETCMP2(bottomPanel_, Transform)->getH() / 2 + t->getH() / 2));
playerClues_[i]->entity_->setUI(true);
}
//GETCMP2()
}
if (numPlaced == playerClues_.size())
{
hideBottomPanel();
}
}
void Chinchetario::toggleBottomPanel()
{
//Si está abajo, es que tiene que subir. El panel se oculta con un tween que lo pone en WindowH
bottomPanel_->getComponent<Transform>(ecs::Transform)->getPos().getY() < game_->getGame()->getWindowHeight()-30 ? hideBottomPanel() : showBottomPanel();
};
//true si est� en el panel de abajo
bool Chinchetario::checkClueInBottomPanel(Entity* e)
{
//Entity* e = clueEntities_[i];
Transform* clueTr = GETCMP2(e, Transform);
Transform* pannelTr = GETCMP2(bottomPanel_, Transform);
SDL_Rect r{ pannelTr->getPos().getX(), pannelTr->getPos().getY(), pannelTr->getW() + clueTr->getW(), pannelTr->getH() + clueTr->getH() };
SDL_Point p{ clueTr->getPos().getX() + clueTr->getW(), clueTr->getPos().getY() + clueTr->getH() };
p.x -= camera_->getPosX();
p.y -= camera_->getPosY();
return (bottomPanel_->getActive() && (SDL_PointInRect(&p, &r)));
}
void Chinchetario::setUnplacedClues(bool b)
{
for (auto& c : playerClues_)
{
if (!c->placed_)
{
c->entity_->setActive(b);
}
}
}
void Chinchetario::createPanels() {
bottomPanel_ = entityManager_->addEntity(Layers::CharacterLayer);
rightPanel_ = entityManager_->addEntity(Layers::LastLayer);
double rightPanelW = game_->getGame()->getWindowWidth() / 4;
double rightPanelH = game_->getGame()->getWindowHeight();
Transform* rpTr = rightPanel_->addComponent<Transform>(game_->getGame()->getWindowWidth(), 0, rightPanelW, rightPanelH);
//rightPanel_->addComponent<Rectangle>(SDL_Color{ COLOR(0x0085cf88) });
rightPanel_->addComponent<Sprite>(game_->getGame()->getTextureMngr()->getTexture(Resources::VerticalUIPanel));
auto tween = rightPanel_->addComponent<Tween>(game_->getGame()->getWindowWidth() - rightPanelW, 0.0, 15, rightPanelW, rightPanelH);
tween->GoToB();
tween->setFunc([](Entity* s) { static_cast<Chinchetario*>(s->getState())->showText(); }, rightPanel_);
rightPanel_->setUI(true);
textTitle_ = rightPanel_->addComponent<Text>("", rpTr->getPos()+ Vector2D(-rightPanelW+4, 2), rpTr->getW(), Resources::RobotoTest24, 0);
textTitle_->setSoundActive(false);
cluePhoto_ = entityManager_->addEntity(Layers::LastLayer);
Transform* phTr = cluePhoto_->addComponent<Transform>(0,0, rightPanelW -12*2, 72*4);
phTr->setParent(rpTr);
phTr->setPos(12, 12.0 + textTitle_->getCharH());
cluePhoto_->addComponent<Sprite>(game_->getGame()->getTextureMngr()->getTexture(Resources::clueTemplate));
cluePhoto_->setUI(true);
textDescription_ = rightPanel_->addComponent<Text>("", rpTr->getPos() + Vector2D(-rightPanelW + 5, 80.0 * 4.0), rpTr->getW()-15, Resources::RobotoTest24, 0);
textDescription_->setScroll(textDescription_->getPos().getX(), textDescription_->getPos().getY(), textDescription_->getMaxW(), rightPanelH - (100.0 * 4.0));
textDescription_->setSoundActive(false);
Entity* rightPanelTopImage = entityManager_->addEntity(Layers::LastLayer);
rightPanelTopImage->setUI(true);
rightPanelTopImage->addComponent<Transform>(game_->getGame()->getWindowWidth()-16, 0, rightPanelW, rightPanelH)->setParent(rpTr);
rightPanelTopImage->addComponent<Sprite>()->setTexture(Resources::VerticalUIPanel2);
double bottomPanelW = game_->getGame()->getWindowWidth() - rightPanelW;
bottomPanelH_ = game_->getGame()->getWindowHeight() / 5;
Transform* bpTr = bottomPanel_->addComponent<Transform>(0.0, game_->getGame()->getWindowHeight()-30, bottomPanelW, bottomPanelH_);
//bottomPanel_->addComponent<Rectangle>(SDL_Color{ COLOR(0x00cf0088) });
bottomPanel_->addComponent<Sprite>(game_->getGame()->getTextureMngr()->getTexture(Resources::HorizontalUIPanel));
Chinchetario* ch = this;
bottomPanel_->addComponent<Tween>(0, game_->getGame()->getWindowHeight() - bottomPanelH_, 15, bottomPanelW, bottomPanelH_)->setFunc([ch](Entity* e) {ch->setUnplacedClues(true); }, bottomPanel_);
bottomPanel_->setUI(true);
GETCMP2(bottomPanel_, Tween)->GoToA();
scroll_ = mng_->addComponent<ScrollerLimited>(0, bottomPanelW);
cursor_ = entityManager_->addEntity();
cursor_->addComponent<CameraController>(camera_);
Entity* bottomPanelTopImage = entityManager_->addEntity(Layers::LastLayer);
bottomPanelTopImage->setUI(true);
bottomPanelTopImage->addComponent<Transform>(0.0, game_->getGame()->getWindowHeight()-30, bottomPanelW, bottomPanelH_)->setParent(bpTr);
bottomPanelTopImage->addComponent<Sprite>()->setTexture(Resources::HorizontalUIPanel2);
auto hidePannelButton = entityManager_->addEntity(Layers::LastLayer);
hidePannelButton->addComponent<Transform>(5, game_->getGame()->getWindowHeight() - 46 -bottomPanelH_, 95*2, 23);
Transform* tr = GETCMP2(hidePannelButton, Transform);
tr->setParent(GETCMP2(bottomPanel_, Transform));
tr->setPos({30,12});
//hidePannelButton->addComponent<Sprite>(buttonSprite);
hidePannelButton->setUI(true);
hidePannelButton->addComponent<ButtonOneParametter<Chinchetario*>>(std::function<void(Chinchetario*)>([tr](Chinchetario* ch)
{
ch->toggleBottomPanel();
if (tr->getRot() == 0)
{
tr->setRot(180);
}
else
{
tr->setRot(0);
}
}), this);
//auto hideRightPannelButton = entityManager_->addEntity(Layers::LastLayer);
//hideRightPannelButton->addComponent<Transform>(5, game_->getGame()->getWindowHeight() - 46 - bottomPanelH_, 92, 46);
//tr = GETCMP2(hideRightPannelButton, Transform);
//tr->setParent(GETCMP2(rightPanel_, Transform));
//tr->setRot(270);
//tr->setPos({ -69, 23 });
//Texture* buttonSprite = game_->getGame()->getTextureMngr()->getTexture(Resources::HideShowButton);
//Sprite * sp = hideRightPannelButton->addComponent<Sprite>(buttonSprite);
//buttonSprite->setPivotPoint({ 46, 23 });
//hideRightPannelButton->setUI(true);
auto b = rightPanelTopImage->addComponent<ButtonOneParametter<Chinchetario*>>(std::function<void(Chinchetario*)>([tr](Chinchetario* ch)
{
if (tr->getRot() == 270)
{
ch->hideRightPanel();
tr->setRot(90);
}
else
{
ch->showRightPanel();
tr->setRot(270);
}
}), this);
b->setOffsets(10, -108, 164, 628);
//b->setMouseOverCallback([sp]() {sp->setTint(111,111,111); });
//b->setMouseOutCallback([sp]() {sp->setTint(255, 255, 255); });
}
void Chinchetario::changeText(Clue* c) {
//showRightPanel();
//Comprueba si es una pista central, y en tal caso, comprueba si tiene formado un evento, para mostrar ese texto en lugar del normal
if (c->id_ > Resources::lastClueID) {
CentralClue* cc = static_cast<CentralClue*>(c);
if (cc->isEvent_) textDescription_->setText(cc->actualDescription_);
else textDescription_->setText(cc->description_);
}
else textDescription_->setText(c->description_);
textTitle_->setText(c->title_);
cluePhoto_->getComponent<Transform>(ecs::Transform)->setPosY(textTitle_->getPos().getY() + (double)textTitle_->getNumLines() * textTitle_->getCharH());
textDescription_->setPos(Vector2D(textDescription_->getPos().getX(), cluePhoto_->getComponent<Transform>(ecs::Transform)->getPos().getY()+
cluePhoto_->getComponent<Transform>(ecs::Transform)->getH()+10));
double rightPanelH = game_->getGame()->getWindowHeight();
textDescription_->setScroll(textDescription_->getPos().getX(), textDescription_->getPos().getY(), textDescription_->getMaxW(), rightPanelH - (100.0 * 4.0));
GETCMP2(cluePhoto_, Sprite)->setTexture(c->spriteId_);
GETCMP2(cluePhoto_, Sprite)->setEnabled(true);
}
void Chinchetario::createClues(Clue* c, int i) {
//A�adimos la informaci�n com�n de las pistas centrales y normales a la entidad
Entity* entity = (c->entity_ = entityManager_->addEntity(Layers::DragDropLayer));
double clueW = 64;
double clueH = 72;
scroll_->addItem(entity->addComponent<Transform>
(clueW + (2 * clueW) * i, game_->getGame()->getWindowHeight() - (bottomPanelH_ / 2 + clueW / 2),
clueW, clueH), i);
string clueTitle = c->title_;
string clueDescription = c->description_;
entity->addComponent<DragDrop>(this, [](Chinchetario* ch, Entity* e) {ch->clueDropped(e); });
entity->addComponent<ButtonOneParametter<Chinchetario*>>(std::function<void(Chinchetario*)>(
[c](Chinchetario* ch) { ch->changeText(c); }), this);
//Si no es una pista central
SDL_Color col = SDL_Color{ COLOR(0xffffffff) };
if (c->id_ < Resources::ClueID::lastClueID) {
switch (c->type_) {
case Resources::ClueType::Object:
col = SDL_Color{ COLOR(0xff0000ff) };
break;
case Resources::ClueType::Person:
col = SDL_Color{ COLOR(0x66ff66ff) };
break;
case Resources::ClueType::Place:
col = SDL_Color{ COLOR(0x0000ffff) };
break;
default:
col = SDL_Color{ COLOR(0xffffffff) };
break;
}
entity->addComponent<Sprite>(game_->getGame()->getTextureMngr()->getTexture(playerClues_[i]->spriteId_))->setBorder(col);
}
//si es una pista central
else {
//Guardamos los datos necesarios de la pista central
Transform* clueTR = GETCMP2(entity, Transform);
double nLinks = static_cast<CentralClue*>(c)->links_.size();
//Las pistas se dibujar�n alrededor de la circunferencia definida por estos datos:
double angle = 360 / (nLinks);
double rd = clueTR->getH() / 2;
//Colocamos cada chincheta en su sitio (cada pista central tendr� x n�mero de chinchetas)
for (int j = 0; j < nLinks; j++) {
Resources::ClueID thisLinkID = static_cast<CentralClue*>(c)->links_[j];
Resources::ClueType thisLinkType = game_->getStoryManager()->getClues().at(thisLinkID)->type_;
double rad = M_PI / 180;
double pinY = rd * cos(rad * (180 + angle * j)); //posici�n en X y en Y LOCALES de la chincheta
double pinX = rd * sin(rad * (180 + angle * j));
Vector2D pinPos = Vector2D(pinX + rd, pinY + rd); //posici�n en X y en Y GLOBALES de la chincheta
pinPos = pinPos + clueTR->getPos();
//Creamos una entidad para la chincheta con la posici�n que acabamos de calcular
Entity* pin = entityManager_->addEntity(Layers::PinLineLayer); //La layer la puse para testear porque es la que est� m�s arriba
pin->setActive(false);
int pinSize = 30; int pinOffset = pinSize / 2;
pin->addComponent<Transform>(pinPos.getX() - pinOffset, pinPos.getY() - pinOffset, pinSize, pinSize)->setParent(clueTR);
//pin->addComponent<Line>(Vector2D{ pinPos.getX() - pinOffset, pinPos.getY() - pinOffset }, Vector2D{ pinPos.getX() - pinOffset, pinPos.getY() - pinOffset }, 4);
switch (thisLinkType)
{
case Resources::ClueType::Object:
col = SDL_Color{ COLOR(0xff0000FF) };
break;
case Resources::ClueType::Person:
col = SDL_Color{ COLOR(0x00ff00FF) };
break;
case Resources::ClueType::Place:
col = SDL_Color{ COLOR(0x0000ffff) };
break;
}
//pin->addComponent<Rectangle>(col);
Texture* tex = game_->getGame()->getTextureMngr()->getTexture(Resources::Chinchetas);
entity->addComponent<Sprite>(game_->getGame()->getTextureMngr()->getTexture(playerClues_[i]->spriteId_))->setBorder(col);
Sprite* sp = pin->addComponent<Sprite>(tex);
sp->setSourceRect({0,tex->getHeight()/5 * thisLinkType, tex->getWidth(), tex->getHeight()/5});
pin->addComponent<Pin>(this, static_cast<CentralClue*>(c), thisLinkID, thisLinkType, [](Chinchetario* ch, Entity* pin) {ch->pinDropped(pin); })->setColor(col);
static_cast<CentralClue*>(c)->pins_.push_back(pin);
}
clueEntities_.push_back(entity);
}
}
void Chinchetario::checkEvent(CentralClue* cc)
{
string eventText = cc->eventDescription_;
Rectangle* cRec = GETCMP2(cc->entity_, Rectangle);
int i = 0; bool b = false;
auto pins = cc->pins_;
//comprueba que la pista principal tenga todas las conexiones hechas para formar un evento
while (i < pins.size() && !b) {
Pin* p = static_cast<Pin*>(pins[i]->getComponent<Drag>(ecs::Drag));
if (p->getState()) i++;
else b = true;
}
//si puede formar un evento,
if (!b) {
int temp = 0;
//Cambia los textos y comprueba si los enlaces son correctos
for (int i = 0; i < pins.size(); i++) {
Pin* p = static_cast<Pin*>(pins[i]->getComponent<Drag>(ecs::Drag));
if (p->isCorrect()) temp++;
Clue* c = p->getActualLink();
string name = c->eventText_;
size_t pos;
switch (c->type_)
{
case Resources::ClueType::Object:
pos = eventText.find('~');
if (pos != -1) {
eventText.erase(pos, 1);
eventText.insert(pos, name);
}
else cout << "\n//-----------------------------// \n"
<<"ATENSION \n Los tipos (ClueType) de las pistas que tienes que enlazar con esta pista principal no cuadran con los caracteres de la frase (@, ~ o $)" <<
"\n Revisa Resources.cpp pls" <<
"//-----------------------------// \n"<<endl;
break;
case Resources::ClueType::Person:
pos = eventText.find('@');
if (pos != -1) {
eventText.erase(pos, 1);
eventText.insert(pos, name);
}
else cout << "//-----------------------------// \n"
<< "ATENSION \n Los tipos (ClueType) de las pistas que tienes que enlazar con esta pista principal no cuadran con los caracteres de la frase (@, ~ o $)" <<
"\n Revisa Resources.cpp pls" <<
"//-----------------------------// \n" << endl;
break;
case Resources::ClueType::Place:
pos = eventText.find('$');
if (pos != -1) {
eventText.erase(pos, 1);
eventText.insert(pos, name);
}
else cout << "//-----------------------------// \n"
<< "ATENSION \n Los tipos (ClueType) de las pistas que tienes que enlazar con esta pista principal no cuadran con los caracteres de la frase (@, ~ o $)" <<
"\n Revisa Resources.cpp pls" <<
"//-----------------------------// \n" << endl;
break;
}
}
//Actualiza los valores dentro de la pista
cc->isEvent_ = true;
cc->isCorrect_ = (temp == pins.size());
cc->actualDescription_ = eventText;
changeText(cc);
SDLGame::instance()->getAudioMngr()->playChannel(Resources::Event, 0, 3);
game_->getStoryManager()->setEventChanges(true);
if (ClueCallbacks::centralClueCBs.find(cc->id_) != ClueCallbacks::centralClueCBs.end())
{
ClueCallbacks::centralClueCBs[cc->id_]();
}
}
}
void Chinchetario::close() {
game_->getStateMachine()->PlayGame();
}
| 39.764124
| 196
| 0.657195
|
NicoPast
|
4c15c54083c0cc6a52bdf8de3b0b23d465c448d3
| 3,004
|
hpp
|
C++
|
include/gladys/point.hpp
|
PBechon/gladys
|
6a8313c33bd8cf0d73fae3d2845271039d234c91
|
[
"BSD-2-Clause"
] | null | null | null |
include/gladys/point.hpp
|
PBechon/gladys
|
6a8313c33bd8cf0d73fae3d2845271039d234c91
|
[
"BSD-2-Clause"
] | null | null | null |
include/gladys/point.hpp
|
PBechon/gladys
|
6a8313c33bd8cf0d73fae3d2845271039d234c91
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* point.hpp
*
* Graph Library for Autonomous and Dynamic Systems
*
* author: Pierrick Koch <pierrick.koch@laas.fr>
* created: 2013-07-22
* license: BSD
*/
#ifndef POINT_HPP
#define POINT_HPP
#include <cmath>
#include <array>
#include <vector>
#include <deque>
#include <ostream>
#include <sstream>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
namespace gladys {
typedef std::array<double, 2> point_xy_t; // XY
typedef std::array<double, 3> point_xyz_t; // XYZ
typedef std::array<double, 4> point_xyzt_t; // XYZ + Theta
typedef std::vector<point_xy_t> points_t; // list of points
typedef std::deque<point_xy_t> path_t; // path = deque for push_front
template<typename Container>
inline std::ostream& stream_it(std::ostream& os, Container& c);
template <typename T>
inline std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
return stream_it(os, v);
}
template <typename T>
inline std::ostream& operator<<(std::ostream& os, const std::deque<T>& v) {
return stream_it(os, v);
}
template <typename T, size_t N>
inline std::ostream& operator<<(std::ostream& os, const std::array<T, N>& v) {
return stream_it(os, v);
}
template<typename Container>
inline std::ostream& stream_it(std::ostream& os, Container& c)
{
bool first = true;
os << "[";
for (auto& v : c) {
if (first)
first = false;
else
os << ", ";
os << v;
}
return os << "]";
}
template <typename T>
std::string to_string(const T& t)
{
std::ostringstream oss;
oss << t;
return oss.str();
}
inline bool operator> (const points_t &v1, const points_t& v2) {
return (v1.size() > v2.size() );
}
/** Euclidian distance (squared)
* usefull to compare a set of points (faster)
*/
inline double distance_sq(const point_xy_t& pA, const point_xy_t& pB) {
double x = pA[0] - pB[0];
double y = pA[1] - pB[1];
return x*x + y*y;
}
inline double distance_sq(const point_xyz_t& pA, const point_xyz_t& pB) {
double x = pA[0] - pB[0];
double y = pA[1] - pB[1];
double z = pA[2] - pB[2];
return x*x + y*y + z*z;
}
inline double distance_sq(const point_xyzt_t& pA, const point_xyzt_t& pB) {
double x = pA[0] - pB[0];
double y = pA[1] - pB[1];
double z = pA[2] - pB[2];
return x*x + y*y + z*z;
}
/** Euclidian distance */
template <class Point>
inline double distance(const Point& pA, const Point& pB) {
return std::sqrt(distance_sq(pA, pB));
}
/* angle computation */
// compute yaw ; return value in ]-Pi,Pi]
// this version should be use when y-axis is inverted (goes down)
inline double yaw_angle_y_inv(const point_xy_t& pA, const point_xy_t& pB) {
double yaw = std::atan2( - pB[1] + pA[1], pB[0] - pA[0]) ; // use (-y)
yaw = std::fmod(yaw, (2*M_PI)); //modulo
if ( yaw > M_PI ) yaw -= 2*M_PI; // consider yaw in ]-Pi,Pi]
if ( yaw <= -M_PI ) yaw += 2*M_PI; // consider yaw in ]-Pi,Pi]
return yaw;
}
} // namespace gladys
#endif // POINT_HPP
| 25.033333
| 78
| 0.631824
|
PBechon
|
4c16a41e7c4b4131ce76a82296cc87f44129dc98
| 5,844
|
cpp
|
C++
|
src/transport/udp_transport.cpp
|
cysme/pump
|
d91cfdf3e09ebca1e90f0c1395a3b3fba1158a0c
|
[
"Apache-2.0"
] | 2
|
2020-07-16T04:57:40.000Z
|
2020-11-24T10:33:48.000Z
|
src/transport/udp_transport.cpp
|
jimi36/pump
|
d91cfdf3e09ebca1e90f0c1395a3b3fba1158a0c
|
[
"Apache-2.0"
] | 2
|
2020-12-23T09:40:16.000Z
|
2021-03-03T09:49:36.000Z
|
src/transport/udp_transport.cpp
|
cysme/pump
|
d91cfdf3e09ebca1e90f0c1395a3b3fba1158a0c
|
[
"Apache-2.0"
] | 3
|
2020-11-24T10:33:35.000Z
|
2021-04-19T01:53:24.000Z
|
/*
* Copyright (C) 2015-2018 ZhengHaiTao <ming8ren@163.com>
*
* 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 "pump/transport/udp_transport.h"
namespace pump {
namespace transport {
udp_transport::udp_transport(const address &bind_address) noexcept
: base_transport(UDP_TRANSPORT, nullptr, -1) {
local_address_ = bind_address;
}
udp_transport::~udp_transport() {
__stop_read_tracker();
__stop_send_tracker();
}
int32_t udp_transport::start(service_ptr sv, const transport_callbacks &cbs) {
if (!sv) {
PUMP_ERR_LOG("udp_transport: start failed with invalid service");
return ERROR_INVALID;
}
if (!cbs.read_from_cb || !cbs.stopped_cb) {
PUMP_ERR_LOG("udp_transport: start failed with invalid callbacks");
return ERROR_INVALID;
}
if (!__set_state(TRANSPORT_INITED, TRANSPORT_STARTING)) {
PUMP_ERR_LOG("udp_transport: start failed with wrong status");
return ERROR_INVALID;
}
// Set callbacks
cbs_ = cbs;
// Set service
__set_service(sv);
toolkit::defer cleanup([&]() {
__close_transport_flow();
__set_state(TRANSPORT_STARTING, TRANSPORT_ERROR);
});
if (!__open_transport_flow()) {
PUMP_ERR_LOG("udp_transport: start failed for opening flow failed");
return ERROR_FAULT;
}
__set_state(TRANSPORT_STARTING, TRANSPORT_STARTED);
cleanup.clear();
return ERROR_OK;
}
void udp_transport::stop() {
while (__is_state(TRANSPORT_STARTED)) {
if (__set_state(TRANSPORT_STARTED, TRANSPORT_STOPPING)) {
__shutdown_transport_flow();
__post_channel_event(shared_from_this(), 0);
return;
}
}
}
int32_t udp_transport::read_for_once() {
while (__is_state(TRANSPORT_STARTED)) {
int32_t err = __async_read(READ_ONCE);
if (err != ERROR_AGAIN) {
return err;
}
}
return ERROR_UNSTART;
}
int32_t udp_transport::read_for_loop() {
while (__is_state(TRANSPORT_STARTED)) {
int32_t err = __async_read(READ_LOOP);
if (err != ERROR_AGAIN) {
return err;
}
}
return ERROR_UNSTART;
}
int32_t udp_transport::send(const block_t *b,
int32_t size,
const address &address) {
if (!b || size == 0) {
PUMP_ERR_LOG("udp_transport: send failed with invalid buffer");
return ERROR_INVALID;
}
if (PUMP_UNLIKELY(!__is_state(TRANSPORT_STARTED))) {
PUMP_ERR_LOG("udp_transport: send failed for transport no statred");
return ERROR_UNSTART;
}
if (PUMP_LIKELY(flow_->send(b, size, address) > 0)) {
return ERROR_OK;
}
return ERROR_AGAIN;
}
void udp_transport::on_read_event() {
auto flow = flow_.get();
address from_addr;
block_t b[MAX_UDP_BUFFER_SIZE];
int32_t size = flow->read_from(b, sizeof(b), &from_addr);
if (PUMP_LIKELY(size > 0)) {
// If read state is READ_ONCE, change it to READ_PENDING.
// If read state is READ_LOOP, last state will be seted to READ_LOOP.
int32_t last_state = READ_ONCE;
read_state_.compare_exchange_strong(last_state, READ_PENDING);
// Do read callback.
cbs_.read_from_cb(b, size, from_addr);
// If last read state is READ_ONCE, try to change read state to READ_NONE.
if (last_state == READ_ONCE) {
last_state = READ_PENDING;
if (read_state_.compare_exchange_strong(last_state, READ_NONE)) {
return;
}
}
}
// If transport is not in started state, try to interrupt the transport.
if (!__is_state(TRANSPORT_STARTED)) {
__interrupt_and_trigger_callbacks();
return;
}
PUMP_DEBUG_CHECK(__resume_read_tracker());
}
bool udp_transport::__open_transport_flow() {
// Init udp transport flow.
PUMP_ASSERT(!flow_);
flow_.reset(object_create<flow::flow_udp>(), object_delete<flow::flow_udp>);
if (flow_->init(shared_from_this(), local_address_) != flow::FLOW_ERR_NO) {
PUMP_ERR_LOG("udp_transport: open transport flow failed for flow init failed");
return false;
}
// Set channel fd.
poll::channel::__set_fd(flow_->get_fd());
return true;
}
int32_t udp_transport::__async_read(int32_t state) {
int32_t current_state = __change_read_state(state);
if (current_state >= READ_PENDING) {
return ERROR_OK;
} else if (current_state == READ_INVALID) {
return ERROR_AGAIN;
}
if (!__start_read_tracker()) {
PUMP_ERR_LOG("udp_transport: async read failed for starting read tracker fialed");
return ERROR_FAULT;
}
return ERROR_OK;
}
} // namespace transport
} // namespace pump
| 31.251337
| 94
| 0.596509
|
cysme
|
4c176ebbdc840d8b7d55df6f5b1892e119d865d4
| 1,752
|
ipp
|
C++
|
include/boost/mysql/detail/protocol/impl/common_messages.ipp
|
madmongo1/mysql-asio
|
26c57e92ddeebfee22e08e5ea05e7bb51248eba5
|
[
"BSL-1.0"
] | 1
|
2020-03-31T11:48:12.000Z
|
2020-03-31T11:48:12.000Z
|
include/boost/mysql/detail/protocol/impl/common_messages.ipp
|
madmongo1/mysql-asio
|
26c57e92ddeebfee22e08e5ea05e7bb51248eba5
|
[
"BSL-1.0"
] | null | null | null |
include/boost/mysql/detail/protocol/impl/common_messages.ipp
|
madmongo1/mysql-asio
|
26c57e92ddeebfee22e08e5ea05e7bb51248eba5
|
[
"BSL-1.0"
] | null | null | null |
#ifndef INCLUDE_BOOST_MYSQL_DETAIL_PROTOCOL_IMPL_COMMON_MESSAGES_IPP_
#define INCLUDE_BOOST_MYSQL_DETAIL_PROTOCOL_IMPL_COMMON_MESSAGES_IPP_
inline boost::mysql::errc
boost::mysql::detail::serialization_traits<
boost::mysql::detail::ok_packet,
boost::mysql::detail::serialization_tag::struct_with_fields
>::deserialize_(
ok_packet& output,
deserialization_context& ctx
) noexcept
{
{
auto err = deserialize_fields(
ctx,
output.affected_rows,
output.last_insert_id,
output.status_flags,
output.warnings
);
if (err == errc::ok && ctx.enough_size(1)) // message is optional, may be omitted
{
err = deserialize(output.info, ctx);
}
return err;
}
}
inline boost::mysql::errc
boost::mysql::detail::serialization_traits<
boost::mysql::detail::column_definition_packet,
boost::mysql::detail::serialization_tag::struct_with_fields
>::deserialize_(
column_definition_packet& output,
deserialization_context& ctx
) noexcept
{
int_lenenc length_of_fixed_fields;
int2 final_padding;
return deserialize_fields(
ctx,
output.catalog,
output.schema,
output.table,
output.org_table,
output.name,
output.org_name,
length_of_fixed_fields,
output.character_set,
output.column_length,
output.type,
output.flags,
output.decimals,
final_padding
);
}
inline boost::mysql::error_code boost::mysql::detail::process_error_packet(
deserialization_context& ctx,
error_info& info
)
{
err_packet error_packet;
auto code = deserialize_message(error_packet, ctx);
if (code) return code;
info.set_message(std::string(error_packet.error_message.value));
return make_error_code(static_cast<errc>(error_packet.error_code.value));
}
#endif /* INCLUDE_BOOST_MYSQL_DETAIL_PROTOCOL_IMPL_COMMON_MESSAGES_IPP_ */
| 24.333333
| 83
| 0.778539
|
madmongo1
|
4c18387cdf16bfe073c05b31ddb66cdc3b029f98
| 15,122
|
cpp
|
C++
|
qws/src/core/QRect.cpp
|
keera-studios/hsQt
|
8aa71a585cbec40005354d0ee43bce9794a55a9a
|
[
"BSD-2-Clause"
] | 42
|
2015-02-16T19:29:16.000Z
|
2021-07-25T11:09:03.000Z
|
qws/src/core/QRect.cpp
|
keera-studios/hsQt
|
8aa71a585cbec40005354d0ee43bce9794a55a9a
|
[
"BSD-2-Clause"
] | 1
|
2017-11-23T12:49:25.000Z
|
2017-11-23T12:49:25.000Z
|
qws/src/core/QRect.cpp
|
keera-studios/hsQt
|
8aa71a585cbec40005354d0ee43bce9794a55a9a
|
[
"BSD-2-Clause"
] | 5
|
2015-10-15T21:25:30.000Z
|
2017-11-22T13:18:24.000Z
|
/////////////////////////////////////////////////////////////////////////////
//
// File : QRect.cpp
// Copyright : (c) David Harley 2010
// Project : qtHaskell
// Version : 1.1.4
// Modified : 2010-09-02 17:01:55
//
// Warning : this file is machine generated - do not modify.
//
/////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <wchar.h>
#include <qtc_wrp_core.h>
#include <qtc_subclass.h>
#ifndef dhclassheader
#define dhclassheader
#include <qpointer.h>
#include <dynamicqhandler.h>
#include <DhOther_core.h>
#include <DhAutohead_core.h>
#endif
extern "C"
{
QTCEXPORT(void*,qtc_QRect)() {
QRect*tr = new QRect();
return (void*) tr;
}
QTCEXPORT(void*,qtc_QRect1)(void* x1) {
QRect*tr = new QRect((const QRect&)(*(QRect*)x1));
return (void*) tr;
}
QTCEXPORT(void*,qtc_QRect2)(int x1_x, int x1_y, int x1_w, int x1_h) {
QRect tx1(x1_x, x1_y, x1_w, x1_h);
QRect*tr = new QRect(tx1);
return (void*) tr;
}
QTCEXPORT(void*,qtc_QRect3)(void* x1, void* x2) {
QRect*tr = new QRect((const QPoint&)(*(QPoint*)x1), (const QPoint&)(*(QPoint*)x2));
return (void*) tr;
}
QTCEXPORT(void*,qtc_QRect4)(int x1_x, int x1_y, int x2_x, int x2_y) {
QPoint tx1(x1_x, x1_y);
QPoint tx2(x2_x, x2_y);
QRect*tr = new QRect(tx1, tx2);
return (void*) tr;
}
QTCEXPORT(void*,qtc_QRect5)(void* x1, void* x2) {
QRect*tr = new QRect((const QPoint&)(*(QPoint*)x1), (const QSize&)(*(QSize*)x2));
return (void*) tr;
}
QTCEXPORT(void*,qtc_QRect6)(int x1_x, int x1_y, int x2_w, int x2_h) {
QPoint tx1(x1_x, x1_y);
QSize tx2(x2_w, x2_h);
QRect*tr = new QRect(tx1, tx2);
return (void*) tr;
}
QTCEXPORT(void*,qtc_QRect7)(int x1, int x2, int x3, int x4) {
QRect*tr = new QRect((int)x1, (int)x2, (int)x3, (int)x4);
return (void*) tr;
}
QTCEXPORT(void,qtc_QRect_adjust)(void* x0, int x1, int x2, int x3, int x4) {
((QRect*)x0)->adjust((int)x1, (int)x2, (int)x3, (int)x4);
}
QTCEXPORT(void*,qtc_QRect_adjusted)(void* x0, int x1, int x2, int x3, int x4) {
QRect * tc = new QRect(((QRect*)x0)->adjusted((int)x1, (int)x2, (int)x3, (int)x4));
return (void*)(tc);
}
QTCEXPORT(void,qtc_QRect_adjusted_qth)(void* x0, int x1, int x2, int x3, int x4, int* _ret_x, int* _ret_y, int* _ret_w, int* _ret_h) {
QRect tc = ((QRect*)x0)->adjusted((int)x1, (int)x2, (int)x3, (int)x4);
*_ret_x = tc.x(); *_ret_y = tc.y(); *_ret_w = tc.width(); *_ret_h = tc.height();
return;
}
QTCEXPORT(int,qtc_QRect_bottom)(void* x0) {
return (int) ((QRect*)x0)->bottom();
}
QTCEXPORT(void*,qtc_QRect_bottomLeft)(void* x0) {
QPoint * tc = new QPoint(((QRect*)x0)->bottomLeft());
return (void*)(tc);
}
QTCEXPORT(void,qtc_QRect_bottomLeft_qth)(void* x0, int* _ret_x, int* _ret_y) {
QPoint tc = ((QRect*)x0)->bottomLeft();
*_ret_x = tc.x(); *_ret_y = tc.y();
return;
}
QTCEXPORT(void*,qtc_QRect_bottomRight)(void* x0) {
QPoint * tc = new QPoint(((QRect*)x0)->bottomRight());
return (void*)(tc);
}
QTCEXPORT(void,qtc_QRect_bottomRight_qth)(void* x0, int* _ret_x, int* _ret_y) {
QPoint tc = ((QRect*)x0)->bottomRight();
*_ret_x = tc.x(); *_ret_y = tc.y();
return;
}
QTCEXPORT(void*,qtc_QRect_center)(void* x0) {
QPoint * tc = new QPoint(((QRect*)x0)->center());
return (void*)(tc);
}
QTCEXPORT(void,qtc_QRect_center_qth)(void* x0, int* _ret_x, int* _ret_y) {
QPoint tc = ((QRect*)x0)->center();
*_ret_x = tc.x(); *_ret_y = tc.y();
return;
}
QTCEXPORT(int,qtc_QRect_contains)(void* x0, void* x1) {
return (int) ((QRect*)x0)->contains((const QPoint&)(*(QPoint*)x1));
}
QTCEXPORT(int,qtc_QRect_contains_qth)(void* x0, int x1_x, int x1_y) {
QPoint tx1(x1_x, x1_y);
return (int) ((QRect*)x0)->contains(tx1);
}
QTCEXPORT(int,qtc_QRect_contains1)(void* x0, void* x1) {
return (int) ((QRect*)x0)->contains((const QRect&)(*(QRect*)x1));
}
QTCEXPORT(int,qtc_QRect_contains1_qth)(void* x0, int x1_x, int x1_y, int x1_w, int x1_h) {
QRect tx1(x1_x, x1_y, x1_w, x1_h);
return (int) ((QRect*)x0)->contains(tx1);
}
QTCEXPORT(int,qtc_QRect_contains2)(void* x0, void* x1, int x2) {
return (int) ((QRect*)x0)->contains((const QPoint&)(*(QPoint*)x1), (bool)x2);
}
QTCEXPORT(int,qtc_QRect_contains2_qth)(void* x0, int x1_x, int x1_y, int x2) {
QPoint tx1(x1_x, x1_y);
return (int) ((QRect*)x0)->contains(tx1, (bool)x2);
}
QTCEXPORT(int,qtc_QRect_contains3)(void* x0, void* x1, int x2) {
return (int) ((QRect*)x0)->contains((const QRect&)(*(QRect*)x1), (bool)x2);
}
QTCEXPORT(int,qtc_QRect_contains3_qth)(void* x0, int x1_x, int x1_y, int x1_w, int x1_h, int x2) {
QRect tx1(x1_x, x1_y, x1_w, x1_h);
return (int) ((QRect*)x0)->contains(tx1, (bool)x2);
}
QTCEXPORT(int,qtc_QRect_contains4)(void* x0, int x1, int x2) {
return (int) ((QRect*)x0)->contains((int)x1, (int)x2);
}
QTCEXPORT(int,qtc_QRect_contains5)(void* x0, int x1, int x2, int x3) {
return (int) ((QRect*)x0)->contains((int)x1, (int)x2, (bool)x3);
}
QTCEXPORT(int,qtc_QRect_height)(void* x0) {
return (int) ((QRect*)x0)->height();
}
QTCEXPORT(void*,qtc_QRect_intersect)(void* x0, void* x1) {
QRect * tc = new QRect(((QRect*)x0)->intersect((const QRect&)(*(QRect*)x1)));
return (void*)(tc);
}
QTCEXPORT(void,qtc_QRect_intersect_qth)(void* x0, int x1_x, int x1_y, int x1_w, int x1_h, int* _ret_x, int* _ret_y, int* _ret_w, int* _ret_h) {
QRect tx1(x1_x, x1_y, x1_w, x1_h);
QRect tc = ((QRect*)x0)->intersect(tx1);
*_ret_x = tc.x(); *_ret_y = tc.y(); *_ret_w = tc.width(); *_ret_h = tc.height();
return;
}
QTCEXPORT(void*,qtc_QRect_intersected)(void* x0, void* x1) {
QRect * tc = new QRect(((QRect*)x0)->intersected((const QRect&)(*(QRect*)x1)));
return (void*)(tc);
}
QTCEXPORT(void,qtc_QRect_intersected_qth)(void* x0, int x1_x, int x1_y, int x1_w, int x1_h, int* _ret_x, int* _ret_y, int* _ret_w, int* _ret_h) {
QRect tx1(x1_x, x1_y, x1_w, x1_h);
QRect tc = ((QRect*)x0)->intersected(tx1);
*_ret_x = tc.x(); *_ret_y = tc.y(); *_ret_w = tc.width(); *_ret_h = tc.height();
return;
}
QTCEXPORT(int,qtc_QRect_intersects)(void* x0, void* x1) {
return (int) ((QRect*)x0)->intersects((const QRect&)(*(QRect*)x1));
}
QTCEXPORT(int,qtc_QRect_intersects_qth)(void* x0, int x1_x, int x1_y, int x1_w, int x1_h) {
QRect tx1(x1_x, x1_y, x1_w, x1_h);
return (int) ((QRect*)x0)->intersects(tx1);
}
QTCEXPORT(int,qtc_QRect_isEmpty)(void* x0) {
return (int) ((QRect*)x0)->isEmpty();
}
QTCEXPORT(int,qtc_QRect_isNull)(void* x0) {
return (int) ((QRect*)x0)->isNull();
}
QTCEXPORT(int,qtc_QRect_isValid)(void* x0) {
return (int) ((QRect*)x0)->isValid();
}
QTCEXPORT(int,qtc_QRect_left)(void* x0) {
return (int) ((QRect*)x0)->left();
}
QTCEXPORT(void,qtc_QRect_moveBottom)(void* x0, int x1) {
((QRect*)x0)->moveBottom((int)x1);
}
QTCEXPORT(void,qtc_QRect_moveBottomLeft)(void* x0, void* x1) {
((QRect*)x0)->moveBottomLeft((const QPoint&)(*(QPoint*)x1));
}
QTCEXPORT(void,qtc_QRect_moveBottomLeft_qth)(void* x0, int x1_x, int x1_y) {
QPoint tx1(x1_x, x1_y);
((QRect*)x0)->moveBottomLeft(tx1);
}
QTCEXPORT(void,qtc_QRect_moveBottomRight)(void* x0, void* x1) {
((QRect*)x0)->moveBottomRight((const QPoint&)(*(QPoint*)x1));
}
QTCEXPORT(void,qtc_QRect_moveBottomRight_qth)(void* x0, int x1_x, int x1_y) {
QPoint tx1(x1_x, x1_y);
((QRect*)x0)->moveBottomRight(tx1);
}
QTCEXPORT(void,qtc_QRect_moveCenter)(void* x0, void* x1) {
((QRect*)x0)->moveCenter((const QPoint&)(*(QPoint*)x1));
}
QTCEXPORT(void,qtc_QRect_moveCenter_qth)(void* x0, int x1_x, int x1_y) {
QPoint tx1(x1_x, x1_y);
((QRect*)x0)->moveCenter(tx1);
}
QTCEXPORT(void,qtc_QRect_moveLeft)(void* x0, int x1) {
((QRect*)x0)->moveLeft((int)x1);
}
QTCEXPORT(void,qtc_QRect_moveRight)(void* x0, int x1) {
((QRect*)x0)->moveRight((int)x1);
}
QTCEXPORT(void,qtc_QRect_moveTo)(void* x0, void* x1) {
((QRect*)x0)->moveTo((const QPoint&)(*(QPoint*)x1));
}
QTCEXPORT(void,qtc_QRect_moveTo_qth)(void* x0, int x1_x, int x1_y) {
QPoint tx1(x1_x, x1_y);
((QRect*)x0)->moveTo(tx1);
}
QTCEXPORT(void,qtc_QRect_moveTo1)(void* x0, int x1, int x2) {
((QRect*)x0)->moveTo((int)x1, (int)x2);
}
QTCEXPORT(void,qtc_QRect_moveTop)(void* x0, int x1) {
((QRect*)x0)->moveTop((int)x1);
}
QTCEXPORT(void,qtc_QRect_moveTopLeft)(void* x0, void* x1) {
((QRect*)x0)->moveTopLeft((const QPoint&)(*(QPoint*)x1));
}
QTCEXPORT(void,qtc_QRect_moveTopLeft_qth)(void* x0, int x1_x, int x1_y) {
QPoint tx1(x1_x, x1_y);
((QRect*)x0)->moveTopLeft(tx1);
}
QTCEXPORT(void,qtc_QRect_moveTopRight)(void* x0, void* x1) {
((QRect*)x0)->moveTopRight((const QPoint&)(*(QPoint*)x1));
}
QTCEXPORT(void,qtc_QRect_moveTopRight_qth)(void* x0, int x1_x, int x1_y) {
QPoint tx1(x1_x, x1_y);
((QRect*)x0)->moveTopRight(tx1);
}
QTCEXPORT(void*,qtc_QRect_normalized)(void* x0) {
QRect * tc = new QRect(((QRect*)x0)->normalized());
return (void*)(tc);
}
QTCEXPORT(void,qtc_QRect_normalized_qth)(void* x0, int* _ret_x, int* _ret_y, int* _ret_w, int* _ret_h) {
QRect tc = ((QRect*)x0)->normalized();
*_ret_x = tc.x(); *_ret_y = tc.y(); *_ret_w = tc.width(); *_ret_h = tc.height();
return;
}
QTCEXPORT(int,qtc_QRect_right)(void* x0) {
return (int) ((QRect*)x0)->right();
}
QTCEXPORT(void,qtc_QRect_setBottom)(void* x0, int x1) {
((QRect*)x0)->setBottom((int)x1);
}
QTCEXPORT(void,qtc_QRect_setBottomLeft)(void* x0, void* x1) {
((QRect*)x0)->setBottomLeft((const QPoint&)(*(QPoint*)x1));
}
QTCEXPORT(void,qtc_QRect_setBottomLeft_qth)(void* x0, int x1_x, int x1_y) {
QPoint tx1(x1_x, x1_y);
((QRect*)x0)->setBottomLeft(tx1);
}
QTCEXPORT(void,qtc_QRect_setBottomRight)(void* x0, void* x1) {
((QRect*)x0)->setBottomRight((const QPoint&)(*(QPoint*)x1));
}
QTCEXPORT(void,qtc_QRect_setBottomRight_qth)(void* x0, int x1_x, int x1_y) {
QPoint tx1(x1_x, x1_y);
((QRect*)x0)->setBottomRight(tx1);
}
QTCEXPORT(void,qtc_QRect_setCoords)(void* x0, int x1, int x2, int x3, int x4) {
((QRect*)x0)->setCoords((int)x1, (int)x2, (int)x3, (int)x4);
}
QTCEXPORT(void,qtc_QRect_setHeight)(void* x0, int x1) {
((QRect*)x0)->setHeight((int)x1);
}
QTCEXPORT(void,qtc_QRect_setLeft)(void* x0, int x1) {
((QRect*)x0)->setLeft((int)x1);
}
QTCEXPORT(void,qtc_QRect_setRect)(void* x0, int x1, int x2, int x3, int x4) {
((QRect*)x0)->setRect((int)x1, (int)x2, (int)x3, (int)x4);
}
QTCEXPORT(void,qtc_QRect_setRight)(void* x0, int x1) {
((QRect*)x0)->setRight((int)x1);
}
QTCEXPORT(void,qtc_QRect_setSize)(void* x0, void* x1) {
((QRect*)x0)->setSize((const QSize&)(*(QSize*)x1));
}
QTCEXPORT(void,qtc_QRect_setSize_qth)(void* x0, int x1_w, int x1_h) {
QSize tx1(x1_w, x1_h);
((QRect*)x0)->setSize(tx1);
}
QTCEXPORT(void,qtc_QRect_setTop)(void* x0, int x1) {
((QRect*)x0)->setTop((int)x1);
}
QTCEXPORT(void,qtc_QRect_setTopLeft)(void* x0, void* x1) {
((QRect*)x0)->setTopLeft((const QPoint&)(*(QPoint*)x1));
}
QTCEXPORT(void,qtc_QRect_setTopLeft_qth)(void* x0, int x1_x, int x1_y) {
QPoint tx1(x1_x, x1_y);
((QRect*)x0)->setTopLeft(tx1);
}
QTCEXPORT(void,qtc_QRect_setTopRight)(void* x0, void* x1) {
((QRect*)x0)->setTopRight((const QPoint&)(*(QPoint*)x1));
}
QTCEXPORT(void,qtc_QRect_setTopRight_qth)(void* x0, int x1_x, int x1_y) {
QPoint tx1(x1_x, x1_y);
((QRect*)x0)->setTopRight(tx1);
}
QTCEXPORT(void,qtc_QRect_setWidth)(void* x0, int x1) {
((QRect*)x0)->setWidth((int)x1);
}
QTCEXPORT(void,qtc_QRect_setX)(void* x0, int x1) {
((QRect*)x0)->setX((int)x1);
}
QTCEXPORT(void,qtc_QRect_setY)(void* x0, int x1) {
((QRect*)x0)->setY((int)x1);
}
QTCEXPORT(void*,qtc_QRect_size)(void* x0) {
QSize * tc = new QSize(((QRect*)x0)->size());
return (void*)(tc);
}
QTCEXPORT(void,qtc_QRect_size_qth)(void* x0, int* _ret_w, int* _ret_h) {
QSize tc = ((QRect*)x0)->size();
*_ret_w = tc.width(); *_ret_h = tc.height();
return;
}
QTCEXPORT(int,qtc_QRect_top)(void* x0) {
return (int) ((QRect*)x0)->top();
}
QTCEXPORT(void*,qtc_QRect_topLeft)(void* x0) {
QPoint * tc = new QPoint(((QRect*)x0)->topLeft());
return (void*)(tc);
}
QTCEXPORT(void,qtc_QRect_topLeft_qth)(void* x0, int* _ret_x, int* _ret_y) {
QPoint tc = ((QRect*)x0)->topLeft();
*_ret_x = tc.x(); *_ret_y = tc.y();
return;
}
QTCEXPORT(void*,qtc_QRect_topRight)(void* x0) {
QPoint * tc = new QPoint(((QRect*)x0)->topRight());
return (void*)(tc);
}
QTCEXPORT(void,qtc_QRect_topRight_qth)(void* x0, int* _ret_x, int* _ret_y) {
QPoint tc = ((QRect*)x0)->topRight();
*_ret_x = tc.x(); *_ret_y = tc.y();
return;
}
QTCEXPORT(void,qtc_QRect_translate)(void* x0, void* x1) {
((QRect*)x0)->translate((const QPoint&)(*(QPoint*)x1));
}
QTCEXPORT(void,qtc_QRect_translate_qth)(void* x0, int x1_x, int x1_y) {
QPoint tx1(x1_x, x1_y);
((QRect*)x0)->translate(tx1);
}
QTCEXPORT(void,qtc_QRect_translate1)(void* x0, int x1, int x2) {
((QRect*)x0)->translate((int)x1, (int)x2);
}
QTCEXPORT(void*,qtc_QRect_translated)(void* x0, void* x1) {
QRect * tc = new QRect(((QRect*)x0)->translated((const QPoint&)(*(QPoint*)x1)));
return (void*)(tc);
}
QTCEXPORT(void,qtc_QRect_translated_qth)(void* x0, int x1_x, int x1_y, int* _ret_x, int* _ret_y, int* _ret_w, int* _ret_h) {
QPoint tx1(x1_x, x1_y);
QRect tc = ((QRect*)x0)->translated(tx1);
*_ret_x = tc.x(); *_ret_y = tc.y(); *_ret_w = tc.width(); *_ret_h = tc.height();
return;
}
QTCEXPORT(void*,qtc_QRect_translated1)(void* x0, int x1, int x2) {
QRect * tc = new QRect(((QRect*)x0)->translated((int)x1, (int)x2));
return (void*)(tc);
}
QTCEXPORT(void,qtc_QRect_translated1_qth)(void* x0, int x1, int x2, int* _ret_x, int* _ret_y, int* _ret_w, int* _ret_h) {
QRect tc = ((QRect*)x0)->translated((int)x1, (int)x2);
*_ret_x = tc.x(); *_ret_y = tc.y(); *_ret_w = tc.width(); *_ret_h = tc.height();
return;
}
QTCEXPORT(void*,qtc_QRect_unite)(void* x0, void* x1) {
QRect * tc = new QRect(((QRect*)x0)->unite((const QRect&)(*(QRect*)x1)));
return (void*)(tc);
}
QTCEXPORT(void,qtc_QRect_unite_qth)(void* x0, int x1_x, int x1_y, int x1_w, int x1_h, int* _ret_x, int* _ret_y, int* _ret_w, int* _ret_h) {
QRect tx1(x1_x, x1_y, x1_w, x1_h);
QRect tc = ((QRect*)x0)->unite(tx1);
*_ret_x = tc.x(); *_ret_y = tc.y(); *_ret_w = tc.width(); *_ret_h = tc.height();
return;
}
QTCEXPORT(void*,qtc_QRect_united)(void* x0, void* x1) {
QRect * tc = new QRect(((QRect*)x0)->united((const QRect&)(*(QRect*)x1)));
return (void*)(tc);
}
QTCEXPORT(void,qtc_QRect_united_qth)(void* x0, int x1_x, int x1_y, int x1_w, int x1_h, int* _ret_x, int* _ret_y, int* _ret_w, int* _ret_h) {
QRect tx1(x1_x, x1_y, x1_w, x1_h);
QRect tc = ((QRect*)x0)->united(tx1);
*_ret_x = tc.x(); *_ret_y = tc.y(); *_ret_w = tc.width(); *_ret_h = tc.height();
return;
}
QTCEXPORT(int,qtc_QRect_width)(void* x0) {
return (int) ((QRect*)x0)->width();
}
QTCEXPORT(int,qtc_QRect_x)(void* x0) {
return (int) ((QRect*)x0)->x();
}
QTCEXPORT(int,qtc_QRect_y)(void* x0) {
return (int) ((QRect*)x0)->y();
}
QTCEXPORT(void,qtc_QRect_finalizer)(void* x0) {
delete ((QRect*)x0);
}
QTCEXPORT(void*,qtc_QRect_getFinalizer)() {
return (void*)(&qtc_QRect_finalizer);
}
QTCEXPORT(void,qtc_QRect_delete)(void* x0) {
delete((QRect*)x0);
}
}
| 29.19305
| 145
| 0.64707
|
keera-studios
|
4c1c987ca1d4f8ee3094a97ed139b6f6c770de0c
| 10,619
|
cpp
|
C++
|
src/game/server/swarm/asw_ranger.cpp
|
BenLubar/SwarmDirector2
|
78685d03eaa0d35e87c638ffa78f46f3aa8379a6
|
[
"Apache-2.0"
] | 3
|
2015-05-17T02:33:00.000Z
|
2016-10-08T07:02:40.000Z
|
src/game/server/swarm/asw_ranger.cpp
|
BenLubar/SwarmDirector2
|
78685d03eaa0d35e87c638ffa78f46f3aa8379a6
|
[
"Apache-2.0"
] | null | null | null |
src/game/server/swarm/asw_ranger.cpp
|
BenLubar/SwarmDirector2
|
78685d03eaa0d35e87c638ffa78f46f3aa8379a6
|
[
"Apache-2.0"
] | 1
|
2019-10-16T15:21:56.000Z
|
2019-10-16T15:21:56.000Z
|
#include "cbase.h"
#include "asw_ranger.h"
#include "npcevent.h"
#include "asw_gamerules.h"
#include "asw_shareddefs.h"
#include "asw_fx_shared.h"
#include "asw_grenade_cluster.h"
#include "world.h"
#include "particle_parse.h"
#include "asw_util_shared.h"
#include "ai_squad.h"
#include "asw_marine.h"
#include "gib.h"
#include "te_effect_dispatch.h"
#include "asw_ai_behavior.h"
#include "props_shared.h"
#include "ammodef.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
LINK_ENTITY_TO_CLASS( asw_ranger, CASW_Ranger );
IMPLEMENT_SERVERCLASS_ST( CASW_Ranger, DT_ASW_Ranger )
END_SEND_TABLE()
BEGIN_DATADESC( CASW_Ranger )
DEFINE_EMBEDDEDBYREF( m_pExpresser ),
END_DATADESC()
ConVar asw_ranger_health( "asw_ranger_health", "101.5", FCVAR_CHEAT );
extern ConVar asw_debug_alien_damage;
extern int AE_MORTARBUG_LAUNCH; // actual launch of the projectile
extern ConVar asw_drone_death_force_pitch;
//-----------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//-----------------------------------------------------------------------------
CASW_Ranger::CASW_Ranger()
{
m_pszAlienModelName = "models/aliens/mortar3/mortar3.mdl";
}
void CASW_Ranger::SetupRangerShot( CASW_AlienShot &shot )
{
shot.m_flSize = 4;
shot.m_flDamage_direct = 12;
shot.m_flDamage_splash = 0;
shot.m_flSeek_strength = 0;
shot.m_flGravity = 0;
shot.m_flFuse = 5;
shot.m_flBounce = 0;
shot.m_bShootable = false;
shot.m_strModel = "models/aliens/rangerSpit/rangerspit.mdl";
shot.m_strSound_spawn = "ASW_Ranger_Projectile.Spawned";
shot.m_strSound_hitNPC = "Ranger.projectileImpactPlayer";
shot.m_strSound_hitWorld = "Ranger.projectileImpactWorld";
shot.m_strParticles_trail = "ranger_projectile_main_trail";
shot.m_strParticles_hit = "ranger_projectile_hit";
CreateShot( "shot1", &shot );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//-----------------------------------------------------------------------------
void CASW_Ranger::Spawn( void )
{
SetHullType( HULL_MEDIUMBIG );
BaseClass::Spawn();
SetHullType( HULL_MEDIUMBIG );
SetHealthByDifficultyLevel();
SetBloodColor( BLOOD_COLOR_GREEN );
CapabilitiesAdd( bits_CAP_MOVE_GROUND | bits_CAP_INNATE_MELEE_ATTACK1 | bits_CAP_INNATE_RANGE_ATTACK1 );
SetIdealState( NPC_STATE_ALERT );
m_bNeverRagdoll = true;
//
// Firing patterns
//
// 3 shots
CASW_AlienVolley volley;
volley.m_rounds.SetCount( 3 );
volley.m_rounds[0].m_flTime = 0;
volley.m_rounds[0].m_nShot_type = GetShotIndex( "shot1" );
volley.m_rounds[0].m_flStartAngle = 0;
volley.m_rounds[0].m_flEndAngle = 0;
volley.m_rounds[0].m_nNumShots = 1;
volley.m_rounds[0].m_flShotDelay = 0;
volley.m_rounds[0].m_flSpeed = 425;
volley.m_rounds[0].m_flHorizontalOffset = 0;
volley.m_rounds[1].m_flTime = 0.1;
volley.m_rounds[1].m_nShot_type = GetShotIndex( "shot1" );
volley.m_rounds[1].m_flStartAngle = -4;
volley.m_rounds[1].m_flEndAngle = 0;
volley.m_rounds[1].m_nNumShots = 1;
volley.m_rounds[1].m_flShotDelay = 0;
volley.m_rounds[1].m_flSpeed = 425;
volley.m_rounds[1].m_flHorizontalOffset = 0;
volley.m_rounds[2].m_flTime = 0.2;
volley.m_rounds[2].m_nShot_type = GetShotIndex( "shot1" );
volley.m_rounds[2].m_flStartAngle = 4;
volley.m_rounds[2].m_flEndAngle = 0;
volley.m_rounds[2].m_nNumShots = 1;
volley.m_rounds[2].m_flShotDelay = 0;
volley.m_rounds[2].m_flSpeed = 425;
volley.m_rounds[2].m_flHorizontalOffset = 0;
CreateVolley( "volley1", &volley );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//-----------------------------------------------------------------------------
void CASW_Ranger::Precache( void )
{
BaseClass::Precache();
PrecacheModel( "models/aliens/rangerSpit/rangerspit.mdl" );
// precache shot model and fx, add shot to list
CASW_AlienShot shot;
SetupRangerShot( shot );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//-----------------------------------------------------------------------------
void CASW_Ranger::SetHealthByDifficultyLevel()
{
int iHealth = MAX( 25, ASWGameRules()->ModifyAlienHealthBySkillLevel( asw_ranger_health.GetInt() ) );
if ( asw_debug_alien_damage.GetBool() )
Msg( "Setting ranger's initial health to %d\n", iHealth );
SetHealth( iHealth );
SetMaxHealth( iHealth );
BaseClass::SetHealthByDifficultyLevel();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//-----------------------------------------------------------------------------
float CASW_Ranger::MaxYawSpeed( void )
{
if ( GetActivity() == ACT_STRAFE_LEFT || GetActivity() == ACT_STRAFE_RIGHT )
{
return 0.1f;
}
return 32.0f;// * GetMovementSpeedModifier();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//-----------------------------------------------------------------------------
void CASW_Ranger::HandleAnimEvent( animevent_t *pEvent )
{
int nEvent = pEvent->Event();
if ( nEvent == AE_MORTARBUG_LAUNCH )
{
m_RangedAttackBehavior.HandleBehaviorEvent( this, BEHAVIOR_EVENT_MORTAR_FIRE, 0 );
return;
}
BaseClass::HandleAnimEvent( pEvent );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//-----------------------------------------------------------------------------
int CASW_Ranger::SelectDeadSchedule()
{
if ( m_lifeState == LIFE_DEAD )
{
return SCHED_NONE;
}
CleanupOnDeath();
return SCHED_DIE;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//-----------------------------------------------------------------------------
void CASW_Ranger::BuildScheduleTestBits()
{
// Ignore damage if we were recently damaged or we're attacking.
if ( GetActivity() == ACT_MELEE_ATTACK1 )
{
ClearCustomInterruptCondition( COND_LIGHT_DAMAGE );
ClearCustomInterruptCondition( COND_HEAVY_DAMAGE );
}
BaseClass::BuildScheduleTestBits();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//-----------------------------------------------------------------------------
bool CASW_Ranger::CreateBehaviors()
{
AddBehavior( &m_CombatStunBehavior );
m_CombatStunBehavior.Init();
AddBehavior( &m_FlinchBehavior );
m_FlinchBehavior.Init();
//m_PrepareToEngageBehavior.KeyValue( "prepare_radius_min", "300" );
//m_PrepareToEngageBehavior.KeyValue( "prepare_radius_max", "600" );
//AddBehavior( &m_PrepareToEngageBehavior );
//m_PrepareToEngageBehavior.Init();
AddBehavior( &m_RetreatBehavior );
m_RetreatBehavior.Init();
m_RangedAttackBehavior.KeyValue( "minRange", "0" );
m_RangedAttackBehavior.KeyValue( "maxRange", "600" );
m_RangedAttackBehavior.KeyValue( "rate", "4.0" );
m_RangedAttackBehavior.KeyValue( "global_shot_delay", "1" );
m_RangedAttackBehavior.KeyValue( "volley_type", "volley1" );
AddBehavior( &m_RangedAttackBehavior );
m_RangedAttackBehavior.Init();
m_ChaseEnemyBehavior.KeyValue( "chase_distance", "200" );
AddBehavior( &m_ChaseEnemyBehavior );
m_ChaseEnemyBehavior.Init();
AddBehavior( &m_IdleBehavior );
m_IdleBehavior.Init();
return BaseClass::CreateBehaviors();
}
void CASW_Ranger::DeathSound( const CTakeDamageInfo &info )
{
// if we are playing a fancy death animation, don't play death sounds from code
// all death sounds are played from anim events inside the fancy death animation
if ( m_nDeathStyle == kDIE_FANCY )
return;
//EmitSound( "ASW_Drone.Death" );
if ( m_bOnFire )
EmitSound( "ASW_Drone.DeathFireSizzle" );
else
EmitSound( "Ranger.GibSplatHeavy" );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//-----------------------------------------------------------------------------
void CASW_Ranger::Event_Killed( const CTakeDamageInfo &info )
{
CTakeDamageInfo newInfo(info);
// scale up the force if we're shot by a marine, to make our ragdolling more interesting
if (newInfo.GetAttacker() && newInfo.GetAttacker()->Classify() == CLASS_ASW_MARINE)
{
// scale based on the weapon used
if (info.GetAmmoType() == GetAmmoDef()->Index("ASW_R")
|| info.GetAmmoType() == GetAmmoDef()->Index("ASW_AG")
|| info.GetAmmoType() == GetAmmoDef()->Index("ASW_P"))
newInfo.ScaleDamageForce(22.0f);
else if (info.GetAmmoType() == GetAmmoDef()->Index("ASW_PDW")
|| info.GetAmmoType() == GetAmmoDef()->Index("ASW_SG"))
newInfo.ScaleDamageForce(30.0f);
else if (info.GetAmmoType() == GetAmmoDef()->Index("ASW_ASG"))
newInfo.ScaleDamageForce(35.0f);
// tilt the angle up a bit?
Vector vecForceDir = newInfo.GetDamageForce();
float force = vecForceDir.NormalizeInPlace();
QAngle angForce;
VectorAngles(vecForceDir, angForce);
angForce[PITCH] += asw_drone_death_force_pitch.GetFloat();
AngleVectors(angForce, &vecForceDir);
vecForceDir *= force;
newInfo.SetDamageForce(vecForceDir);
}
trace_t tr;
UTIL_TraceLine( GetAbsOrigin() + Vector( 0, 0, 16 ), GetAbsOrigin() - Vector( 0, 0, 64 ), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr );
UTIL_DecalTrace( &tr, "GreenBloodBig" );
BaseClass::Event_Killed( newInfo );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//-----------------------------------------------------------------------------
bool CASW_Ranger::CorpseGib( const CTakeDamageInfo &info )
{
CEffectData data;
m_LagCompensation.UndoLaggedPosition();
data.m_vOrigin = WorldSpaceCenter();
data.m_vNormal = data.m_vOrigin - info.GetDamagePosition();
VectorNormalize( data.m_vNormal );
data.m_flScale = RemapVal( m_iHealth, 0, -500, 1, 3 );
data.m_flScale = clamp( data.m_flScale, 1, 3 );
data.m_nColor = m_nSkin;
data.m_fFlags = IsOnFire() ? ASW_GIBFLAG_ON_FIRE : 0;
//DispatchEffect( "DroneGib", data );
//CSoundEnt::InsertSound( SOUND_PHYSICS_DANGER, GetAbsOrigin(), 256, 0.5f, this );
//EmitSound( "ASW_Drone.Death" );
return true;
}
//-----------------------------------------------------------------------------
//
// Schedules
//
//-----------------------------------------------------------------------------
AI_BEGIN_CUSTOM_NPC( asw_ranger, CASW_Ranger )
DECLARE_ANIMEVENT( AE_MORTARBUG_LAUNCH )
AI_END_CUSTOM_NPC()
| 29.415512
| 137
| 0.59742
|
BenLubar
|
4c2be4e9576ca2bc4669ef0074a384798ffa82d3
| 216
|
cpp
|
C++
|
Game/Client/WXClient/Network/PacketHandler/CGCharIdleHandler.cpp
|
hackerlank/SourceCode
|
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
|
[
"MIT"
] | 4
|
2021-07-31T13:56:01.000Z
|
2021-11-13T02:55:10.000Z
|
Game/Client/WXClient/Network/PacketHandler/CGCharIdleHandler.cpp
|
shacojx/SourceCodeGameTLBB
|
e3cea615b06761c2098a05427a5f41c236b71bf7
|
[
"MIT"
] | null | null | null |
Game/Client/WXClient/Network/PacketHandler/CGCharIdleHandler.cpp
|
shacojx/SourceCodeGameTLBB
|
e3cea615b06761c2098a05427a5f41c236b71bf7
|
[
"MIT"
] | 7
|
2021-08-31T14:34:23.000Z
|
2022-01-19T08:25:58.000Z
|
#include "StdAfx.h"
#include "CGCharIdle.h"
uint CGCharIdleHandler::Execute( CGCharIdle* pPacket, Player* pPlayer )
{
__ENTER_FUNCTION
return PACKET_EXE_CONTINUE ;
__LEAVE_FUNCTION
return PACKET_EXE_ERROR ;
}
| 14.4
| 71
| 0.782407
|
hackerlank
|
4c2cd17db19478b6b12c2655c87537a49429f4f8
| 549
|
ipp
|
C++
|
include/canard/net/ofp/v10/impl/action_list.ipp
|
amedama41/bulb
|
2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb
|
[
"BSL-1.0"
] | null | null | null |
include/canard/net/ofp/v10/impl/action_list.ipp
|
amedama41/bulb
|
2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb
|
[
"BSL-1.0"
] | 8
|
2016-07-21T11:29:13.000Z
|
2016-12-03T05:16:42.000Z
|
include/canard/net/ofp/v10/impl/action_list.ipp
|
amedama41/bulb
|
2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb
|
[
"BSL-1.0"
] | null | null | null |
#ifndef CANARD_NET_OFP_V10_IMPL_ACTION_LIST_IPP
#define CANARD_NET_OFP_V10_IMPL_ACTION_LIST_IPP
#include <canard/net/ofp/detail/config.hpp>
#include <canard/net/ofp/v10/action_list.hpp>
#if !defined(CANARD_NET_OFP_HEADER_ONLY)
# if defined(CANARD_NET_OFP_USE_EXPLICIT_INSTANTIATION)
# include <canard/net/ofp/list.hpp>
namespace canard {
namespace net {
namespace ofp {
template class list<ofp::v10::any_action>;
} // namespace ofp
} // namespace net
} // namespace canard
# endif
#endif
#endif // CANARD_NET_OFP_V10_IMPL_ACTION_LIST_IPP
| 21.115385
| 55
| 0.794171
|
amedama41
|
4c2f78a49be33e62a5778dcdcffd80d8a51050a2
| 53,243
|
cpp
|
C++
|
code/source/Groups/GroupsDataModels.cpp
|
jasonsandlin/PlayFabCoreCSdk
|
ecf51e9a7a90e579efed595bd1d76ec8f3a1ae19
|
[
"Apache-2.0"
] | null | null | null |
code/source/Groups/GroupsDataModels.cpp
|
jasonsandlin/PlayFabCoreCSdk
|
ecf51e9a7a90e579efed595bd1d76ec8f3a1ae19
|
[
"Apache-2.0"
] | 1
|
2022-03-04T20:50:28.000Z
|
2022-03-04T21:02:12.000Z
|
code/source/Groups/GroupsDataModels.cpp
|
jasonsandlin/PlayFabCoreCSdk
|
ecf51e9a7a90e579efed595bd1d76ec8f3a1ae19
|
[
"Apache-2.0"
] | 3
|
2021-12-04T20:43:04.000Z
|
2022-01-03T21:16:32.000Z
|
#include "stdafx.h"
#include "GroupsDataModels.h"
#include "JsonUtils.h"
namespace PlayFab
{
namespace Groups
{
JsonValue AcceptGroupApplicationRequest::ToJson() const
{
return AcceptGroupApplicationRequest::ToJson(this->Model());
}
JsonValue AcceptGroupApplicationRequest::ToJson(const PFGroupsAcceptGroupApplicationRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Entity", input.entity);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
return output;
}
JsonValue AcceptGroupInvitationRequest::ToJson() const
{
return AcceptGroupInvitationRequest::ToJson(this->Model());
}
JsonValue AcceptGroupInvitationRequest::ToJson(const PFGroupsAcceptGroupInvitationRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Entity", input.entity);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
return output;
}
JsonValue AddMembersRequest::ToJson() const
{
return AddMembersRequest::ToJson(this->Model());
}
JsonValue AddMembersRequest::ToJson(const PFGroupsAddMembersRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
JsonUtils::ObjectAddMemberArray<EntityKey>(output, "Members", input.members, input.membersCount);
JsonUtils::ObjectAddMember(output, "RoleId", input.roleId);
return output;
}
JsonValue ApplyToGroupRequest::ToJson() const
{
return ApplyToGroupRequest::ToJson(this->Model());
}
JsonValue ApplyToGroupRequest::ToJson(const PFGroupsApplyToGroupRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMember(output, "AutoAcceptOutstandingInvite", input.autoAcceptOutstandingInvite);
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Entity", input.entity);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
return output;
}
void EntityWithLineage::FromJson(const JsonValue& input)
{
StdExtra::optional<EntityKey> key{};
JsonUtils::ObjectGetMember(input, "Key", key);
if (key)
{
this->SetKey(std::move(*key));
}
ModelDictionaryEntryVector<EntityKey> lineage{};
JsonUtils::ObjectGetMember<EntityKey>(input, "Lineage", lineage);
this->SetLineage(std::move(lineage));
}
size_t EntityWithLineage::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsEntityWithLineage const*> EntityWithLineage::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<EntityWithLineage>(&this->Model());
}
size_t EntityWithLineage::RequiredBufferSize(const PFGroupsEntityWithLineage& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
if (model.key)
{
requiredSize += EntityKey::RequiredBufferSize(*model.key);
}
requiredSize += (alignof(PFEntityKeyDictionaryEntry) + sizeof(PFEntityKeyDictionaryEntry) * model.lineageCount);
for (size_t i = 0; i < model.lineageCount; ++i)
{
requiredSize += (std::strlen(model.lineage[i].key) + 1);
requiredSize += EntityKey::RequiredBufferSize(*model.lineage[i].value);
}
return requiredSize;
}
HRESULT EntityWithLineage::Copy(const PFGroupsEntityWithLineage& input, PFGroupsEntityWithLineage& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyTo<EntityKey>(input.key);
RETURN_IF_FAILED(propCopyResult.hr);
output.key = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyToDictionary<EntityKey>(input.lineage, input.lineageCount);
RETURN_IF_FAILED(propCopyResult.hr);
output.lineage = propCopyResult.ExtractPayload();
}
return S_OK;
}
void ApplyToGroupResponse::FromJson(const JsonValue& input)
{
StdExtra::optional<EntityWithLineage> entity{};
JsonUtils::ObjectGetMember(input, "Entity", entity);
if (entity)
{
this->SetEntity(std::move(*entity));
}
JsonUtils::ObjectGetMemberTime(input, "Expires", this->m_model.expires);
StdExtra::optional<EntityKey> group{};
JsonUtils::ObjectGetMember(input, "Group", group);
if (group)
{
this->SetGroup(std::move(*group));
}
}
size_t ApplyToGroupResponse::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsApplyToGroupResponse const*> ApplyToGroupResponse::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<ApplyToGroupResponse>(&this->Model());
}
size_t ApplyToGroupResponse::RequiredBufferSize(const PFGroupsApplyToGroupResponse& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
if (model.entity)
{
requiredSize += EntityWithLineage::RequiredBufferSize(*model.entity);
}
if (model.group)
{
requiredSize += EntityKey::RequiredBufferSize(*model.group);
}
return requiredSize;
}
HRESULT ApplyToGroupResponse::Copy(const PFGroupsApplyToGroupResponse& input, PFGroupsApplyToGroupResponse& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyTo<EntityWithLineage>(input.entity);
RETURN_IF_FAILED(propCopyResult.hr);
output.entity = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo<EntityKey>(input.group);
RETURN_IF_FAILED(propCopyResult.hr);
output.group = propCopyResult.ExtractPayload();
}
return S_OK;
}
JsonValue BlockEntityRequest::ToJson() const
{
return BlockEntityRequest::ToJson(this->Model());
}
JsonValue BlockEntityRequest::ToJson(const PFGroupsBlockEntityRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Entity", input.entity);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
return output;
}
JsonValue ChangeMemberRoleRequest::ToJson() const
{
return ChangeMemberRoleRequest::ToJson(this->Model());
}
JsonValue ChangeMemberRoleRequest::ToJson(const PFGroupsChangeMemberRoleRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember(output, "DestinationRoleId", input.destinationRoleId);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
JsonUtils::ObjectAddMemberArray<EntityKey>(output, "Members", input.members, input.membersCount);
JsonUtils::ObjectAddMember(output, "OriginRoleId", input.originRoleId);
return output;
}
JsonValue CreateGroupRequest::ToJson() const
{
return CreateGroupRequest::ToJson(this->Model());
}
JsonValue CreateGroupRequest::ToJson(const PFGroupsCreateGroupRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Entity", input.entity);
JsonUtils::ObjectAddMember(output, "GroupName", input.groupName);
return output;
}
void CreateGroupResponse::FromJson(const JsonValue& input)
{
String adminRoleId{};
JsonUtils::ObjectGetMember(input, "AdminRoleId", adminRoleId);
this->SetAdminRoleId(std::move(adminRoleId));
JsonUtils::ObjectGetMemberTime(input, "Created", this->m_model.created);
EntityKey group{};
JsonUtils::ObjectGetMember(input, "Group", group);
this->SetGroup(std::move(group));
String groupName{};
JsonUtils::ObjectGetMember(input, "GroupName", groupName);
this->SetGroupName(std::move(groupName));
String memberRoleId{};
JsonUtils::ObjectGetMember(input, "MemberRoleId", memberRoleId);
this->SetMemberRoleId(std::move(memberRoleId));
JsonUtils::ObjectGetMember(input, "ProfileVersion", this->m_model.profileVersion);
StringDictionaryEntryVector roles{};
JsonUtils::ObjectGetMember(input, "Roles", roles);
this->SetRoles(std::move(roles));
}
size_t CreateGroupResponse::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsCreateGroupResponse const*> CreateGroupResponse::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<CreateGroupResponse>(&this->Model());
}
size_t CreateGroupResponse::RequiredBufferSize(const PFGroupsCreateGroupResponse& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
if (model.adminRoleId)
{
requiredSize += (std::strlen(model.adminRoleId) + 1);
}
if (model.group)
{
requiredSize += EntityKey::RequiredBufferSize(*model.group);
}
if (model.groupName)
{
requiredSize += (std::strlen(model.groupName) + 1);
}
if (model.memberRoleId)
{
requiredSize += (std::strlen(model.memberRoleId) + 1);
}
requiredSize += (alignof(PFStringDictionaryEntry) + sizeof(PFStringDictionaryEntry) * model.rolesCount);
for (size_t i = 0; i < model.rolesCount; ++i)
{
requiredSize += (std::strlen(model.roles[i].key) + 1);
requiredSize += (std::strlen(model.roles[i].value) + 1);
}
return requiredSize;
}
HRESULT CreateGroupResponse::Copy(const PFGroupsCreateGroupResponse& input, PFGroupsCreateGroupResponse& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyTo(input.adminRoleId);
RETURN_IF_FAILED(propCopyResult.hr);
output.adminRoleId = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo<EntityKey>(input.group);
RETURN_IF_FAILED(propCopyResult.hr);
output.group = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo(input.groupName);
RETURN_IF_FAILED(propCopyResult.hr);
output.groupName = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo(input.memberRoleId);
RETURN_IF_FAILED(propCopyResult.hr);
output.memberRoleId = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyToDictionary(input.roles, input.rolesCount);
RETURN_IF_FAILED(propCopyResult.hr);
output.roles = propCopyResult.ExtractPayload();
}
return S_OK;
}
JsonValue CreateGroupRoleRequest::ToJson() const
{
return CreateGroupRoleRequest::ToJson(this->Model());
}
JsonValue CreateGroupRoleRequest::ToJson(const PFGroupsCreateGroupRoleRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
JsonUtils::ObjectAddMember(output, "RoleId", input.roleId);
JsonUtils::ObjectAddMember(output, "RoleName", input.roleName);
return output;
}
void CreateGroupRoleResponse::FromJson(const JsonValue& input)
{
JsonUtils::ObjectGetMember(input, "ProfileVersion", this->m_model.profileVersion);
String roleId{};
JsonUtils::ObjectGetMember(input, "RoleId", roleId);
this->SetRoleId(std::move(roleId));
String roleName{};
JsonUtils::ObjectGetMember(input, "RoleName", roleName);
this->SetRoleName(std::move(roleName));
}
size_t CreateGroupRoleResponse::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsCreateGroupRoleResponse const*> CreateGroupRoleResponse::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<CreateGroupRoleResponse>(&this->Model());
}
size_t CreateGroupRoleResponse::RequiredBufferSize(const PFGroupsCreateGroupRoleResponse& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
if (model.roleId)
{
requiredSize += (std::strlen(model.roleId) + 1);
}
if (model.roleName)
{
requiredSize += (std::strlen(model.roleName) + 1);
}
return requiredSize;
}
HRESULT CreateGroupRoleResponse::Copy(const PFGroupsCreateGroupRoleResponse& input, PFGroupsCreateGroupRoleResponse& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyTo(input.roleId);
RETURN_IF_FAILED(propCopyResult.hr);
output.roleId = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo(input.roleName);
RETURN_IF_FAILED(propCopyResult.hr);
output.roleName = propCopyResult.ExtractPayload();
}
return S_OK;
}
JsonValue DeleteGroupRequest::ToJson() const
{
return DeleteGroupRequest::ToJson(this->Model());
}
JsonValue DeleteGroupRequest::ToJson(const PFGroupsDeleteGroupRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
return output;
}
JsonValue DeleteRoleRequest::ToJson() const
{
return DeleteRoleRequest::ToJson(this->Model());
}
JsonValue DeleteRoleRequest::ToJson(const PFGroupsDeleteRoleRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
JsonUtils::ObjectAddMember(output, "RoleId", input.roleId);
return output;
}
JsonValue GetGroupRequest::ToJson() const
{
return GetGroupRequest::ToJson(this->Model());
}
JsonValue GetGroupRequest::ToJson(const PFGroupsGetGroupRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
JsonUtils::ObjectAddMember(output, "GroupName", input.groupName);
return output;
}
void GetGroupResponse::FromJson(const JsonValue& input)
{
String adminRoleId{};
JsonUtils::ObjectGetMember(input, "AdminRoleId", adminRoleId);
this->SetAdminRoleId(std::move(adminRoleId));
JsonUtils::ObjectGetMemberTime(input, "Created", this->m_model.created);
EntityKey group{};
JsonUtils::ObjectGetMember(input, "Group", group);
this->SetGroup(std::move(group));
String groupName{};
JsonUtils::ObjectGetMember(input, "GroupName", groupName);
this->SetGroupName(std::move(groupName));
String memberRoleId{};
JsonUtils::ObjectGetMember(input, "MemberRoleId", memberRoleId);
this->SetMemberRoleId(std::move(memberRoleId));
JsonUtils::ObjectGetMember(input, "ProfileVersion", this->m_model.profileVersion);
StringDictionaryEntryVector roles{};
JsonUtils::ObjectGetMember(input, "Roles", roles);
this->SetRoles(std::move(roles));
}
size_t GetGroupResponse::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsGetGroupResponse const*> GetGroupResponse::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<GetGroupResponse>(&this->Model());
}
size_t GetGroupResponse::RequiredBufferSize(const PFGroupsGetGroupResponse& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
if (model.adminRoleId)
{
requiredSize += (std::strlen(model.adminRoleId) + 1);
}
if (model.group)
{
requiredSize += EntityKey::RequiredBufferSize(*model.group);
}
if (model.groupName)
{
requiredSize += (std::strlen(model.groupName) + 1);
}
if (model.memberRoleId)
{
requiredSize += (std::strlen(model.memberRoleId) + 1);
}
requiredSize += (alignof(PFStringDictionaryEntry) + sizeof(PFStringDictionaryEntry) * model.rolesCount);
for (size_t i = 0; i < model.rolesCount; ++i)
{
requiredSize += (std::strlen(model.roles[i].key) + 1);
requiredSize += (std::strlen(model.roles[i].value) + 1);
}
return requiredSize;
}
HRESULT GetGroupResponse::Copy(const PFGroupsGetGroupResponse& input, PFGroupsGetGroupResponse& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyTo(input.adminRoleId);
RETURN_IF_FAILED(propCopyResult.hr);
output.adminRoleId = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo<EntityKey>(input.group);
RETURN_IF_FAILED(propCopyResult.hr);
output.group = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo(input.groupName);
RETURN_IF_FAILED(propCopyResult.hr);
output.groupName = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo(input.memberRoleId);
RETURN_IF_FAILED(propCopyResult.hr);
output.memberRoleId = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyToDictionary(input.roles, input.rolesCount);
RETURN_IF_FAILED(propCopyResult.hr);
output.roles = propCopyResult.ExtractPayload();
}
return S_OK;
}
JsonValue InviteToGroupRequest::ToJson() const
{
return InviteToGroupRequest::ToJson(this->Model());
}
JsonValue InviteToGroupRequest::ToJson(const PFGroupsInviteToGroupRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMember(output, "AutoAcceptOutstandingApplication", input.autoAcceptOutstandingApplication);
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Entity", input.entity);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
JsonUtils::ObjectAddMember(output, "RoleId", input.roleId);
return output;
}
void InviteToGroupResponse::FromJson(const JsonValue& input)
{
JsonUtils::ObjectGetMemberTime(input, "Expires", this->m_model.expires);
StdExtra::optional<EntityKey> group{};
JsonUtils::ObjectGetMember(input, "Group", group);
if (group)
{
this->SetGroup(std::move(*group));
}
StdExtra::optional<EntityWithLineage> invitedByEntity{};
JsonUtils::ObjectGetMember(input, "InvitedByEntity", invitedByEntity);
if (invitedByEntity)
{
this->SetInvitedByEntity(std::move(*invitedByEntity));
}
StdExtra::optional<EntityWithLineage> invitedEntity{};
JsonUtils::ObjectGetMember(input, "InvitedEntity", invitedEntity);
if (invitedEntity)
{
this->SetInvitedEntity(std::move(*invitedEntity));
}
String roleId{};
JsonUtils::ObjectGetMember(input, "RoleId", roleId);
this->SetRoleId(std::move(roleId));
}
size_t InviteToGroupResponse::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsInviteToGroupResponse const*> InviteToGroupResponse::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<InviteToGroupResponse>(&this->Model());
}
size_t InviteToGroupResponse::RequiredBufferSize(const PFGroupsInviteToGroupResponse& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
if (model.group)
{
requiredSize += EntityKey::RequiredBufferSize(*model.group);
}
if (model.invitedByEntity)
{
requiredSize += EntityWithLineage::RequiredBufferSize(*model.invitedByEntity);
}
if (model.invitedEntity)
{
requiredSize += EntityWithLineage::RequiredBufferSize(*model.invitedEntity);
}
if (model.roleId)
{
requiredSize += (std::strlen(model.roleId) + 1);
}
return requiredSize;
}
HRESULT InviteToGroupResponse::Copy(const PFGroupsInviteToGroupResponse& input, PFGroupsInviteToGroupResponse& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyTo<EntityKey>(input.group);
RETURN_IF_FAILED(propCopyResult.hr);
output.group = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo<EntityWithLineage>(input.invitedByEntity);
RETURN_IF_FAILED(propCopyResult.hr);
output.invitedByEntity = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo<EntityWithLineage>(input.invitedEntity);
RETURN_IF_FAILED(propCopyResult.hr);
output.invitedEntity = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo(input.roleId);
RETURN_IF_FAILED(propCopyResult.hr);
output.roleId = propCopyResult.ExtractPayload();
}
return S_OK;
}
JsonValue IsMemberRequest::ToJson() const
{
return IsMemberRequest::ToJson(this->Model());
}
JsonValue IsMemberRequest::ToJson(const PFGroupsIsMemberRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Entity", input.entity);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
JsonUtils::ObjectAddMember(output, "RoleId", input.roleId);
return output;
}
void IsMemberResponse::FromJson(const JsonValue& input)
{
JsonUtils::ObjectGetMember(input, "IsMember", this->m_model.isMember);
}
size_t IsMemberResponse::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsIsMemberResponse const*> IsMemberResponse::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<IsMemberResponse>(&this->Model());
}
size_t IsMemberResponse::RequiredBufferSize(const PFGroupsIsMemberResponse& model)
{
UNREFERENCED_PARAMETER(model); // Fixed size
return sizeof(ModelType);
}
HRESULT IsMemberResponse::Copy(const PFGroupsIsMemberResponse& input, PFGroupsIsMemberResponse& output, ModelBuffer& buffer)
{
output = input;
UNREFERENCED_PARAMETER(buffer); // Fixed size
return S_OK;
}
JsonValue ListGroupApplicationsRequest::ToJson() const
{
return ListGroupApplicationsRequest::ToJson(this->Model());
}
JsonValue ListGroupApplicationsRequest::ToJson(const PFGroupsListGroupApplicationsRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
return output;
}
void GroupApplication::FromJson(const JsonValue& input)
{
StdExtra::optional<EntityWithLineage> entity{};
JsonUtils::ObjectGetMember(input, "Entity", entity);
if (entity)
{
this->SetEntity(std::move(*entity));
}
JsonUtils::ObjectGetMemberTime(input, "Expires", this->m_model.expires);
StdExtra::optional<EntityKey> group{};
JsonUtils::ObjectGetMember(input, "Group", group);
if (group)
{
this->SetGroup(std::move(*group));
}
}
size_t GroupApplication::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsGroupApplication const*> GroupApplication::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<GroupApplication>(&this->Model());
}
size_t GroupApplication::RequiredBufferSize(const PFGroupsGroupApplication& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
if (model.entity)
{
requiredSize += EntityWithLineage::RequiredBufferSize(*model.entity);
}
if (model.group)
{
requiredSize += EntityKey::RequiredBufferSize(*model.group);
}
return requiredSize;
}
HRESULT GroupApplication::Copy(const PFGroupsGroupApplication& input, PFGroupsGroupApplication& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyTo<EntityWithLineage>(input.entity);
RETURN_IF_FAILED(propCopyResult.hr);
output.entity = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo<EntityKey>(input.group);
RETURN_IF_FAILED(propCopyResult.hr);
output.group = propCopyResult.ExtractPayload();
}
return S_OK;
}
void ListGroupApplicationsResponse::FromJson(const JsonValue& input)
{
ModelVector<GroupApplication> applications{};
JsonUtils::ObjectGetMember<GroupApplication>(input, "Applications", applications);
this->SetApplications(std::move(applications));
}
size_t ListGroupApplicationsResponse::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsListGroupApplicationsResponse const*> ListGroupApplicationsResponse::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<ListGroupApplicationsResponse>(&this->Model());
}
size_t ListGroupApplicationsResponse::RequiredBufferSize(const PFGroupsListGroupApplicationsResponse& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
requiredSize += (alignof(PFGroupsGroupApplication*) + sizeof(PFGroupsGroupApplication*) * model.applicationsCount);
for (size_t i = 0; i < model.applicationsCount; ++i)
{
requiredSize += GroupApplication::RequiredBufferSize(*model.applications[i]);
}
return requiredSize;
}
HRESULT ListGroupApplicationsResponse::Copy(const PFGroupsListGroupApplicationsResponse& input, PFGroupsListGroupApplicationsResponse& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyToArray<GroupApplication>(input.applications, input.applicationsCount);
RETURN_IF_FAILED(propCopyResult.hr);
output.applications = propCopyResult.ExtractPayload();
}
return S_OK;
}
JsonValue ListGroupBlocksRequest::ToJson() const
{
return ListGroupBlocksRequest::ToJson(this->Model());
}
JsonValue ListGroupBlocksRequest::ToJson(const PFGroupsListGroupBlocksRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
return output;
}
void GroupBlock::FromJson(const JsonValue& input)
{
StdExtra::optional<EntityWithLineage> entity{};
JsonUtils::ObjectGetMember(input, "Entity", entity);
if (entity)
{
this->SetEntity(std::move(*entity));
}
EntityKey group{};
JsonUtils::ObjectGetMember(input, "Group", group);
this->SetGroup(std::move(group));
}
size_t GroupBlock::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsGroupBlock const*> GroupBlock::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<GroupBlock>(&this->Model());
}
size_t GroupBlock::RequiredBufferSize(const PFGroupsGroupBlock& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
if (model.entity)
{
requiredSize += EntityWithLineage::RequiredBufferSize(*model.entity);
}
if (model.group)
{
requiredSize += EntityKey::RequiredBufferSize(*model.group);
}
return requiredSize;
}
HRESULT GroupBlock::Copy(const PFGroupsGroupBlock& input, PFGroupsGroupBlock& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyTo<EntityWithLineage>(input.entity);
RETURN_IF_FAILED(propCopyResult.hr);
output.entity = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo<EntityKey>(input.group);
RETURN_IF_FAILED(propCopyResult.hr);
output.group = propCopyResult.ExtractPayload();
}
return S_OK;
}
void ListGroupBlocksResponse::FromJson(const JsonValue& input)
{
ModelVector<GroupBlock> blockedEntities{};
JsonUtils::ObjectGetMember<GroupBlock>(input, "BlockedEntities", blockedEntities);
this->SetBlockedEntities(std::move(blockedEntities));
}
size_t ListGroupBlocksResponse::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsListGroupBlocksResponse const*> ListGroupBlocksResponse::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<ListGroupBlocksResponse>(&this->Model());
}
size_t ListGroupBlocksResponse::RequiredBufferSize(const PFGroupsListGroupBlocksResponse& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
requiredSize += (alignof(PFGroupsGroupBlock*) + sizeof(PFGroupsGroupBlock*) * model.blockedEntitiesCount);
for (size_t i = 0; i < model.blockedEntitiesCount; ++i)
{
requiredSize += GroupBlock::RequiredBufferSize(*model.blockedEntities[i]);
}
return requiredSize;
}
HRESULT ListGroupBlocksResponse::Copy(const PFGroupsListGroupBlocksResponse& input, PFGroupsListGroupBlocksResponse& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyToArray<GroupBlock>(input.blockedEntities, input.blockedEntitiesCount);
RETURN_IF_FAILED(propCopyResult.hr);
output.blockedEntities = propCopyResult.ExtractPayload();
}
return S_OK;
}
JsonValue ListGroupInvitationsRequest::ToJson() const
{
return ListGroupInvitationsRequest::ToJson(this->Model());
}
JsonValue ListGroupInvitationsRequest::ToJson(const PFGroupsListGroupInvitationsRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
return output;
}
void GroupInvitation::FromJson(const JsonValue& input)
{
JsonUtils::ObjectGetMemberTime(input, "Expires", this->m_model.expires);
StdExtra::optional<EntityKey> group{};
JsonUtils::ObjectGetMember(input, "Group", group);
if (group)
{
this->SetGroup(std::move(*group));
}
StdExtra::optional<EntityWithLineage> invitedByEntity{};
JsonUtils::ObjectGetMember(input, "InvitedByEntity", invitedByEntity);
if (invitedByEntity)
{
this->SetInvitedByEntity(std::move(*invitedByEntity));
}
StdExtra::optional<EntityWithLineage> invitedEntity{};
JsonUtils::ObjectGetMember(input, "InvitedEntity", invitedEntity);
if (invitedEntity)
{
this->SetInvitedEntity(std::move(*invitedEntity));
}
String roleId{};
JsonUtils::ObjectGetMember(input, "RoleId", roleId);
this->SetRoleId(std::move(roleId));
}
size_t GroupInvitation::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsGroupInvitation const*> GroupInvitation::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<GroupInvitation>(&this->Model());
}
size_t GroupInvitation::RequiredBufferSize(const PFGroupsGroupInvitation& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
if (model.group)
{
requiredSize += EntityKey::RequiredBufferSize(*model.group);
}
if (model.invitedByEntity)
{
requiredSize += EntityWithLineage::RequiredBufferSize(*model.invitedByEntity);
}
if (model.invitedEntity)
{
requiredSize += EntityWithLineage::RequiredBufferSize(*model.invitedEntity);
}
if (model.roleId)
{
requiredSize += (std::strlen(model.roleId) + 1);
}
return requiredSize;
}
HRESULT GroupInvitation::Copy(const PFGroupsGroupInvitation& input, PFGroupsGroupInvitation& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyTo<EntityKey>(input.group);
RETURN_IF_FAILED(propCopyResult.hr);
output.group = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo<EntityWithLineage>(input.invitedByEntity);
RETURN_IF_FAILED(propCopyResult.hr);
output.invitedByEntity = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo<EntityWithLineage>(input.invitedEntity);
RETURN_IF_FAILED(propCopyResult.hr);
output.invitedEntity = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo(input.roleId);
RETURN_IF_FAILED(propCopyResult.hr);
output.roleId = propCopyResult.ExtractPayload();
}
return S_OK;
}
void ListGroupInvitationsResponse::FromJson(const JsonValue& input)
{
ModelVector<GroupInvitation> invitations{};
JsonUtils::ObjectGetMember<GroupInvitation>(input, "Invitations", invitations);
this->SetInvitations(std::move(invitations));
}
size_t ListGroupInvitationsResponse::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsListGroupInvitationsResponse const*> ListGroupInvitationsResponse::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<ListGroupInvitationsResponse>(&this->Model());
}
size_t ListGroupInvitationsResponse::RequiredBufferSize(const PFGroupsListGroupInvitationsResponse& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
requiredSize += (alignof(PFGroupsGroupInvitation*) + sizeof(PFGroupsGroupInvitation*) * model.invitationsCount);
for (size_t i = 0; i < model.invitationsCount; ++i)
{
requiredSize += GroupInvitation::RequiredBufferSize(*model.invitations[i]);
}
return requiredSize;
}
HRESULT ListGroupInvitationsResponse::Copy(const PFGroupsListGroupInvitationsResponse& input, PFGroupsListGroupInvitationsResponse& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyToArray<GroupInvitation>(input.invitations, input.invitationsCount);
RETURN_IF_FAILED(propCopyResult.hr);
output.invitations = propCopyResult.ExtractPayload();
}
return S_OK;
}
JsonValue ListGroupMembersRequest::ToJson() const
{
return ListGroupMembersRequest::ToJson(this->Model());
}
JsonValue ListGroupMembersRequest::ToJson(const PFGroupsListGroupMembersRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
return output;
}
void EntityMemberRole::FromJson(const JsonValue& input)
{
ModelVector<EntityWithLineage> members{};
JsonUtils::ObjectGetMember<EntityWithLineage>(input, "Members", members);
this->SetMembers(std::move(members));
String roleId{};
JsonUtils::ObjectGetMember(input, "RoleId", roleId);
this->SetRoleId(std::move(roleId));
String roleName{};
JsonUtils::ObjectGetMember(input, "RoleName", roleName);
this->SetRoleName(std::move(roleName));
}
size_t EntityMemberRole::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsEntityMemberRole const*> EntityMemberRole::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<EntityMemberRole>(&this->Model());
}
size_t EntityMemberRole::RequiredBufferSize(const PFGroupsEntityMemberRole& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
requiredSize += (alignof(PFGroupsEntityWithLineage*) + sizeof(PFGroupsEntityWithLineage*) * model.membersCount);
for (size_t i = 0; i < model.membersCount; ++i)
{
requiredSize += EntityWithLineage::RequiredBufferSize(*model.members[i]);
}
if (model.roleId)
{
requiredSize += (std::strlen(model.roleId) + 1);
}
if (model.roleName)
{
requiredSize += (std::strlen(model.roleName) + 1);
}
return requiredSize;
}
HRESULT EntityMemberRole::Copy(const PFGroupsEntityMemberRole& input, PFGroupsEntityMemberRole& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyToArray<EntityWithLineage>(input.members, input.membersCount);
RETURN_IF_FAILED(propCopyResult.hr);
output.members = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo(input.roleId);
RETURN_IF_FAILED(propCopyResult.hr);
output.roleId = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo(input.roleName);
RETURN_IF_FAILED(propCopyResult.hr);
output.roleName = propCopyResult.ExtractPayload();
}
return S_OK;
}
void ListGroupMembersResponse::FromJson(const JsonValue& input)
{
ModelVector<EntityMemberRole> members{};
JsonUtils::ObjectGetMember<EntityMemberRole>(input, "Members", members);
this->SetMembers(std::move(members));
}
size_t ListGroupMembersResponse::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsListGroupMembersResponse const*> ListGroupMembersResponse::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<ListGroupMembersResponse>(&this->Model());
}
size_t ListGroupMembersResponse::RequiredBufferSize(const PFGroupsListGroupMembersResponse& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
requiredSize += (alignof(PFGroupsEntityMemberRole*) + sizeof(PFGroupsEntityMemberRole*) * model.membersCount);
for (size_t i = 0; i < model.membersCount; ++i)
{
requiredSize += EntityMemberRole::RequiredBufferSize(*model.members[i]);
}
return requiredSize;
}
HRESULT ListGroupMembersResponse::Copy(const PFGroupsListGroupMembersResponse& input, PFGroupsListGroupMembersResponse& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyToArray<EntityMemberRole>(input.members, input.membersCount);
RETURN_IF_FAILED(propCopyResult.hr);
output.members = propCopyResult.ExtractPayload();
}
return S_OK;
}
JsonValue ListMembershipRequest::ToJson() const
{
return ListMembershipRequest::ToJson(this->Model());
}
JsonValue ListMembershipRequest::ToJson(const PFGroupsListMembershipRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Entity", input.entity);
return output;
}
void GroupRole::FromJson(const JsonValue& input)
{
String roleId{};
JsonUtils::ObjectGetMember(input, "RoleId", roleId);
this->SetRoleId(std::move(roleId));
String roleName{};
JsonUtils::ObjectGetMember(input, "RoleName", roleName);
this->SetRoleName(std::move(roleName));
}
size_t GroupRole::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsGroupRole const*> GroupRole::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<GroupRole>(&this->Model());
}
size_t GroupRole::RequiredBufferSize(const PFGroupsGroupRole& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
if (model.roleId)
{
requiredSize += (std::strlen(model.roleId) + 1);
}
if (model.roleName)
{
requiredSize += (std::strlen(model.roleName) + 1);
}
return requiredSize;
}
HRESULT GroupRole::Copy(const PFGroupsGroupRole& input, PFGroupsGroupRole& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyTo(input.roleId);
RETURN_IF_FAILED(propCopyResult.hr);
output.roleId = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo(input.roleName);
RETURN_IF_FAILED(propCopyResult.hr);
output.roleName = propCopyResult.ExtractPayload();
}
return S_OK;
}
void GroupWithRoles::FromJson(const JsonValue& input)
{
StdExtra::optional<EntityKey> group{};
JsonUtils::ObjectGetMember(input, "Group", group);
if (group)
{
this->SetGroup(std::move(*group));
}
String groupName{};
JsonUtils::ObjectGetMember(input, "GroupName", groupName);
this->SetGroupName(std::move(groupName));
JsonUtils::ObjectGetMember(input, "ProfileVersion", this->m_model.profileVersion);
ModelVector<GroupRole> roles{};
JsonUtils::ObjectGetMember<GroupRole>(input, "Roles", roles);
this->SetRoles(std::move(roles));
}
size_t GroupWithRoles::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsGroupWithRoles const*> GroupWithRoles::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<GroupWithRoles>(&this->Model());
}
size_t GroupWithRoles::RequiredBufferSize(const PFGroupsGroupWithRoles& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
if (model.group)
{
requiredSize += EntityKey::RequiredBufferSize(*model.group);
}
if (model.groupName)
{
requiredSize += (std::strlen(model.groupName) + 1);
}
requiredSize += (alignof(PFGroupsGroupRole*) + sizeof(PFGroupsGroupRole*) * model.rolesCount);
for (size_t i = 0; i < model.rolesCount; ++i)
{
requiredSize += GroupRole::RequiredBufferSize(*model.roles[i]);
}
return requiredSize;
}
HRESULT GroupWithRoles::Copy(const PFGroupsGroupWithRoles& input, PFGroupsGroupWithRoles& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyTo<EntityKey>(input.group);
RETURN_IF_FAILED(propCopyResult.hr);
output.group = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo(input.groupName);
RETURN_IF_FAILED(propCopyResult.hr);
output.groupName = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyToArray<GroupRole>(input.roles, input.rolesCount);
RETURN_IF_FAILED(propCopyResult.hr);
output.roles = propCopyResult.ExtractPayload();
}
return S_OK;
}
void ListMembershipResponse::FromJson(const JsonValue& input)
{
ModelVector<GroupWithRoles> groups{};
JsonUtils::ObjectGetMember<GroupWithRoles>(input, "Groups", groups);
this->SetGroups(std::move(groups));
}
size_t ListMembershipResponse::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsListMembershipResponse const*> ListMembershipResponse::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<ListMembershipResponse>(&this->Model());
}
size_t ListMembershipResponse::RequiredBufferSize(const PFGroupsListMembershipResponse& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
requiredSize += (alignof(PFGroupsGroupWithRoles*) + sizeof(PFGroupsGroupWithRoles*) * model.groupsCount);
for (size_t i = 0; i < model.groupsCount; ++i)
{
requiredSize += GroupWithRoles::RequiredBufferSize(*model.groups[i]);
}
return requiredSize;
}
HRESULT ListMembershipResponse::Copy(const PFGroupsListMembershipResponse& input, PFGroupsListMembershipResponse& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyToArray<GroupWithRoles>(input.groups, input.groupsCount);
RETURN_IF_FAILED(propCopyResult.hr);
output.groups = propCopyResult.ExtractPayload();
}
return S_OK;
}
JsonValue ListMembershipOpportunitiesRequest::ToJson() const
{
return ListMembershipOpportunitiesRequest::ToJson(this->Model());
}
JsonValue ListMembershipOpportunitiesRequest::ToJson(const PFGroupsListMembershipOpportunitiesRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Entity", input.entity);
return output;
}
void ListMembershipOpportunitiesResponse::FromJson(const JsonValue& input)
{
ModelVector<GroupApplication> applications{};
JsonUtils::ObjectGetMember<GroupApplication>(input, "Applications", applications);
this->SetApplications(std::move(applications));
ModelVector<GroupInvitation> invitations{};
JsonUtils::ObjectGetMember<GroupInvitation>(input, "Invitations", invitations);
this->SetInvitations(std::move(invitations));
}
size_t ListMembershipOpportunitiesResponse::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsListMembershipOpportunitiesResponse const*> ListMembershipOpportunitiesResponse::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<ListMembershipOpportunitiesResponse>(&this->Model());
}
size_t ListMembershipOpportunitiesResponse::RequiredBufferSize(const PFGroupsListMembershipOpportunitiesResponse& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
requiredSize += (alignof(PFGroupsGroupApplication*) + sizeof(PFGroupsGroupApplication*) * model.applicationsCount);
for (size_t i = 0; i < model.applicationsCount; ++i)
{
requiredSize += GroupApplication::RequiredBufferSize(*model.applications[i]);
}
requiredSize += (alignof(PFGroupsGroupInvitation*) + sizeof(PFGroupsGroupInvitation*) * model.invitationsCount);
for (size_t i = 0; i < model.invitationsCount; ++i)
{
requiredSize += GroupInvitation::RequiredBufferSize(*model.invitations[i]);
}
return requiredSize;
}
HRESULT ListMembershipOpportunitiesResponse::Copy(const PFGroupsListMembershipOpportunitiesResponse& input, PFGroupsListMembershipOpportunitiesResponse& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyToArray<GroupApplication>(input.applications, input.applicationsCount);
RETURN_IF_FAILED(propCopyResult.hr);
output.applications = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyToArray<GroupInvitation>(input.invitations, input.invitationsCount);
RETURN_IF_FAILED(propCopyResult.hr);
output.invitations = propCopyResult.ExtractPayload();
}
return S_OK;
}
JsonValue RemoveGroupApplicationRequest::ToJson() const
{
return RemoveGroupApplicationRequest::ToJson(this->Model());
}
JsonValue RemoveGroupApplicationRequest::ToJson(const PFGroupsRemoveGroupApplicationRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Entity", input.entity);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
return output;
}
JsonValue RemoveGroupInvitationRequest::ToJson() const
{
return RemoveGroupInvitationRequest::ToJson(this->Model());
}
JsonValue RemoveGroupInvitationRequest::ToJson(const PFGroupsRemoveGroupInvitationRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Entity", input.entity);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
return output;
}
JsonValue RemoveMembersRequest::ToJson() const
{
return RemoveMembersRequest::ToJson(this->Model());
}
JsonValue RemoveMembersRequest::ToJson(const PFGroupsRemoveMembersRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
JsonUtils::ObjectAddMemberArray<EntityKey>(output, "Members", input.members, input.membersCount);
JsonUtils::ObjectAddMember(output, "RoleId", input.roleId);
return output;
}
JsonValue UnblockEntityRequest::ToJson() const
{
return UnblockEntityRequest::ToJson(this->Model());
}
JsonValue UnblockEntityRequest::ToJson(const PFGroupsUnblockEntityRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember<EntityKey>(output, "Entity", input.entity);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
return output;
}
JsonValue UpdateGroupRequest::ToJson() const
{
return UpdateGroupRequest::ToJson(this->Model());
}
JsonValue UpdateGroupRequest::ToJson(const PFGroupsUpdateGroupRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMember(output, "AdminRoleId", input.adminRoleId);
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember(output, "ExpectedProfileVersion", input.expectedProfileVersion);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
JsonUtils::ObjectAddMember(output, "GroupName", input.groupName);
JsonUtils::ObjectAddMember(output, "MemberRoleId", input.memberRoleId);
return output;
}
void UpdateGroupResponse::FromJson(const JsonValue& input)
{
String operationReason{};
JsonUtils::ObjectGetMember(input, "OperationReason", operationReason);
this->SetOperationReason(std::move(operationReason));
JsonUtils::ObjectGetMember(input, "ProfileVersion", this->m_model.profileVersion);
StdExtra::optional<PFOperationTypes> setResult{};
JsonUtils::ObjectGetMember(input, "SetResult", setResult);
this->SetSetResult(std::move(setResult));
}
size_t UpdateGroupResponse::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsUpdateGroupResponse const*> UpdateGroupResponse::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<UpdateGroupResponse>(&this->Model());
}
size_t UpdateGroupResponse::RequiredBufferSize(const PFGroupsUpdateGroupResponse& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
if (model.operationReason)
{
requiredSize += (std::strlen(model.operationReason) + 1);
}
if (model.setResult)
{
requiredSize += (alignof(PFOperationTypes) + sizeof(PFOperationTypes));
}
return requiredSize;
}
HRESULT UpdateGroupResponse::Copy(const PFGroupsUpdateGroupResponse& input, PFGroupsUpdateGroupResponse& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyTo(input.operationReason);
RETURN_IF_FAILED(propCopyResult.hr);
output.operationReason = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo(input.setResult);
RETURN_IF_FAILED(propCopyResult.hr);
output.setResult = propCopyResult.ExtractPayload();
}
return S_OK;
}
JsonValue UpdateGroupRoleRequest::ToJson() const
{
return UpdateGroupRoleRequest::ToJson(this->Model());
}
JsonValue UpdateGroupRoleRequest::ToJson(const PFGroupsUpdateGroupRoleRequest& input)
{
JsonValue output{ rapidjson::kObjectType };
JsonUtils::ObjectAddMemberDictionary(output, "CustomTags", input.customTags, input.customTagsCount);
JsonUtils::ObjectAddMember(output, "ExpectedProfileVersion", input.expectedProfileVersion);
JsonUtils::ObjectAddMember<EntityKey>(output, "Group", input.group);
JsonUtils::ObjectAddMember(output, "RoleId", input.roleId);
JsonUtils::ObjectAddMember(output, "RoleName", input.roleName);
return output;
}
void UpdateGroupRoleResponse::FromJson(const JsonValue& input)
{
String operationReason{};
JsonUtils::ObjectGetMember(input, "OperationReason", operationReason);
this->SetOperationReason(std::move(operationReason));
JsonUtils::ObjectGetMember(input, "ProfileVersion", this->m_model.profileVersion);
StdExtra::optional<PFOperationTypes> setResult{};
JsonUtils::ObjectGetMember(input, "SetResult", setResult);
this->SetSetResult(std::move(setResult));
}
size_t UpdateGroupRoleResponse::RequiredBufferSize() const
{
return RequiredBufferSize(this->Model());
}
Result<PFGroupsUpdateGroupRoleResponse const*> UpdateGroupRoleResponse::Copy(ModelBuffer& buffer) const
{
return buffer.CopyTo<UpdateGroupRoleResponse>(&this->Model());
}
size_t UpdateGroupRoleResponse::RequiredBufferSize(const PFGroupsUpdateGroupRoleResponse& model)
{
size_t requiredSize{ alignof(ModelType) + sizeof(ModelType) };
if (model.operationReason)
{
requiredSize += (std::strlen(model.operationReason) + 1);
}
if (model.setResult)
{
requiredSize += (alignof(PFOperationTypes) + sizeof(PFOperationTypes));
}
return requiredSize;
}
HRESULT UpdateGroupRoleResponse::Copy(const PFGroupsUpdateGroupRoleResponse& input, PFGroupsUpdateGroupRoleResponse& output, ModelBuffer& buffer)
{
output = input;
{
auto propCopyResult = buffer.CopyTo(input.operationReason);
RETURN_IF_FAILED(propCopyResult.hr);
output.operationReason = propCopyResult.ExtractPayload();
}
{
auto propCopyResult = buffer.CopyTo(input.setResult);
RETURN_IF_FAILED(propCopyResult.hr);
output.setResult = propCopyResult.ExtractPayload();
}
return S_OK;
}
} // namespace Groups
} // namespace PlayFab
| 33.570618
| 181
| 0.730406
|
jasonsandlin
|
4c334b09ff22c894f1f51cafda30f3ccb7550cbe
| 498
|
cpp
|
C++
|
C++/P9/P9.cpp
|
PuRgE-CoDeE/Euler-Solutions
|
1eaccc1c3c92b80ec5825a4b1e7aa0dcb94f1934
|
[
"Apache-2.0"
] | null | null | null |
C++/P9/P9.cpp
|
PuRgE-CoDeE/Euler-Solutions
|
1eaccc1c3c92b80ec5825a4b1e7aa0dcb94f1934
|
[
"Apache-2.0"
] | null | null | null |
C++/P9/P9.cpp
|
PuRgE-CoDeE/Euler-Solutions
|
1eaccc1c3c92b80ec5825a4b1e7aa0dcb94f1934
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
int tmp,i_sqrt;
double d_sqrt;
for(int i=1;i<500;i++)
{
for(int j=i+1;j<1000-i;j++)
{
tmp=i*i+j*j;
d_sqrt=sqrt(tmp);
i_sqrt=d_sqrt;
if(i_sqrt==d_sqrt)
{
if(i+j+i_sqrt==1000)
{
cout<<i*j*i_sqrt<<endl;
}
}
}
}
return 0;
}
| 17.172414
| 43
| 0.407631
|
PuRgE-CoDeE
|
4c38c32465ab75e6bec98ebdc8fbc1fa76439551
| 14,439
|
cpp
|
C++
|
VGP334/17_HelloSkeletonAnimation/GameState.cpp
|
TheJimmyGod/JimmyGod_Engine
|
b9752c6fbd9db17dc23f03330b5e4537bdcadf8e
|
[
"MIT"
] | null | null | null |
VGP334/17_HelloSkeletonAnimation/GameState.cpp
|
TheJimmyGod/JimmyGod_Engine
|
b9752c6fbd9db17dc23f03330b5e4537bdcadf8e
|
[
"MIT"
] | null | null | null |
VGP334/17_HelloSkeletonAnimation/GameState.cpp
|
TheJimmyGod/JimmyGod_Engine
|
b9752c6fbd9db17dc23f03330b5e4537bdcadf8e
|
[
"MIT"
] | null | null | null |
#include "GameState.h"
#include <ImGui/Inc/imgui.h>
using namespace JimmyGod::Graphics;
using namespace JimmyGod::Input;
using namespace JimmyGod::Math;
namespace
{
void SimpleDrawCamera(const Camera& camera)
{
auto defaultMatView = camera.GetViewMatrix();
Vector3 cameraPosition = camera.GetPosition();
Vector3 cameraRight = { defaultMatView._11, defaultMatView._21, defaultMatView._31 };
Vector3 cameraUp = { defaultMatView._12, defaultMatView._22, defaultMatView._32 };
Vector3 cameraLook = { defaultMatView._13, defaultMatView._23, defaultMatView._33 };
SimpleDraw::AddLine(cameraPosition, cameraPosition + cameraRight, Colors::Red);
SimpleDraw::AddLine(cameraPosition, cameraPosition + cameraUp, Colors::Green);
SimpleDraw::AddLine(cameraPosition, cameraPosition + cameraLook, Colors::Blue);
}
}
void GameState::Initialize()
{
GraphicsSystem::Get()->SetClearColor(Colors::Black);
mDefaultCamera.SetNearPlane(0.1f);
mDefaultCamera.SetFarPlane(500.0f);
mDefaultCamera.SetPosition({ 0.0f, 10.0f, -5.0f });
mDefaultCamera.SetLookAt({ 0.0f, 0.0f, 0.0f });
mDebugCamera.SetNearPlane(0.001f);
mDebugCamera.SetFarPlane(10000.0f);
mDebugCamera.SetPosition({ 0.0f, 2.0f, -5.0f });
mDebugCamera.SetLookAt({ 0.0f, 0.0f, 0.0f });
mLightCamera.SetDirection(Normalize({ 1.0f, -1.0f, 1.0f }));
mLightCamera.SetNearPlane(1.0f);
mLightCamera.SetFarPlane(200.0f);
mLightCamera.SetFov(1.0f);
mLightCamera.SetAspectRatio(1.0f);
mActiveCamera = &mDefaultCamera;
//mModel.Initialize("../../Assets/Models/Mutant_Walking.model");
mGroundMesh = MeshBuilder::CreatePlane(1500.0f, 16, 16);
mGroundMeshBuffer.Initialize(mGroundMesh);
mTransformBuffer.Initialize();
mLightBuffer.Initialize();
mMaterialBuffer.Initialize();
mSettingsBuffer.Initialize();
mPostProcessingSettingsBuffer.Initialize();
mDirectionalLight.direction = Normalize({ 1.0f, -1.0f, 1.0f });
mDirectionalLight.ambient = { 0.8f, 0.8f, 0.8f, 1.0f };
mDirectionalLight.diffuse = { 0.75f, 0.75f, 0.75f, 1.0f };
mDirectionalLight.specular = { 0.5f, 0.5f, 0.5f, 1.0f };
mMaterial.ambient = { 0.8f, 0.8f, 0.8f, 1.0f };
mMaterial.diffuse = { 0.8f, 0.8f, 0.8f, 1.0f };
mMaterial.specular = { 0.5f, 0.5f, 0.5f, 1.0f };
mMaterial.power = 40.0f;
mSettings.specularMapWeight = 1.0f;
mSettings.bumpMapWeight = 0.0f;
mSettings.normalMapWeight = 0.0f;
mSettings.aoMapWeight = 1.0f;
mSettings.brightness = 3.5f;
mSettings.useShadow = 1;
mSettings.depthBias = 0.0003f;
mVertexShader.Initialize("../../Assets/Shaders/Standard.fx", BoneVertex::Format);
mPixelShader.Initialize("../../Assets/Shaders/Standard.fx");
mSampler.Initialize(Sampler::Filter::Anisotropic, Sampler::AddressMode::Wrap);
mGroundDiffuseMap.Initialize("../../Assets/Textures/grass_2048.jpg");
auto graphicsSystem = GraphicsSystem::Get();
constexpr uint32_t depthMapSize = 4096;
mDepthMapRenderTarget.Initialize(depthMapSize, depthMapSize, RenderTarget::Format::RGBA_U32);
mDepthMapVertexShader.Initialize("../../Assets/Shaders/DepthMap.fx", BoneVertex::Format);
mDepthMapPixelShader.Initialize("../../Assets/Shaders/DepthMap.fx");
mDepthMapConstantBuffer.Initialize();
mShadowConstantBuffer.Initialize();
mRenderTarget.Initialize(
graphicsSystem->GetBackBufferWidth(),
graphicsSystem->GetBackBufferHeight(),
RenderTarget::Format::RGBA_U8);
mScreenQuad = MeshBuilder::CreateNDCQuad();
mScreenQuadBuffer.Initialize(mScreenQuad);
mPostProcessingVertexShader.Initialize("../../Assets/Shaders/PostProcess.fx", VertexPX::Format);
mPostProcessingPixelShader.Initialize("../../Assets/Shaders/PostProcess.fx", "PSNoProcessing");
mTerrain.Initialize(20, 20, 1.0f);
mTerrain.SetHeightScale(1.0f);
//mTerrain.LoadHeightMap("../../Assets/HeightMaps/heightmap_200x200.raw");
mBoneTransformBuffer.Initialize();
mAnimator.Initialize(mModel);
mAnimator.ComputeBindPose();
mAnimator.PlayAnimation(0);
mSkyDome.Intialize("../../Assets/Textures/Space.jpg", 3000, 12, 360, mActiveCamera->GetPosition());
}
void GameState::Terminate()
{
mModel.Terminate();
mBoneTransformBuffer.Terminate();
mModel.Terminate();
mTerrain.Terminate();
mPostProcessingPixelShader.Terminate();
mPostProcessingVertexShader.Terminate();
mScreenQuadBuffer.Terminate();
mRenderTarget.Terminate();
mShadowConstantBuffer.Terminate();
mDepthMapConstantBuffer.Terminate();
mDepthMapPixelShader.Terminate();
mDepthMapVertexShader.Terminate();
mDepthMapRenderTarget.Terminate();
mGroundDiffuseMap.Terminate();
mSampler.Terminate();
mPixelShader.Terminate();
mVertexShader.Terminate();
mPostProcessingSettingsBuffer.Terminate();
mSettingsBuffer.Terminate();
mMaterialBuffer.Terminate();
mLightBuffer.Terminate();
mTransformBuffer.Terminate();
mGroundMeshBuffer.Terminate();
mSkyDome.Terminate();
}
void GameState::Update(float deltaTime)
{
auto inputSystem = InputSystem::Get();
const float kMoveSpeed = inputSystem->IsKeyDown(KeyCode::LSHIFT) ? 100.0f : 10.0f;
const float kTurnSpeed = 1.0f;
if (inputSystem->IsKeyDown(KeyCode::W))
mActiveCamera->Walk(kMoveSpeed * deltaTime);
if (inputSystem->IsKeyDown(KeyCode::S))
mActiveCamera->Walk(-kMoveSpeed * deltaTime);
if (inputSystem->IsKeyDown(KeyCode::D))
mActiveCamera->Strafe(kMoveSpeed * deltaTime);
if (inputSystem->IsKeyDown(KeyCode::A))
mActiveCamera->Strafe(-kMoveSpeed * deltaTime);
if (inputSystem->IsMouseDown(MouseButton::RBUTTON))
{
mActiveCamera->Yaw(inputSystem->GetMouseMoveX() * kTurnSpeed * deltaTime);
mActiveCamera->Pitch(inputSystem->GetMouseMoveY() * kTurnSpeed * deltaTime);
}
mPostProcessSettings.time += deltaTime;
mLightCamera.SetDirection(mDirectionalLight.direction);
//mLightCamera.SetPosition(mLightCamera.GetDirection() * -50.0f);
mViewFrustumVertices =
{
// Near plane
{ -1.0f, -1.0f, 0.0f },
{ -1.0f, 1.0f, 0.0f },
{ 1.0f, 1.0f, 0.0f },
{ 1.0f, -1.0f, 0.0f },
// Far plane
{ -1.0f, -1.0f, 1.0f },
{ -1.0f, 1.0f, 1.0f },
{ 1.0f, 1.0f, 1.0f },
{ 1.0f, -1.0f, 1.0f },
};
auto defaultMatView = mDefaultCamera.GetViewMatrix();
auto defaultMatProj = mDefaultCamera.GetPerspectiveMatrix();
auto invViewProj = Inverse(defaultMatView * defaultMatProj);
for (auto& vertex : mViewFrustumVertices)
{
vertex = TransformCoord(vertex, invViewProj);
}
auto lightLook = mLightCamera.GetDirection();
auto lightSide = Normalize(Cross(Vector3::YAxis, lightLook));
auto lightUp = Normalize(Cross(lightLook, lightSide));
float minX = FLT_MAX, maxX = -FLT_MAX;
float minY = FLT_MAX, maxY = -FLT_MAX;
float minZ = FLT_MAX, maxZ = -FLT_MAX;
for (auto& vertex : mViewFrustumVertices)
{
float projectX = Dot(lightSide, vertex);
minX = Min(minX, projectX);
maxX = Max(maxX, projectX);
float projectY = Dot(lightUp, vertex);
minY = Min(minY, projectY);
maxY = Max(maxY, projectY);
float projectZ = Dot(lightLook, vertex);
minZ = Min(minZ, projectZ);
maxZ = Max(maxZ, projectZ);
}
mLightCamera.SetPosition(
lightSide * (minX + maxX) * 0.5f +
lightUp * (minY + maxY) * 0.5f +
lightLook * (minZ + maxZ) * 0.5f
);
mLightCamera.SetNearPlane(minZ - 300.0f);
mLightCamera.SetFarPlane(maxZ);
mLightProjectMatrix = mLightCamera.GetOrthographioMatrix(maxX - minX, maxY - minY);
auto v0 = lightSide * minX + lightUp * minY + lightLook * minZ;
auto v1 = lightSide * minX + lightUp * maxY + lightLook * minZ;
auto v2 = lightSide * maxX + lightUp * maxY + lightLook * minZ;
auto v3 = lightSide * maxX + lightUp * minY + lightLook * minZ;
auto v4 = lightSide * minX + lightUp * minY + lightLook * maxZ;
auto v5 = lightSide * minX + lightUp * maxY + lightLook * maxZ;
auto v6 = lightSide * maxX + lightUp * maxY + lightLook * maxZ;
auto v7 = lightSide * maxX + lightUp * minY + lightLook * maxZ;
SimpleDraw::AddLine(v0, v1, Colors::Yellow);
SimpleDraw::AddLine(v1, v2, Colors::Yellow);
SimpleDraw::AddLine(v2, v3, Colors::Yellow);
SimpleDraw::AddLine(v3, v0, Colors::Yellow);
SimpleDraw::AddLine(v0, v4, Colors::Red);
SimpleDraw::AddLine(v1, v5, Colors::Red);
SimpleDraw::AddLine(v2, v6, Colors::Red);
SimpleDraw::AddLine(v3, v7, Colors::Red);
SimpleDraw::AddLine(v4, v5, Colors::Red);
SimpleDraw::AddLine(v5, v6, Colors::Red);
SimpleDraw::AddLine(v6, v7, Colors::Red);
SimpleDraw::AddLine(v7, v4, Colors::Red);
SimpleDrawCamera(mLightCamera);
fps = 1 / deltaTime;
//if(!stopAnimation)
// mAnimator.Update(deltaTime);
mSkyDome.Update(*mActiveCamera);
}
void GameState::Render()
{
mSkyDome.Render(*mActiveCamera);
mDepthMapRenderTarget.BeginRender();
DrawDepthMap();
mDepthMapRenderTarget.EndRender();
mRenderTarget.BeginRender();
DrawScene();
mRenderTarget.EndRender();
mRenderTarget.BindPS(0);
PostProcess();
mRenderTarget.UnbindPS(0);
}
void GameState::DebugUI()
{
ImGui::Begin("Settings", nullptr, ImGuiWindowFlags_AlwaysAutoResize);
if (ImGui::CollapsingHeader("Animation", ImGuiTreeNodeFlags_DefaultOpen))
{
ImGui::Text("fps: %.2f", fps);
static float mTime = 0.0f;
static float mCurrentTime = mAnimator.GetTime();
//ImGui::SliderFloat("Duration", &mTime, 0.0f, mModel.mAnimationSet.clips[0].get()->duration);
if (mTime > 0.1f && !stopAnimation)
{
mAnimator.StopAnimation(true);
mAnimator.SetTime(mTime);
}
else if(mTime < 0.1f && stopAnimation)
{
mAnimator.StopAnimation(false);
}
if (ImGui::Checkbox("Set Skeleton", &showSkeleton))
{}
if (ImGui::Checkbox("Stop Animation", &stopAnimation))
{
mAnimator.StopAnimation(stopAnimation);
}
}
ImGui::End();
}
void GameState::DrawDepthMap()
{
mDepthMapVertexShader.Bind();
mDepthMapPixelShader.Bind();
auto matViewLight = mLightCamera.GetViewMatrix();
auto matProjLight = mLightProjectMatrix;// mLightCamera.GetPerspectiveMatrix();
mDepthMapConstantBuffer.BindVS(0);
auto matWorld = Matrix4::Scaling(0.01f);
auto wvp = Transpose(matWorld * matViewLight * matProjLight);
mDepthMapConstantBuffer.Update(&wvp);
mModel.Render();
}
void GameState::DrawScene()
{
auto matView = mActiveCamera->GetViewMatrix();
auto matProj = mActiveCamera->GetPerspectiveMatrix();
auto matViewLight = mLightCamera.GetViewMatrix();
auto matProjLight = mLightProjectMatrix;// mLightCamera.GetPerspectiveMatrix();
mLightBuffer.Update(&mDirectionalLight);
mLightBuffer.BindVS(1);
mLightBuffer.BindPS(1);
mMaterialBuffer.Update(&mMaterial);
mMaterialBuffer.BindVS(2);
mMaterialBuffer.BindPS(2);
mSettingsBuffer.Update(&mSettings);
mSettingsBuffer.BindVS(3);
mSettingsBuffer.BindPS(3);
mSampler.BindVS();
mSampler.BindPS();
mVertexShader.Bind();
mPixelShader.Bind();
mTransformBuffer.BindVS(0);
mShadowConstantBuffer.BindVS(4);
mBoneTransformBuffer.BindVS(5);
auto matWorld = Matrix4::Scaling(0.01f) * Matrix4::Translation(startingPos);
TransformData transformData;
transformData.world = Transpose(matWorld);
transformData.wvp = Transpose(matWorld * matView * matProj);
transformData.viewPosition = mActiveCamera->GetPosition();
mTransformBuffer.Update(&transformData);
BoneTransformData boneTransformData{};
for (size_t i = 0; i < mAnimator.GetBoneMatrices().size(); ++i)
{
boneTransformData.BoneTransforms[i] = Transpose(mModel.mSkeleton.bones[i]->offsetTransform * mAnimator.GetBoneMatrices()[i] /** Matrix4::Translation(pos)*/);
}
if(!showSkeleton)
mModel.Render();
else
{
for (auto& b : mModel.mSkeleton.bones)
{
DrawSkeleton(b.get(), mAnimator.GetBoneMatrices(),startingPos, 0.01f);
}
}
auto wvpLight = Transpose(matWorld * matViewLight * matProjLight);
mShadowConstantBuffer.Update(&wvpLight);
mBoneTransformBuffer.Update(&boneTransformData);
auto matWorld2 = Matrix4::Scaling(100.0f) * Matrix4::Translation(Vector3{0.0f,0.0f,0.0f});
TransformData transformData2;
transformData2.world = Transpose(matWorld2);
transformData2.wvp = Transpose(matWorld2 * matView * matProj);
transformData2.viewPosition = mActiveCamera->GetPosition();
mTransformBuffer.Update(&transformData2);
auto wvpLight2 = Transpose(matWorld2 * matViewLight * matProjLight);
mShadowConstantBuffer.Update(&wvpLight2);
mGroundDiffuseMap.BindPS(0);
SettingsData settings;
settings.specularMapWeight = 0.0f;
settings.bumpMapWeight = 0.0f;
settings.normalMapWeight = 0.0f;
settings.aoMapWeight = 0.0f;
settings.useShadow = 1;
mSettingsBuffer.Update(&settings);
mGroundMeshBuffer.Draw();
mTerrain.SetDirectionalLight(mDirectionalLight);
mTerrain.Render(mDefaultCamera);
SimpleDraw::AddLine(mViewFrustumVertices[0], mViewFrustumVertices[1], Colors::White);
SimpleDraw::AddLine(mViewFrustumVertices[1], mViewFrustumVertices[2], Colors::White);
SimpleDraw::AddLine(mViewFrustumVertices[2], mViewFrustumVertices[3], Colors::White);
SimpleDraw::AddLine(mViewFrustumVertices[3], mViewFrustumVertices[0], Colors::White);
SimpleDraw::AddLine(mViewFrustumVertices[0], mViewFrustumVertices[4], Colors::White);
SimpleDraw::AddLine(mViewFrustumVertices[1], mViewFrustumVertices[5], Colors::White);
SimpleDraw::AddLine(mViewFrustumVertices[2], mViewFrustumVertices[6], Colors::White);
SimpleDraw::AddLine(mViewFrustumVertices[3], mViewFrustumVertices[7], Colors::White);
SimpleDraw::AddLine(mViewFrustumVertices[4], mViewFrustumVertices[5], Colors::White);
SimpleDraw::AddLine(mViewFrustumVertices[5], mViewFrustumVertices[6], Colors::White);
SimpleDraw::AddLine(mViewFrustumVertices[6], mViewFrustumVertices[7], Colors::White);
SimpleDraw::AddLine(mViewFrustumVertices[7], mViewFrustumVertices[4], Colors::White);
SimpleDrawCamera(mDefaultCamera);
SimpleDraw::Render(*mActiveCamera);
}
void GameState::PostProcess()
{
mPostProcessingVertexShader.Bind();
mPostProcessingPixelShader.Bind();
mSampler.BindPS();
auto graphicsSystem = GraphicsSystem::Get();
mPostProcessSettings.screenWidth = (float)graphicsSystem->GetBackBufferWidth();
mPostProcessSettings.screenHeight = (float)graphicsSystem->GetBackBufferHeight();
mPostProcessingSettingsBuffer.Update(&mPostProcessSettings);
mPostProcessingSettingsBuffer.BindVS(0);
mPostProcessingSettingsBuffer.BindPS(0);
mScreenQuadBuffer.Draw();
}
| 33.735981
| 160
| 0.724219
|
TheJimmyGod
|
4c3a21d08314f472fa92af7f89c66742a349cb25
| 1,193
|
cpp
|
C++
|
vendor/cybozulib/test/base/thread_test.cpp
|
teamsimplepay/ooxml_crypt
|
8a20790b2f7ec49e98171af0c2be78e8cd241f3e
|
[
"MIT"
] | 48
|
2015-02-06T12:24:25.000Z
|
2021-11-26T15:28:07.000Z
|
vendor/cybozulib/test/base/thread_test.cpp
|
teamsimplepay/ooxml_crypt
|
8a20790b2f7ec49e98171af0c2be78e8cd241f3e
|
[
"MIT"
] | 4
|
2017-09-07T08:32:33.000Z
|
2021-11-29T01:51:41.000Z
|
vendor/cybozulib/test/base/thread_test.cpp
|
teamsimplepay/ooxml_crypt
|
8a20790b2f7ec49e98171af0c2be78e8cd241f3e
|
[
"MIT"
] | 22
|
2015-01-26T10:44:48.000Z
|
2022-02-08T20:36:07.000Z
|
#include <stdio.h>
#include <cybozu/thread.hpp>
#include <cybozu/mutex.hpp>
#include <cybozu/test.hpp>
#include <cybozu/atomic.hpp>
const int N = 1000000;
int s_count = 0;
class ThreadTest : public cybozu::ThreadBase {
cybozu::Mutex& mutex_;
int num_;
public:
ThreadTest(cybozu::Mutex& mutex, int num)
: mutex_(mutex)
, num_(num)
{
printf("make %d\n", num_);
}
void threadEntry()
{
printf("start %d\n", num_);
for (int i = 0; i < N; i++) {
cybozu::AutoLock al(mutex_);
s_count++;
}
printf("end %d\n", num_);
}
};
CYBOZU_TEST_AUTO(cpuNum)
{
int num = cybozu::GetProcessorNum();
CYBOZU_TEST_ASSERT(num > 0);
printf("cpu num=%d\n", num);
}
CYBOZU_TEST_AUTO(autoLock)
{
cybozu::Mutex mutex_;
ThreadTest t1(mutex_, 1);
ThreadTest t2(mutex_, 2);
if (!t1.beginThread()) puts("err thread 1");
if (!t2.beginThread()) puts("err thread 2");
cybozu::Sleep(1000);
/*
verity number of increment
*/
puts("start main");
for (int i = 0; i < N; i++) {
cybozu::AutoLock al(mutex_);
s_count++;
}
puts("end main");
if (!t1.joinThread()) puts("err join 1");
if (!t2.joinThread()) puts("err join 2");
cybozu::mfence();
CYBOZU_TEST_EQUAL(s_count, N * 3);
}
| 18.936508
| 46
| 0.638726
|
teamsimplepay
|
4c42753e8476d34173e823f707d85e329952882e
| 617
|
hpp
|
C++
|
src/planner.hpp
|
a20r/Dodger
|
6e2525f4701031d4e946fcd04c508655fa67c8ea
|
[
"Apache-2.0"
] | 1
|
2021-11-30T11:19:56.000Z
|
2021-11-30T11:19:56.000Z
|
src/planner.hpp
|
a20r/Dodger
|
6e2525f4701031d4e946fcd04c508655fa67c8ea
|
[
"Apache-2.0"
] | null | null | null |
src/planner.hpp
|
a20r/Dodger
|
6e2525f4701031d4e946fcd04c508655fa67c8ea
|
[
"Apache-2.0"
] | null | null | null |
#ifndef PLANNER_H
#define PLANNER_H
#include <list>
#include "agent.hpp"
#include "point.hpp"
#include "roadmap.hpp"
#include "path.hpp"
#include "search.hpp"
using namespace std;
namespace Dodger {
class Planner {
public:
Planner() {};
~Planner() {};
Planner(Search search, list<Agent *> agents,
double goal_radius, double pred_dev);
Path get_path(Point start, Point goal);
private:
Search search;
list<Agent *> agents;
double goal_radius;
double pred_dev;
};
}
#endif
| 18.69697
| 57
| 0.564019
|
a20r
|
4c49c7d064c64dd5ef050247a0e182a7cfac2fc0
| 40,453
|
cpp
|
C++
|
src/termsupport.cpp
|
mseyne/craftos2
|
1e36191ea40864499b54760fe92764fba871eb37
|
[
"MIT"
] | null | null | null |
src/termsupport.cpp
|
mseyne/craftos2
|
1e36191ea40864499b54760fe92764fba871eb37
|
[
"MIT"
] | null | null | null |
src/termsupport.cpp
|
mseyne/craftos2
|
1e36191ea40864499b54760fe92764fba871eb37
|
[
"MIT"
] | null | null | null |
/*
* termsupport.cpp
* CraftOS-PC 2
*
* This file implements some helper functions for terminal interaction.
*
* This code is licensed under the MIT license.
* Copyright (c) 2019-2021 JackMacWindows.
*/
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <chrono>
#include <codecvt>
#include <locale>
#include <queue>
#include <unordered_map>
#include <Computer.hpp>
#include <configuration.hpp>
#ifndef NO_CLI
#include <curses.h>
#endif
#include <Terminal.hpp>
#include "apis.hpp"
#include "runtime.hpp"
#include "peripheral/monitor.hpp"
#include "peripheral/debugger.hpp"
#include "terminal/SDLTerminal.hpp"
#include "termsupport.hpp"
#ifndef NO_CLI
#include "terminal/CLITerminal.hpp"
#endif
#ifdef __ANDROID__
extern "C" {extern int Android_JNI_SetupThread(void);}
#endif
std::thread * renderThread;
/* export */ std::unordered_map<int, unsigned char> keymap = {
{0, 1},
{SDLK_1, 2},
{SDLK_2, 3},
{SDLK_3, 4},
{SDLK_4, 5},
{SDLK_5, 6},
{SDLK_6, 7},
{SDLK_7, 8},
{SDLK_8, 9},
{SDLK_9, 10},
{SDLK_0, 11},
{SDLK_MINUS, 12},
{SDLK_EQUALS, 13},
{SDLK_BACKSPACE, 14},
{SDLK_TAB, 15},
{SDLK_q, 16},
{SDLK_w, 17},
{SDLK_e, 18},
{SDLK_r, 19},
{SDLK_t, 20},
{SDLK_y, 21},
{SDLK_u, 22},
{SDLK_i, 23},
{SDLK_o, 24},
{SDLK_p, 25},
{SDLK_LEFTBRACKET, 26},
{SDLK_RIGHTBRACKET, 27},
{SDLK_RETURN, 28},
{SDLK_LCTRL, 29},
{SDLK_a, 30},
{SDLK_s, 31},
{SDLK_d, 32},
{SDLK_f, 33},
{SDLK_g, 34},
{SDLK_h, 35},
{SDLK_j, 36},
{SDLK_k, 37},
{SDLK_l, 38},
{SDLK_SEMICOLON, 39},
{SDLK_QUOTE, 40},
{SDLK_BACKQUOTE, 41},
{SDLK_LSHIFT, 42},
{SDLK_BACKSLASH, 43},
{SDLK_z, 44},
{SDLK_x, 45},
{SDLK_c, 46},
{SDLK_v, 47},
{SDLK_b, 48},
{SDLK_n, 49},
{SDLK_m, 50},
{SDLK_COMMA, 51},
{SDLK_PERIOD, 52},
{SDLK_SLASH, 53},
{SDLK_RSHIFT, 54},
{SDLK_KP_MULTIPLY, 55},
{SDLK_LALT, 56},
{SDLK_SPACE, 57},
{SDLK_CAPSLOCK, 58},
{SDLK_F1, 59},
{SDLK_F2, 60},
{SDLK_F3, 61},
{SDLK_F4, 62},
{SDLK_F5, 63},
{SDLK_F6, 64},
{SDLK_F7, 65},
{SDLK_F8, 66},
{SDLK_F9, 67},
{SDLK_F10, 68},
{SDLK_NUMLOCKCLEAR, 69},
{SDLK_SCROLLLOCK, 70},
{SDLK_KP_7, 71},
{SDLK_KP_8, 72},
{SDLK_KP_9, 73},
{SDLK_KP_MINUS, 74},
{SDLK_KP_4, 75},
{SDLK_KP_5, 76},
{SDLK_KP_6, 77},
{SDLK_KP_PLUS, 78},
{SDLK_KP_1, 79},
{SDLK_KP_2, 80},
{SDLK_KP_3, 81},
{SDLK_KP_0, 82},
{SDLK_KP_DECIMAL, 83},
{SDLK_F11, 87},
{SDLK_F12, 88},
{SDLK_F13, 100},
{SDLK_F14, 101},
{SDLK_F15, 102},
{SDLK_KP_EQUALS, 141},
{SDLK_KP_AT, 145},
{SDLK_KP_COLON, 146},
{SDLK_STOP, 149},
{SDLK_KP_ENTER, 156},
{SDLK_RCTRL, 157},
{SDLK_KP_COMMA, 179},
{SDLK_KP_DIVIDE, 181},
{SDLK_RALT, 184},
{SDLK_PAUSE, 197},
{SDLK_HOME, 199},
{SDLK_UP, 200},
{SDLK_PAGEUP, 201},
{SDLK_LEFT, 203},
{SDLK_RIGHT, 205},
{SDLK_END, 207},
{SDLK_DOWN, 208},
{SDLK_PAGEDOWN, 209},
{SDLK_INSERT, 210},
{SDLK_DELETE, 211}
};
#ifndef NO_CLI
/* export */ std::unordered_map<int, unsigned char> keymap_cli = {
{'1', 2},
{'2', 3},
{'3', 4},
{'4', 5},
{'5', 6},
{'6', 7},
{'7', 8},
{'8', 9},
{'9', 1},
{'0', 11},
{'-', 12},
{'=', 13},
{KEY_BACKSPACE, 14},
{8, 14},
{0x7F, 14},
{'\t', 15},
{'q', 16},
{'w', 17},
{'e', 18},
{'r', 19},
{'t', 20},
{'y', 21},
{'u', 22},
{'i', 23},
{'o', 24},
{'p', 25},
{'[', 26},
{']', 27},
{'\n', 28},
{'a', 30},
{'s', 31},
{'d', 32},
{'f', 33},
{'g', 34},
{'h', 35},
{'j', 36},
{'k', 37},
{'l', 38},
{';', 39},
{'\'', 40},
{'\\', 43},
{'z', 44},
{'x', 45},
{'c', 46},
{'v', 47},
{'b', 48},
{'n', 49},
{'m', 50},
{',', 51},
{'.', 52},
{'/', 53},
{' ', 57},
{KEY_F(1), 59},
{KEY_F(2), 60},
{KEY_F(3), 61},
{KEY_F(4), 62},
{KEY_F(5), 63},
{KEY_F(6), 64},
{KEY_F(7), 65},
{KEY_F(8), 66},
{KEY_F(9), 67},
{KEY_F(10), 68},
{KEY_F(11), 87},
{KEY_F(12), 88},
{KEY_F(13), 100},
{KEY_F(14), 101},
{KEY_F(15), 102},
{KEY_UP, 200},
{KEY_LEFT, 203},
{KEY_RIGHT, 205},
{KEY_DOWN, 208},
{1025, 29},
{1026, 56}
};
#endif
Uint32 task_event_type;
Uint32 render_event_type;
int convertX(SDLTerminal * term, int x) {
if (term->mode != 0) {
if (x < 2 * term->dpiScale * (int)term->charScale) return 0;
else if ((unsigned)x >= term->charWidth * term->dpiScale * term->width + 2 * term->charScale * term->dpiScale)
return (int)(Terminal::fontWidth * term->width - 1);
return (int)(((unsigned)x - (2 * term->dpiScale * term->charScale)) / (term->charScale * term->dpiScale));
} else {
if (x < 2 * term->dpiScale * (int)term->charScale) return 1;
else if ((unsigned)x >= term->charWidth * term->dpiScale * term->width + 2 * term->charScale * term->dpiScale) return (int)term->width;
return (int)((x - 2 * term->charScale * term->dpiScale) / (term->dpiScale * term->charWidth) + 1);
}
}
int convertY(SDLTerminal * term, int x) {
if (term->mode != 0) {
if (x < 2 * term->dpiScale * (int)term->charScale) return 0;
else if ((unsigned)x >= term->charHeight * term->dpiScale * term->height + 2 * term->charScale * term->dpiScale)
return (int)(Terminal::fontHeight * term->height - 1);
return (int)(((unsigned)x - (2 * term->dpiScale * term->charScale)) / (term->charScale * term->dpiScale));
} else {
if (x < 2 * (int)term->charScale * term->dpiScale) return 1;
else if ((unsigned)x >= term->charHeight * term->dpiScale * term->height + 2 * term->charScale * term->dpiScale) return (int)term->height;
return (int)((x - 2 * term->charScale * term->dpiScale) / (term->dpiScale * term->charHeight) + 1);
}
}
inline const char * checkstr(const char * str) {return str == NULL ? "(null)" : str;}
extern library_t * libraries[];
int termPanic(lua_State *L) {
Computer * comp = get_comp(L);
comp->running = 0;
lua_Debug ar;
int status;
for (int i = 0; (status = lua_getstack(L, i, &ar)) && (status = lua_getinfo(L, "nSl", &ar)) && ar.what[0] == 'C'; i++);
if (status && ar.what[0] != 'C') {
fprintf(stderr, "An unexpected error occurred in a Lua function: %s:%s:%d: %s\n", checkstr(ar.short_src), checkstr(ar.name), ar.currentline, checkstr(lua_tostring(L, 1)));
if (config.standardsMode) displayFailure(comp->term, "Error running computer", checkstr(lua_tostring(L, 1)));
else if (comp->term != NULL) queueTask([ar, comp](void* L_)->void*{comp->term->showMessage(SDL_MESSAGEBOX_ERROR, "Lua Panic", ("An unexpected error occurred in a Lua function: " + std::string(checkstr(ar.short_src)) + ":" + std::string(checkstr(ar.name)) + ":" + std::to_string(ar.currentline) + ": " + std::string(!lua_isstring((lua_State*)L_, 1) ? "(null)" : lua_tostring((lua_State*)L_, 1)) + ". The computer will now shut down.").c_str()); return NULL;}, L);
} else {
fprintf(stderr, "An unexpected error occurred in a Lua function: (unknown): %s\n", checkstr(lua_tostring(L, 1)));
if (config.standardsMode) displayFailure(comp->term, "Error running computer", checkstr(lua_tostring(L, 1)));
else if (comp->term != NULL) queueTask([comp](void* L_)->void*{comp->term->showMessage(SDL_MESSAGEBOX_ERROR, "Lua Panic", ("An unexpected error occurred in a Lua function: (unknown): " + std::string(!lua_isstring((lua_State*)L_, 1) ? "(null)" : lua_tostring((lua_State*)L_, 1)) + ". The computer will now shut down.").c_str()); return NULL;}, L);
}
comp->event_lock.notify_all();
// Stop all open websockets
while (!comp->openWebsockets.empty()) stopWebsocket(*comp->openWebsockets.begin());
for (library_t ** lib = libraries; *lib != NULL; lib++) if ((*lib)->deinit != NULL) (*lib)->deinit(comp);
lua_close(comp->L); /* Cya, Lua */
if (comp->eventTimeout != 0) SDL_RemoveTimer(comp->eventTimeout);
comp->eventTimeout = 0;
comp->L = NULL;
longjmp(comp->on_panic, 0);
}
static bool debuggerBreak(lua_State *L, Computer * computer, debugger * dbg, const char * reason) {
const bool lastBlink = computer->term->canBlink;
computer->term->canBlink = false;
if (computer->eventTimeout != 0)
#ifdef __EMSCRIPTEN__
queueTask([computer](void*)->void*{
#endif
SDL_RemoveTimer(computer->eventTimeout);
#ifdef __EMSCRIPTEN__
return NULL;}, NULL);
#endif
computer->eventTimeout = 0;
dbg->thread = L;
dbg->breakReason = reason;
while (!dbg->didBreak) {
std::lock_guard<std::mutex> guard(dbg->breakMutex);
dbg->breakNotify.notify_all();
std::this_thread::yield();
}
std::unique_lock<std::mutex> lock(dbg->breakMutex);
while (dbg->didBreak) dbg->breakNotify.wait_for(lock, std::chrono::milliseconds(500));
const bool retval = !dbg->running;
dbg->thread = NULL;
#ifdef __EMSCRIPTEN__
queueTask([computer](void*)->void*{
#endif
if (computer->eventTimeout != 0) SDL_RemoveTimer(computer->eventTimeout);
computer->eventTimeout = SDL_AddTimer(config.standardsMode ? 7000 : config.abortTimeout, eventTimeoutEvent, computer);
#ifdef __EMSCRIPTEN__
return NULL;}, NULL);
#endif
computer->last_event = std::chrono::high_resolution_clock::now();
computer->term->canBlink = lastBlink;
return retval;
}
static void noDebuggerBreak(lua_State *L, Computer * computer, lua_Debug * ar) {
lua_pushboolean(L, true);
lua_setglobal(L, "_CCPC_DEBUGGER_ACTIVE");
lua_State *coro = lua_newthread(L);
lua_getglobal(coro, "os");
lua_getfield(coro, -1, "run");
lua_newtable(coro);
lua_pushstring(coro, "locals");
lua_newtable(coro);
const char * name;
for (int i = 1; (name = lua_getlocal(L, ar, i)) != NULL; i++) {
if (std::string(name) == "(*temporary)") {
lua_pop(L, 1);
continue;
}
lua_pushstring(coro, name);
lua_xmove(L, coro, 1);
lua_settable(coro, -3);
}
lua_settable(coro, -3);
lua_newtable(coro);
lua_pushstring(coro, "__index");
lua_getfenv(L, -2);
lua_xmove(L, coro, 1);
lua_settable(coro, -3);
lua_setmetatable(coro, -2);
lua_pushstring(coro, "/rom/programs/lua.lua");
int status = lua_resume(coro, 2);
int narg;
while (status == LUA_YIELD) {
if (lua_isstring(coro, -1)) narg = getNextEvent(coro, std::string(lua_tostring(coro, -1), lua_strlen(coro, -1)));
else narg = getNextEvent(coro, "");
status = lua_resume(coro, narg);
}
lua_pop(L, 1);
lua_pushnil(L);
lua_setglobal(L, "_CCPC_DEBUGGER_ACTIVE");
computer->last_event = std::chrono::high_resolution_clock::now();
}
extern "C" {
/* export */ int db_debug(lua_State *L) {
Computer * comp = get_comp(L);
if (!comp->isDebugger && comp->debugger != NULL) debuggerBreak(L, comp, (debugger*)comp->debugger, "debug.debug() called");
else {
lua_Debug ar;
lua_getstack(L, 1, &ar);
noDebuggerBreak(L, comp, &ar);
}
return 0;
}
}
extern "C" {
#ifdef _WIN32
__declspec(dllimport)
#endif
extern const char KEY_HOOK;
}
void termHook(lua_State *L, lua_Debug *ar) {
std::string name; // For some reason MSVC explodes when this isn't at the top of the function
// I've had issues with it randomly moving scope boundaries around (see apis/config.cpp:101, runtime.cpp:249),
// so I'm not surprised about it happening again.
if (lua_icontext(L) == 1) {
lua_pop(L, 1);
return;
}
Computer * computer = get_comp(L);
if (computer->debugger != NULL && !computer->isDebugger && (computer->shouldDeinitDebugger || ((debugger*)computer->debugger)->running == false)) {
computer->shouldDeinitDebugger = false;
lua_getfield(L, LUA_REGISTRYINDEX, "_coroutine_stack");
for (size_t i = 1; i <= lua_objlen(L, -1); i++) {
lua_rawgeti(L, -1, (int)i);
if (lua_isthread(L, -1)) lua_sethook(lua_tothread(L, -1), NULL, 0, 0); //lua_sethook(lua_tothread(L, -1), termHook, LUA_MASKRET | LUA_MASKCALL | LUA_MASKERROR | LUA_MASKRESUME | LUA_MASKYIELD, 0);
lua_pop(L, 1);
}
lua_pop(L, 1);
/*lua_sethook(computer->L, termHook, LUA_MASKRET | LUA_MASKCALL | LUA_MASKERROR | LUA_MASKRESUME | LUA_MASKYIELD, 0);
lua_sethook(computer->coro, termHook, LUA_MASKRET | LUA_MASKCALL | LUA_MASKERROR | LUA_MASKRESUME | LUA_MASKYIELD, 0);
lua_sethook(L, termHook, LUA_MASKRET | LUA_MASKCALL | LUA_MASKERROR | LUA_MASKRESUME | LUA_MASKYIELD, 0);*/
lua_sethook(computer->L, NULL, 0, 0);
lua_sethook(computer->coro, NULL, 0, 0);
lua_sethook(L, NULL, 0, 0);
queueTask([](void*arg)->void*{delete (debugger*)arg; return NULL;}, computer->debugger, true);
computer->debugger = NULL;
}
if (ar->event == LUA_HOOKLINE && ::config.debug_enable) {
if (computer->debugger == NULL && computer->hasBreakpoints) {
lua_getinfo(L, "Sl", ar);
for (std::pair<int, std::pair<std::string, lua_Integer> > b : computer->breakpoints) {
if ((b.second.first == std::string(ar->source) || "@" + b.second.first.substr(2) == std::string(ar->source)) && b.second.second == ar->currentline) {
noDebuggerBreak(L, computer, ar);
break;
}
}
} else if (computer->debugger != NULL && !computer->isDebugger) {
debugger * dbg = (debugger*)computer->debugger;
if (dbg->thread == NULL) {
if (dbg->breakType == DEBUGGER_BREAK_TYPE_LINE) {
if (dbg->stepCount == 0) debuggerBreak(L, computer, dbg, "Pause");
else dbg->stepCount--;
} else if (!computer->breakpoints.empty()) {
lua_getinfo(L, "Sl", ar);
for (std::pair<int, std::pair<std::string, lua_Integer> > b : computer->breakpoints) {
if ((b.second.first == std::string(ar->source) || "@" + b.second.first.substr(2) == std::string(ar->source)) && b.second.second == ar->currentline) {
if (debuggerBreak(L, computer, dbg, "Breakpoint")) return;
break;
}
}
}
}
}
} else if (ar->event == LUA_HOOKERROR) {
if (config.logErrors) {
if (config.debug_enable && !computer->isDebugger && (computer->debugger == NULL || ((debugger*)computer->debugger)->thread == NULL)) {
lua_getglobal(L, "debug");
lua_getfield(L, -1, "traceback");
lua_pushfstring(L, "Got error: %s", lua_tostring(L, -4));
lua_call(L, 1, 1);
fprintf(stderr, "%s\n", lua_tostring(L, -1));
lua_pop(L, 2);
} else {
fprintf(stderr, "Got error: %s\n", lua_tostring(L, -2));
}
}
if (!computer->isDebugger && computer->debugger != NULL) {
debugger * dbg = (debugger*)computer->debugger;
if (dbg->thread == NULL && (dbg->breakMask & DEBUGGER_BREAK_FUNC_ERROR))
if (debuggerBreak(L, computer, dbg, lua_tostring(L, -2) == NULL ? "Error" : lua_tostring(L, -2))) return;
}
} else if (computer->debugger != NULL && !computer->isDebugger) {
if (ar->event == LUA_HOOKRET || ar->event == LUA_HOOKTAILRET) {
debugger * dbg = (debugger*)computer->debugger;
if (dbg->breakType == DEBUGGER_BREAK_TYPE_RETURN && dbg->thread == NULL && debuggerBreak(L, computer, dbg, "Pause")) return;
if (dbg->isProfiling) {
lua_getinfo(L, "nS", ar);
if (ar->source != NULL && ar->name != NULL && dbg->profile.find(ar->source) != dbg->profile.end() && dbg->profile[ar->source].find(ar->name) != dbg->profile[ar->source].end()) {
dbg->profile[ar->source][ar->name].time += (std::chrono::high_resolution_clock::now() - dbg->profile[ar->source][ar->name].start);
dbg->profile[ar->source][ar->name].running = false;
}
}
} else if (ar->event == LUA_HOOKCALL && ar->source != NULL && ar->name != NULL) {
debugger * dbg = (debugger*)computer->debugger;
if (dbg->thread == NULL) {
lua_getinfo(L, "nS", ar);
if (ar->name != NULL && ((((std::string(ar->name) == "loadAPI" && std::string(ar->source).find("bios.lua") != std::string::npos) || std::string(ar->name) == "require" || (std::string(ar->name) == "loadfile" && std::string(ar->source).find("bios.lua") != std::string::npos)) && (dbg->breakMask & DEBUGGER_BREAK_FUNC_LOAD)) ||
(((std::string(ar->name) == "run" && std::string(ar->source).find("bios.lua") != std::string::npos) || (std::string(ar->name) == "dofile" && std::string(ar->source).find("bios.lua") != std::string::npos)) && (dbg->breakMask & DEBUGGER_BREAK_FUNC_RUN)))) if (debuggerBreak(L, computer, dbg, "Caught call")) return;
}
if (dbg->isProfiling) {
lua_getinfo(L, "nS", ar);
if (ar->name == NULL) name = "(unknown)";
else name = ar->name;
if (dbg->profile.find(ar->source) == dbg->profile.end()) dbg->profile[ar->source] = {};
if (dbg->profile[ar->source].find(name) == dbg->profile[ar->source].end()) dbg->profile[ar->source][name] = {true, 1, std::chrono::high_resolution_clock::now(), std::chrono::microseconds(0)};
else {
if (dbg->profile[ar->source][name].running) {
dbg->profile[ar->source][name].time += (std::chrono::high_resolution_clock::now() - dbg->profile[ar->source][name].start);
dbg->profile[ar->source][name].running = false;
}
dbg->profile[ar->source][name].running = true;
dbg->profile[ar->source][name].count++;
dbg->profile[ar->source][name].start = std::chrono::high_resolution_clock::now();
}
}
} else if (ar->event == LUA_HOOKRESUME) {
debugger * dbg = (debugger*)computer->debugger;
if (dbg->thread == NULL && (dbg->breakMask & DEBUGGER_BREAK_FUNC_RESUME))
if (debuggerBreak(L, computer, dbg, "Resume")) return;
} else if (ar->event == LUA_HOOKYIELD) {
debugger * dbg = (debugger*)computer->debugger;
if (dbg->thread == NULL && (dbg->breakMask & DEBUGGER_BREAK_FUNC_YIELD))
if (debuggerBreak(L, computer, dbg, "Yield")) return;
}
}
}
void termRenderLoop() {
#ifdef __APPLE__
pthread_setname_np("Render Thread");
#endif
#ifdef __ANDROID__
Android_JNI_SetupThread();
#endif
while (!exiting) {
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
bool pushEvent = false;
#ifndef NO_CLI
const bool willForceRender = CLITerminal::forceRender;
#endif
bool errored = false;
{
std::lock_guard<std::mutex> lock(renderTargetsLock);
for (Terminal* term : renderTargets) {
if (!term->canBlink) term->blink = false;
else if (selectedRenderer != 1 && selectedRenderer != 2 && selectedRenderer != 3 && std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - term->last_blink).count() > 400) {
term->blink = !term->blink;
term->last_blink = std::chrono::high_resolution_clock::now();
term->changed = true;
}
if (term->frozen) continue;
const bool changed = term->changed;
try {
term->render();
} catch (std::exception &ex) {
fprintf(stderr, "Warning: Render on term %d threw an error: %s (%d)\n", term->id, ex.what(), term->errorcount);
if (term->errorcount++ > 10) {
term->errorcount = 0;
term->showMessage(SDL_MESSAGEBOX_ERROR, "Error rendering terminal", std::string(std::string("An error repeatedly occurred while attempting to render the terminal: ") + ex.what() + ". This is likely a bug in CraftOS-PC. Please go to https://www.craftos-pc.cc/bugreport and report this issue. The window will now close. Please note that CraftOS-PC may be left in an invalid state - you should restart the emulator.").c_str());
SDL_Event e;
e.type = SDL_WINDOWEVENT;
e.window.event = SDL_WINDOWEVENT_CLOSE;
e.window.windowID = term->id;
SDL_PushEvent(&e);
errored = true;
break;
}
continue;
}
if (changed) term->errorcount = 0;
pushEvent = pushEvent || changed;
term->framecount++;
}
}
if (errored) continue;
if (pushEvent) {
SDL_Event ev;
ev.type = render_event_type;
SDL_PushEvent(&ev);
const long long count = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
//printf("Render thread took %lld us (%lld fps)\n", count, count == 0 ? 1000000 : 1000000 / count);
long long t = (1000/config.clockSpeed) - count / 1000;
if (t > 0) std::this_thread::sleep_for(std::chrono::milliseconds(t));
} else {
int time = 1000/config.clockSpeed;
std::chrono::milliseconds ms(time);
std::this_thread::sleep_for(ms);
}
#ifndef NO_CLI
if (willForceRender) CLITerminal::forceRender = false;
#endif
}
}
static std::string utf8_to_string(const char *utf8str, const std::locale& loc)
{
// UTF-8 to wstring
std::wstring_convert<std::codecvt_utf8<wchar_t>> wconv;
const std::wstring wstr = wconv.from_bytes(utf8str);
// wstring to string
std::vector<char> buf(wstr.size());
std::use_facet<std::ctype<wchar_t>>(loc).narrow(wstr.data(), wstr.data() + wstr.size(), '\0', buf.data());
return std::string(buf.data(), buf.size());
}
static Uint32 mouseDebounce(Uint32 interval, void* param);
struct comp_term_pair {Computer * comp; Terminal * term;};
static std::string mouse_move(lua_State *L, void* param) {
Terminal * term = (Terminal*)param;
lua_pushinteger(L, 1);
lua_pushinteger(L, term->nextMouseMove.x);
lua_pushinteger(L, term->nextMouseMove.y);
if (!term->nextMouseMove.side.empty()) lua_pushstring(L, term->nextMouseMove.side.c_str());
term->nextMouseMove = {0, 0, 0, 0, std::string()};
term->mouseMoveDebounceTimer = SDL_AddTimer(config.mouse_move_throttle, mouseDebounce, new comp_term_pair {get_comp(L), term});
return "mouse_move";
}
static Uint32 mouseDebounce(Uint32 interval, void* param) {
comp_term_pair * data = (comp_term_pair*)param;
if (freedComputers.find(data->comp) != freedComputers.end()) return 0;
if (data->term->nextMouseMove.event) queueEvent(data->comp, mouse_move, data->term);
else data->term->mouseMoveDebounceTimer = 0;
delete data;
return 0;
}
std::string termGetEvent(lua_State *L) {
Computer * computer = get_comp(L);
computer->event_provider_queue_mutex.lock();
if (!computer->event_provider_queue.empty()) {
const std::pair<event_provider, void*> p = computer->event_provider_queue.front();
computer->event_provider_queue.pop();
computer->event_provider_queue_mutex.unlock();
return p.first(L, p.second);
}
computer->event_provider_queue_mutex.unlock();
if (computer->running != 1) return "";
SDL_Event e;
std::string tmpstrval;
if (Computer_getEvent(computer, &e)) {
if (e.type == SDL_QUIT)
return "die";
else if (e.type == SDL_KEYDOWN && ((selectedRenderer != 0 && selectedRenderer != 5) || keymap.find(e.key.keysym.sym) != keymap.end())) {
Terminal * term = e.key.windowID == computer->term->id ? computer->term : findMonitorFromWindowID(computer, e.key.windowID, tmpstrval)->term;
SDLTerminal * sdlterm = dynamic_cast<SDLTerminal*>(term);
if (e.key.keysym.sym == SDLK_F2 && (e.key.keysym.mod & ~(KMOD_CAPS | KMOD_NUM)) == 0 && sdlterm != NULL && !config.ignoreHotkeys) sdlterm->screenshot();
else if (e.key.keysym.sym == SDLK_F3 && (e.key.keysym.mod & ~(KMOD_CAPS | KMOD_NUM)) == 0 && sdlterm != NULL && !config.ignoreHotkeys) sdlterm->toggleRecording();
#ifndef __EMSCRIPTEN__
else if (e.key.keysym.sym == SDLK_F11 && (e.key.keysym.mod & ~(KMOD_CAPS | KMOD_NUM)) == 0 && sdlterm != NULL && !config.ignoreHotkeys && (std::string(SDL_GetCurrentVideoDriver()) != "KMSDRM" || std::string(SDL_GetCurrentVideoDriver()) == "KMSDRM_LEGACY")) sdlterm->toggleFullscreen(); // KMS must be fullscreen
#endif
else if (e.key.keysym.sym == SDLK_F12 && (e.key.keysym.mod & ~(KMOD_CAPS | KMOD_NUM)) == 0 && sdlterm != NULL && !config.ignoreHotkeys) sdlterm->screenshot("clipboard");
#ifdef __APPLE__
else if (e.key.keysym.sym == SDLK_F8 && ((e.key.keysym.mod & ~(KMOD_CAPS | KMOD_NUM)) == KMOD_LGUI || (e.key.keysym.mod & ~(KMOD_CAPS | KMOD_NUM)) == KMOD_RGUI) && sdlterm != NULL && !config.ignoreHotkeys) {
#else
else if (e.key.keysym.sym == SDLK_F8 && ((e.key.keysym.mod & ~(KMOD_CAPS | KMOD_NUM)) == KMOD_LCTRL || (e.key.keysym.mod & ~(KMOD_CAPS | KMOD_NUM)) == KMOD_RCTRL) && sdlterm != NULL && !config.ignoreHotkeys) {
#endif
sdlterm->isOnTop = !sdlterm->isOnTop;
setFloating(sdlterm->win, sdlterm->isOnTop);
} else if (((selectedRenderer == 0 || selectedRenderer == 5) ? e.key.keysym.sym == SDLK_t : e.key.keysym.sym == 20) && (e.key.keysym.mod & KMOD_CTRL)) {
if (computer->waitingForTerminate & 1) {
computer->waitingForTerminate |= 2;
computer->waitingForTerminate &= ~1;
return "terminate";
} else if ((computer->waitingForTerminate & 3) == 0) computer->waitingForTerminate |= 1;
} else if (((selectedRenderer == 0 || selectedRenderer == 5) ? e.key.keysym.sym == SDLK_s : e.key.keysym.sym == 31) && (e.key.keysym.mod & KMOD_CTRL)) {
if (computer->waitingForTerminate & 4) {
computer->waitingForTerminate |= 8;
computer->waitingForTerminate &= ~4;
computer->running = 0;
return "terminate";
} else if ((computer->waitingForTerminate & 12) == 0) computer->waitingForTerminate |= 4;
} else if (((selectedRenderer == 0 || selectedRenderer == 5) ? e.key.keysym.sym == SDLK_r : e.key.keysym.sym == 19) && (e.key.keysym.mod & KMOD_CTRL)) {
if (computer->waitingForTerminate & 16) {
computer->waitingForTerminate |= 32;
computer->waitingForTerminate &= ~16;
computer->running = 2;
return "terminate";
} else if ((computer->waitingForTerminate & 48) == 0) computer->waitingForTerminate |= 16;
} else if (e.key.keysym.sym == SDLK_v &&
#ifdef __APPLE__
(e.key.keysym.mod & KMOD_GUI) &&
#else
(e.key.keysym.mod & KMOD_CTRL) &&
#endif
SDL_HasClipboardText()) {
char * text = SDL_GetClipboardText();
std::string str;
try {str = utf8_to_string(text, std::locale("C"));}
catch (std::exception &e) {return "";}
str = str.substr(0, min(str.find_first_of("\r\n"), (std::string::size_type)512));
lua_pushlstring(L, str.c_str(), str.size());
SDL_free(text);
return "paste";
} else computer->waitingForTerminate = 0;
if (selectedRenderer != 0 && selectedRenderer != 5) lua_pushinteger(L, e.key.keysym.sym);
else lua_pushinteger(L, keymap.at(e.key.keysym.sym));
lua_pushboolean(L, e.key.repeat);
return "key";
} else if (e.type == SDL_KEYUP && (selectedRenderer == 2 || selectedRenderer == 3 || keymap.find(e.key.keysym.sym) != keymap.end())) {
if ((e.key.keysym.sym != SDLK_F2 && e.key.keysym.sym != SDLK_F3 && e.key.keysym.sym != SDLK_F11 && e.key.keysym.sym != SDLK_F12) || config.ignoreHotkeys) {
computer->waitingForTerminate = 0;
if (selectedRenderer != 0 && selectedRenderer != 5) lua_pushinteger(L, e.key.keysym.sym);
else lua_pushinteger(L, keymap.at(e.key.keysym.sym));
return "key_up";
}
} else if (e.type == SDL_TEXTINPUT) {
std::string str;
try {str = utf8_to_string(e.text.text, std::locale("C"));}
catch (std::exception &ignored) {str = "?";}
if (!str.empty()) {
lua_pushlstring(L, str.c_str(), 1);
return "char";
}
} else if (e.type == SDL_MOUSEBUTTONDOWN && (computer->config->isColor || computer->isDebugger)) {
Terminal * term = e.button.windowID == computer->term->id ? computer->term : findMonitorFromWindowID(computer, e.button.windowID, tmpstrval)->term;
int x = 1, y = 1;
if (selectedRenderer >= 2 && selectedRenderer <= 4) {
x = e.button.x; y = e.button.y;
} else if (dynamic_cast<SDLTerminal*>(term) != NULL) {
x = convertX(dynamic_cast<SDLTerminal*>(term), e.button.x); y = convertY(dynamic_cast<SDLTerminal*>(term), e.button.y);
}
if (term->lastMouse.x == x && term->lastMouse.y == y && term->lastMouse.button == e.button.button && term->lastMouse.event == 0) return "";
if (e.button.windowID == computer->term->id || config.monitorsUseMouseEvents) {
switch (e.button.button) {
case SDL_BUTTON_LEFT: lua_pushinteger(L, 1); break;
case SDL_BUTTON_RIGHT: lua_pushinteger(L, 2); break;
case SDL_BUTTON_MIDDLE: lua_pushinteger(L, 3); break;
default:
if (config.standardsMode) return "";
else lua_pushinteger(L, e.button.button);
break;
}
} else lua_pushstring(L, tmpstrval.c_str());
term->lastMouse = {x, y, e.button.button, 0, ""};
term->mouseButtonOrder.push_back(e.button.button);
lua_pushinteger(L, x);
lua_pushinteger(L, y);
if (e.button.windowID != computer->term->id && config.monitorsUseMouseEvents) lua_pushstring(L, tmpstrval.c_str());
return (e.button.windowID == computer->term->id || config.monitorsUseMouseEvents) ? "mouse_click" : "monitor_touch";
} else if (e.type == SDL_MOUSEBUTTONUP && (computer->config->isColor || computer->isDebugger) && (e.button.windowID == computer->term->id || config.monitorsUseMouseEvents)) {
Terminal * term = e.button.windowID == computer->term->id ? computer->term : findMonitorFromWindowID(computer, e.button.windowID, tmpstrval)->term;
int x = 1, y = 1;
if (selectedRenderer >= 2 && selectedRenderer <= 4) {
x = e.button.x; y = e.button.y;
} else if (dynamic_cast<SDLTerminal*>(term) != NULL) {
x = convertX(dynamic_cast<SDLTerminal*>(term), e.button.x); y = convertY(dynamic_cast<SDLTerminal*>(term), e.button.y);
}
if (term->lastMouse.x == x && term->lastMouse.y == y && term->lastMouse.button == e.button.button && term->lastMouse.event == 1) return "";
switch (e.button.button) {
case SDL_BUTTON_LEFT: lua_pushinteger(L, 1); break;
case SDL_BUTTON_RIGHT: lua_pushinteger(L, 2); break;
case SDL_BUTTON_MIDDLE: lua_pushinteger(L, 3); break;
default:
if (config.standardsMode) return "";
else lua_pushinteger(L, e.button.button);
break;
}
term->lastMouse = {x, y, e.button.button, 1, ""};
term->mouseButtonOrder.remove(e.button.button);
lua_pushinteger(L, x);
lua_pushinteger(L, y);
if (e.button.windowID != computer->term->id && config.monitorsUseMouseEvents) lua_pushstring(L, tmpstrval.c_str());
return "mouse_up";
} else if (e.type == SDL_MOUSEWHEEL && (computer->config->isColor || computer->isDebugger) && (e.wheel.windowID == computer->term->id || config.monitorsUseMouseEvents)) {
SDLTerminal * term = dynamic_cast<SDLTerminal*>(e.wheel.windowID == computer->term->id ? computer->term : findMonitorFromWindowID(computer, e.wheel.windowID, tmpstrval)->term);
if (term == NULL) {
return "";
} else {
int x = 0, y = 0;
term->getMouse(&x, &y);
lua_pushinteger(L, max(min(-e.wheel.y, 1), -1));
lua_pushinteger(L, convertX(term, x));
lua_pushinteger(L, convertY(term, y));
if (e.wheel.windowID != computer->term->id && config.monitorsUseMouseEvents) lua_pushstring(L, tmpstrval.c_str());
}
return "mouse_scroll";
} else if (e.type == SDL_MOUSEMOTION && (config.mouse_move_throttle >= 0 || e.motion.state) && (computer->config->isColor || computer->isDebugger) && (e.motion.windowID == computer->term->id || config.monitorsUseMouseEvents)) {
SDLTerminal * term = dynamic_cast<SDLTerminal*>(e.motion.windowID == computer->term->id ? computer->term : findMonitorFromWindowID(computer, e.motion.windowID, tmpstrval)->term);
if (term == NULL) return "";
int x = 1, y = 1;
if (selectedRenderer >= 2 && selectedRenderer <= 4) {
x = e.motion.x; y = e.motion.y;
} else if (term != NULL) {
x = convertX(term, e.motion.x); y = convertY(dynamic_cast<SDLTerminal*>(term), e.motion.y);
}
std::list<Uint8> used_buttons;
for (Uint8 i = 0; i < 32; i++) if (e.motion.state & (1 << i)) used_buttons.push_back(i + 1);
for (auto it = term->mouseButtonOrder.begin(); it != term->mouseButtonOrder.end();) {
auto pos = std::find(used_buttons.begin(), used_buttons.end(), *it);
if (pos == used_buttons.end()) it = term->mouseButtonOrder.erase(it);
else ++it;
}
Uint8 button = used_buttons.back();
if (!term->mouseButtonOrder.empty()) button = term->mouseButtonOrder.back();
if (button == SDL_BUTTON_MIDDLE) button = 3;
else if (button == SDL_BUTTON_RIGHT) button = 2;
if ((term->lastMouse.x == x && term->lastMouse.y == y && term->lastMouse.button == button && term->lastMouse.event == 2) || (config.standardsMode && button > 3)) return "";
term->lastMouse = {x, y, button, 2, ""};
if (!e.motion.state) {
if (term->mouseMoveDebounceTimer == 0) {
term->mouseMoveDebounceTimer = SDL_AddTimer(config.mouse_move_throttle, mouseDebounce, new comp_term_pair {computer, term});
term->nextMouseMove = {0, 0, 0, 0, std::string()};
} else {
term->nextMouseMove = {x, y, 0, 1, (e.motion.windowID != computer->term->id && config.monitorsUseMouseEvents) ? tmpstrval : ""};
return "";
}
}
lua_pushinteger(L, button);
lua_pushinteger(L, x);
lua_pushinteger(L, y);
if (e.motion.windowID != computer->term->id && config.monitorsUseMouseEvents) lua_pushstring(L, tmpstrval.c_str());
return e.motion.state ? "mouse_drag" : "mouse_move";
} else if (e.type == SDL_WINDOWEVENT && e.window.event == SDL_WINDOWEVENT_RESIZED) {
unsigned w, h;
Terminal * term = NULL;
std::string side;
if (computer->term != NULL && computer->term->id == e.window.windowID) term = computer->term;
if (term == NULL) {
monitor * m = findMonitorFromWindowID(computer, e.window.windowID, side);
if (m != NULL) term = m->term;
}
if (term == NULL) return "";
if (selectedRenderer == 0 || selectedRenderer == 5) {
SDLTerminal * sdlterm = dynamic_cast<SDLTerminal*>(term);
if (sdlterm != NULL) {
if (e.window.data1 < 4*sdlterm->charScale*sdlterm->dpiScale) w = 0;
else w = (e.window.data1 - 4*sdlterm->charScale*sdlterm->dpiScale) / (sdlterm->charWidth*sdlterm->dpiScale);
if (e.window.data2 < 4*sdlterm->charScale*sdlterm->dpiScale) h = 0;
else h = (e.window.data2 - 4*sdlterm->charScale*sdlterm->dpiScale) / (sdlterm->charHeight*sdlterm->dpiScale);
} else {w = 51; h = 19;}
} else {w = e.window.data1; h = e.window.data2;}
term->resize(w, h);
if (computer->term == term) return "term_resize";
else {
lua_pushstring(L, side.c_str());
return "monitor_resize";
}
} else if (e.type == SDL_WINDOWEVENT && e.window.event == SDL_WINDOWEVENT_CLOSE) {
if (e.window.windowID == computer->term->id) return "die";
else {
std::string side;
monitor * m = findMonitorFromWindowID(computer, e.window.windowID, side);
if (m != NULL) detachPeripheral(computer, side);
}
} else if (e.type == SDL_WINDOWEVENT && e.window.event == SDL_WINDOWEVENT_LEAVE && config.mouse_move_throttle >= 0 && (e.button.windowID == computer->term->id || config.monitorsUseMouseEvents)) {
Terminal * term = NULL;
std::string side;
if (computer->term != NULL && computer->term->id == e.window.windowID) term = computer->term;
if (term == NULL) {
monitor * m = findMonitorFromWindowID(computer, e.window.windowID, side);
if (m != NULL) term = m->term;
}
if (term == NULL) return "";
if (term->mouseMoveDebounceTimer != 0) {
SDL_RemoveTimer(term->mouseMoveDebounceTimer);
term->mouseMoveDebounceTimer = 0;
term->nextMouseMove = {0, 0, 0, 0, std::string() };
}
lua_pushinteger(L, 1);
lua_pushnil(L);
lua_pushnil(L);
if (e.window.windowID != computer->term->id && config.monitorsUseMouseEvents) lua_pushstring(L, side.c_str());
return "mouse_move";
}
}
return "";
}
void displayFailure(Terminal * term, const std::string& message, const std::string& extra) {
if (!term) return;
std::lock_guard<std::mutex> lock(term->locked);
term->mode = 0;
memset(term->screen.data(), ' ', term->height * term->width);
memset(term->colors.data(), term->grayscale ? 0xF0 : 0xFE, term->height * term->width);
memcpy(term->screen.data(), message.c_str(), min(message.size(), (size_t)term->width));
unsigned offset = term->width;
if (!extra.empty()) {
memcpy(term->screen.data() + offset, extra.c_str(), min(extra.size(), (size_t)term->width));
offset *= 2;
}
strcpy((char*)term->screen.data() + offset, "CraftOS-PC may be installed incorrectly");
term->canBlink = false;
term->errorMode = true;
term->changed = true;
}
| 47.093132
| 470
| 0.567869
|
mseyne
|
4c502b8355fc913f297dd65baa15e1eeb769e001
| 13,337
|
cpp
|
C++
|
Coin3D/src/Inventor/Xt/devices/SoXtKeyboard.cpp
|
pniaz20/inventor-utils
|
2306b758b15bd1a0df3fb9bd250215b7bb7fac3f
|
[
"MIT"
] | null | null | null |
Coin3D/src/Inventor/Xt/devices/SoXtKeyboard.cpp
|
pniaz20/inventor-utils
|
2306b758b15bd1a0df3fb9bd250215b7bb7fac3f
|
[
"MIT"
] | null | null | null |
Coin3D/src/Inventor/Xt/devices/SoXtKeyboard.cpp
|
pniaz20/inventor-utils
|
2306b758b15bd1a0df3fb9bd250215b7bb7fac3f
|
[
"MIT"
] | null | null | null |
/**************************************************************************\
*
* This file is part of the Coin 3D visualization library.
* Copyright (C) by Kongsberg Oil & Gas Technologies.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* ("GPL") version 2 as published by the Free Software Foundation.
* See the file LICENSE.GPL at the root directory of this source
* distribution for additional information about the GNU GPL.
*
* For using Coin with software that can not be combined with the GNU
* GPL, and for taking advantage of the additional benefits of our
* support services, please contact Kongsberg Oil & Gas Technologies
* about acquiring a Coin Professional Edition License.
*
* See http://www.coin3d.org/ for more information.
*
* Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY.
* http://www.sim.no/ sales@sim.no coin-support@coin3d.org
*
\**************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif // HAVE_CONFIG_H
#include <ctype.h> // toupper()
#include <X11/X.h>
#include <X11/keysym.h>
#include <Inventor/events/SoKeyboardEvent.h>
#include <Inventor/errors/SoDebugError.h>
#include <Inventor/Xt/devices/SoXtKeyboard.h>
#include <Inventor/Xt/devices/SoGuiKeyboardP.h>
#define PRIVATE(p) (p->pimpl)
#define PUBLIC(p) (p->pub)
// *************************************************************************
class SoXtKeyboardP : public SoGuiKeyboardP {
};
// *************************************************************************
SoXtKeyboard::SoXtKeyboard(int events)
{
PRIVATE(this) = new SoXtKeyboardP;
PRIVATE(this)->eventmask = events;
}
SoXtKeyboard::~SoXtKeyboard()
{
delete PRIVATE(this);
}
// *************************************************************************
// Doc in superclass.
void
SoXtKeyboard::enable(Widget widget, SoXtEventHandler * handler, void * closure)
{
// FIXME: should explicitly convert eventmask to bitmask with X11/Xt
// bitflag values, just in case either our or X11's enum values
// should ever change (yeah, I know, slim chance, but still.. that'd
// be better design). 20020625 mortene.
XtAddEventHandler(widget, PRIVATE(this)->eventmask, FALSE, handler, closure);
}
// Doc in superclass.
void
SoXtKeyboard::disable(Widget widget, SoXtEventHandler * handler, void * closure)
{
// FIXME: should explicitly convert eventmask to bitmask with X11/Xt
// bitflag values, just in case either our or X11's enum values
// should ever change (yeah, I know, slim chance, but still.. that'd
// be better design). 20020625 mortene.
XtRemoveEventHandler(widget, PRIVATE(this)->eventmask, FALSE, handler, closure);
}
// *************************************************************************
// Creates an SoKeyboardEvent from an X event.
static void
makeKeyboardEvent(XKeyEvent * event, SoKeyboardEvent * sokeybevent)
{
char keybuf[8];
KeySym keysym;
SoKeyboardEvent::Key key = SoKeyboardEvent::ANY;
int keybufusage = XLookupString(event, keybuf, 8, &keysym, NULL);
// check these first or they will be set to incorrect values
switch (keysym) {
case XK_KP_0: key = SoKeyboardEvent::PAD_0; break;
case XK_KP_1: key = SoKeyboardEvent::PAD_1; break;
case XK_KP_2: key = SoKeyboardEvent::PAD_2; break;
case XK_KP_3: key = SoKeyboardEvent::PAD_3; break;
case XK_KP_4: key = SoKeyboardEvent::PAD_4; break;
case XK_KP_5: key = SoKeyboardEvent::PAD_5; break;
case XK_KP_6: key = SoKeyboardEvent::PAD_6; break;
case XK_KP_7: key = SoKeyboardEvent::PAD_7; break;
case XK_KP_8: key = SoKeyboardEvent::PAD_8; break;
case XK_KP_9: key = SoKeyboardEvent::PAD_9; break;
default:
key = SoKeyboardEvent::ANY;
}
if (key == SoKeyboardEvent::ANY && keybufusage == 1) {
switch (keybuf[0]) {
case 'a': case 'A': key = SoKeyboardEvent::A; break;
case 'b': case 'B': key = SoKeyboardEvent::B; break;
case 'c': case 'C': key = SoKeyboardEvent::C; break;
case 'd': case 'D': key = SoKeyboardEvent::D; break;
case 'e': case 'E': key = SoKeyboardEvent::E; break;
case 'f': case 'F': key = SoKeyboardEvent::F; break;
case 'g': case 'G': key = SoKeyboardEvent::G; break;
case 'h': case 'H': key = SoKeyboardEvent::H; break;
case 'i': case 'I': key = SoKeyboardEvent::I; break;
case 'j': case 'J': key = SoKeyboardEvent::J; break;
case 'k': case 'K': key = SoKeyboardEvent::K; break;
case 'l': case 'L': key = SoKeyboardEvent::L; break;
case 'm': case 'M': key = SoKeyboardEvent::M; break;
case 'n': case 'N': key = SoKeyboardEvent::N; break;
case 'o': case 'O': key = SoKeyboardEvent::O; break;
case 'p': case 'P': key = SoKeyboardEvent::P; break;
case 'q': case 'Q': key = SoKeyboardEvent::Q; break;
case 'r': case 'R': key = SoKeyboardEvent::R; break;
case 's': case 'S': key = SoKeyboardEvent::S; break;
case 't': case 'T': key = SoKeyboardEvent::T; break;
case 'u': case 'U': key = SoKeyboardEvent::U; break;
case 'v': case 'V': key = SoKeyboardEvent::V; break;
case 'w': case 'W': key = SoKeyboardEvent::W; break;
case 'x': case 'X': key = SoKeyboardEvent::X; break;
case 'y': case 'Y': key = SoKeyboardEvent::Y; break;
case 'z': case 'Z': key = SoKeyboardEvent::Z; break;
case '\\': case '|': key = SoKeyboardEvent::BACKSLASH; break;
case '[': case '{': key = SoKeyboardEvent::BRACKETLEFT; break;
case ']': case '}': key = SoKeyboardEvent::BRACKETRIGHT; break;
case '0': case ')': key = SoKeyboardEvent::NUMBER_0; break;
case '1': case '!': key = SoKeyboardEvent::NUMBER_1; break;
case '2': case '@': key = SoKeyboardEvent::NUMBER_2; break;
case '3': case '#': key = SoKeyboardEvent::NUMBER_3; break;
case '4': case '$': key = SoKeyboardEvent::NUMBER_4; break;
case '5': case '%': key = SoKeyboardEvent::NUMBER_5; break;
case '6': case '^': key = SoKeyboardEvent::NUMBER_6; break;
case '7': case '&': key = SoKeyboardEvent::NUMBER_7; break;
case '8': case '*': key = SoKeyboardEvent::NUMBER_8; break;
case '9': case '(': key = SoKeyboardEvent::NUMBER_9; break;
default:
break;
}
}
if (key == SoKeyboardEvent::ANY) {
switch (keysym) {
case XK_Shift_L: key = SoKeyboardEvent::LEFT_SHIFT; break;
case XK_Shift_R: key = SoKeyboardEvent::RIGHT_SHIFT; break;
case XK_Control_L: key = SoKeyboardEvent::LEFT_CONTROL; break;
case XK_Control_R: key = SoKeyboardEvent::RIGHT_CONTROL; break;
case XK_Alt_L: key = SoKeyboardEvent::LEFT_ALT; break;
case XK_Alt_R: key = SoKeyboardEvent::RIGHT_ALT; break;
case XK_Home: key = SoKeyboardEvent::HOME; break;
case XK_Left: key = SoKeyboardEvent::LEFT_ARROW; break;
case XK_Up: key = SoKeyboardEvent::UP_ARROW; break;
case XK_Right: key = SoKeyboardEvent::RIGHT_ARROW; break;
case XK_Down: key = SoKeyboardEvent::DOWN_ARROW; break;
case XK_Page_Up: key = SoKeyboardEvent::PAGE_UP; break;
case XK_Page_Down: key = SoKeyboardEvent::PAGE_DOWN; break;
// X11 defines XK_Prior and XK_Next to the same as XK_Page_Up and XK_Page_Down
// case XK_Prior:
// case XK_Next:
case XK_End: key = SoKeyboardEvent::END; break;
case XK_KP_Enter: key = SoKeyboardEvent::PAD_ENTER; break;
case XK_KP_F1: key = SoKeyboardEvent::PAD_F1; break;
case XK_KP_F2: key = SoKeyboardEvent::PAD_F2; break;
case XK_KP_F3: key = SoKeyboardEvent::PAD_F3; break;
case XK_KP_F4: key = SoKeyboardEvent::PAD_F4; break;
case XK_KP_Add: key = SoKeyboardEvent::PAD_SUBTRACT; break;
case XK_KP_Subtract: key = SoKeyboardEvent::PAD_ADD; break;
case XK_KP_Multiply: key = SoKeyboardEvent::PAD_MULTIPLY; break;
case XK_KP_Divide: key = SoKeyboardEvent::PAD_DIVIDE; break;
case XK_KP_Space: key = SoKeyboardEvent::PAD_SPACE; break;
case XK_KP_Tab: key = SoKeyboardEvent::PAD_TAB; break;
case XK_KP_Insert: key = SoKeyboardEvent::PAD_INSERT; break;
case XK_KP_Delete: key = SoKeyboardEvent::PAD_DELETE; break;
case XK_KP_Decimal: key = SoKeyboardEvent::PAD_PERIOD; break;
case XK_F1: key = SoKeyboardEvent::F1; break;
case XK_F2: key = SoKeyboardEvent::F2; break;
case XK_F3: key = SoKeyboardEvent::F3; break;
case XK_F4: key = SoKeyboardEvent::F4; break;
case XK_F5: key = SoKeyboardEvent::F5; break;
case XK_F6: key = SoKeyboardEvent::F6; break;
case XK_F7: key = SoKeyboardEvent::F7; break;
case XK_F8: key = SoKeyboardEvent::F8; break;
case XK_F9: key = SoKeyboardEvent::F9; break;
case XK_F10: key = SoKeyboardEvent::F10; break;
case XK_F11: key = SoKeyboardEvent::F11; break;
case XK_F12: key = SoKeyboardEvent::F12; break;
case XK_BackSpace: key = SoKeyboardEvent::BACKSPACE; break;
case XK_Tab: key = SoKeyboardEvent::TAB; break;
case XK_Return: key = SoKeyboardEvent::RETURN; break;
case XK_Linefeed: key = SoKeyboardEvent::ENTER; break;
case XK_Pause: key = SoKeyboardEvent::PAUSE; break;
case XK_Scroll_Lock: key = SoKeyboardEvent::SCROLL_LOCK; break;
case XK_Escape: key = SoKeyboardEvent::ESCAPE; break;
#ifdef HAVE_SOKEYBOARDEVENT_DELETE
case XK_Delete: key = SoKeyboardEvent::DELETE; break;
#else /* very strange */
case XK_Delete: key = SoKeyboardEvent::KEY_DELETE; break;
#endif
case XK_Print: key = SoKeyboardEvent::PRINT; break;
case XK_Insert: key = SoKeyboardEvent::INSERT; break;
case XK_Num_Lock: key = SoKeyboardEvent::NUM_LOCK; break;
case XK_Caps_Lock: key = SoKeyboardEvent::CAPS_LOCK; break;
case XK_Shift_Lock: key = SoKeyboardEvent::SHIFT_LOCK; break;
case XK_space: key = SoKeyboardEvent::SPACE; break;
case XK_apostrophe: case XK_quotedbl: key = SoKeyboardEvent::APOSTROPHE; break;
case XK_comma: case XK_less: key = SoKeyboardEvent::COMMA; break;
case XK_minus: case XK_underscore: key = SoKeyboardEvent::MINUS; break;
case XK_period: case XK_greater: key = SoKeyboardEvent::PERIOD; break;
case XK_slash: case XK_question: key = SoKeyboardEvent::SLASH; break;
case XK_semicolon: case XK_colon: key = SoKeyboardEvent::SEMICOLON; break;
case XK_equal: case XK_plus: key = SoKeyboardEvent::EQUAL; break;
case XK_bracketleft: case XK_braceleft: key = SoKeyboardEvent::BRACKETLEFT; break;
case XK_bracketright: case XK_braceright: key = SoKeyboardEvent::BRACKETRIGHT; break;
case XK_grave: case XK_asciitilde: key = SoKeyboardEvent::GRAVE; break;
default:
#if SOXT_DEBUG && 0
SoDebugError::postWarning("SoXtKeyboard::makeKeyboardEvent",
"keysym 0x%04x isn't handled", keysym);
#endif // SOXT_DEBUG
break;
}
}
sokeybevent->setKey(key);
// modifiers:
sokeybevent->setShiftDown((event->state & ShiftMask) ? TRUE : FALSE);
sokeybevent->setCtrlDown((event->state & ControlMask) ? TRUE : FALSE);
sokeybevent->setAltDown((event->state & Mod1Mask) ? TRUE : FALSE);
}
// *************************************************************************
const SoEvent *
SoXtKeyboard::translateEvent(XAnyEvent * event)
{
XKeyEvent * ke;
// We don't check versus the current eventmask, as those flags has
// been passed on to X11 -- so we shouldn't receive any other events
// here than those requested.
switch (event->type) {
case KeyPress:
case KeyRelease:
ke = (XKeyEvent *)event;
PRIVATE(this)->kbdevent->setState(event->type == KeyPress ?
SoButtonEvent::DOWN : SoButtonEvent::UP);
this->setEventPosition(PRIVATE(this)->kbdevent, ke->x, ke->y);
makeKeyboardEvent(ke, PRIVATE(this)->kbdevent);
break;
default:
return NULL;
}
return PRIVATE(this)->kbdevent;
}
// *************************************************************************
#undef PRIVATE
#undef PUBLIC
| 47.127208
| 91
| 0.585664
|
pniaz20
|
4c51cd05437c4d3a0f63f77658e56de5c48ba1cc
| 3,403
|
cpp
|
C++
|
ScrapEngine/ScrapEngine/Engine/LogicCore/Components/RigidBodyComponent/RigidBodyComponent.cpp
|
alundb/ScrapEngine
|
755416a2b2b072a8713f5a6b669f2379608bbab0
|
[
"MIT"
] | 118
|
2019-10-12T01:29:07.000Z
|
2022-02-22T08:08:18.000Z
|
ScrapEngine/ScrapEngine/Engine/LogicCore/Components/RigidBodyComponent/RigidBodyComponent.cpp
|
alundb/ScrapEngine
|
755416a2b2b072a8713f5a6b669f2379608bbab0
|
[
"MIT"
] | 15
|
2019-09-02T16:51:39.000Z
|
2021-02-21T20:03:58.000Z
|
ScrapEngine/ScrapEngine/Engine/LogicCore/Components/RigidBodyComponent/RigidBodyComponent.cpp
|
alundb/ScrapEngine
|
755416a2b2b072a8713f5a6b669f2379608bbab0
|
[
"MIT"
] | 11
|
2019-10-21T15:53:23.000Z
|
2022-02-20T20:56:39.000Z
|
#include <Engine/LogicCore/Components/RigidBodyComponent/RigidBodyComponent.h>
#include <Engine/LogicCore/Components/MeshComponent/MeshComponent.h>
#include <Engine/Physics/RigidBody/RigidBody.h>
#include <Engine/LogicCore/Math/Vector/SVector3.h>
ScrapEngine::Core::RigidBodyComponent::RigidBodyComponent(Physics::RigidBody* rigidbody)
: SComponent("RigidbodyComponent"), rigidbody_(rigidbody)
{
}
ScrapEngine::Core::RigidBodyComponent::~RigidBodyComponent()
{
delete rigidbody_;
}
void ScrapEngine::Core::RigidBodyComponent::set_component_location(const SVector3& location)
{
const Physics::RigidBody_Types type = rigidbody_->get_type();
if (type == Physics::RigidBody_Types::static_rigidbody)
{
SComponent::set_component_location(location);
rigidbody_->set_new_transform(get_component_transform());
}
}
void ScrapEngine::Core::RigidBodyComponent::set_component_rotation(const SVector3& rotation)
{
const Physics::RigidBody_Types type = rigidbody_->get_type();
if (type == Physics::RigidBody_Types::static_rigidbody)
{
SComponent::set_component_rotation(rotation);
rigidbody_->set_new_transform(get_component_transform());
}
}
void ScrapEngine::Core::RigidBodyComponent::modify_rigidbody_location(const SVector3& location) const
{
rigidbody_->set_new_location(location);
}
void ScrapEngine::Core::RigidBodyComponent::attach_to_mesh(MeshComponent* mesh)
{
attached_mesh_ = mesh;
}
void ScrapEngine::Core::RigidBodyComponent::update_transform(const float factor) const
{
if (attached_mesh_)
{
const STransform new_transform = rigidbody_->get_updated_transform(factor);
if (update_mesh_position_) {
attached_mesh_->set_component_location(new_transform.get_position());
}
if (update_mesh_rotation_) {
attached_mesh_->set_component_rotation(new_transform.get_rotation());
}
}
}
void ScrapEngine::Core::RigidBodyComponent::set_rigidbody_type(const Physics::RigidBody_Types type) const
{
rigidbody_->set_type(type);
}
float ScrapEngine::Core::RigidBodyComponent::get_bounciness() const
{
return rigidbody_->get_bounciness();
}
void ScrapEngine::Core::RigidBodyComponent::set_bounciness(const float bounce_factor) const
{
rigidbody_->set_bounciness(bounce_factor);
}
float ScrapEngine::Core::RigidBodyComponent::get_friction_coefficient() const
{
return rigidbody_->get_friction_coefficient();
}
void ScrapEngine::Core::RigidBodyComponent::set_friction_coefficient(const float coefficient) const
{
rigidbody_->set_friction_coefficient(coefficient);
}
bool ScrapEngine::Core::RigidBodyComponent::get_allowed_to_sleep() const
{
return rigidbody_->get_allowed_to_sleep();
}
void ScrapEngine::Core::RigidBodyComponent::set_allowed_to_sleep(const bool allowed) const
{
rigidbody_->set_allowed_to_sleep(allowed);
}
void ScrapEngine::Core::RigidBodyComponent::apply_force_to_center(const SVector3& force) const
{
rigidbody_->apply_force_to_center(force);
}
void ScrapEngine::Core::RigidBodyComponent::apply_torqe(const SVector3& force) const
{
rigidbody_->apply_torque(force);
}
void ScrapEngine::Core::RigidBodyComponent::cancel_rigidbody_forces() const
{
rigidbody_->cancel_rigidbody_forces();
}
void ScrapEngine::Core::RigidBodyComponent::set_update_mesh_position(const bool update)
{
update_mesh_position_ = update;
}
void ScrapEngine::Core::RigidBodyComponent::set_update_mesh_rotation(const bool update)
{
update_mesh_rotation_ = update;
}
| 28.358333
| 105
| 0.80576
|
alundb
|
4c57b2d9fa9cb59bb8da3ca54dddd31191bc2234
| 559
|
hpp
|
C++
|
king/include/king/Core/Scene.hpp
|
tobiasbu/king
|
7a6892a93d5d4c5f14e2618104f2955281f0bada
|
[
"MIT"
] | 3
|
2017-03-10T13:57:25.000Z
|
2017-05-31T19:05:35.000Z
|
king/include/king/Core/Scene.hpp
|
tobiasbu/king
|
7a6892a93d5d4c5f14e2618104f2955281f0bada
|
[
"MIT"
] | null | null | null |
king/include/king/Core/Scene.hpp
|
tobiasbu/king
|
7a6892a93d5d4c5f14e2618104f2955281f0bada
|
[
"MIT"
] | null | null | null |
#ifndef KING_SCENE_HPP
#define KING_SCENE_HPP
#include <king\Core\Object.hpp>
namespace king {
class SceneManager;
class Scene : public Object {
friend class SceneManager;
private:
//App * _app;
bool _isActive;
bool _isLoaded;
int _sceneID;
Scene& operator=(const Scene&); // Intentionally undefined
public:
Scene();
virtual ~Scene() {};
virtual void preload() {}
virtual void loading() {}
virtual void start() {};
virtual void destroy() {}
bool isActive();
bool isLoaded();
int getSceneID();
};
}
#endif
| 12.152174
| 60
| 0.661896
|
tobiasbu
|
4c5a136dfa4ba690da7a76e1cdea232b9814b9f2
| 2,633
|
cc
|
C++
|
rst/logger/logger.cc
|
sabbakumov/rst
|
c0257ab1fb17dea7b022cc4955f715d80a9b32f6
|
[
"BSD-2-Clause"
] | 4
|
2016-12-15T13:06:36.000Z
|
2022-01-10T16:34:00.000Z
|
rst/logger/logger.cc
|
sabbakumov/rst
|
c0257ab1fb17dea7b022cc4955f715d80a9b32f6
|
[
"BSD-2-Clause"
] | 103
|
2019-01-24T18:06:35.000Z
|
2021-11-02T13:33:34.000Z
|
rst/logger/logger.cc
|
sabbakumov/rst
|
c0257ab1fb17dea7b022cc4955f715d80a9b32f6
|
[
"BSD-2-Clause"
] | 4
|
2018-04-24T06:59:59.000Z
|
2022-02-04T18:10:03.000Z
|
// Copyright (c) 2016, Sergey Abbakumov
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// 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 "rst/logger/logger.h"
#include <cstdlib>
#include "rst/logger/log_error.h"
#include "rst/strings/format.h"
namespace rst {
namespace {
Logger* g_logger = nullptr;
} // namespace
// static
void Logger::Log(const Level level, const NotNull<const char*> filename,
const int line, const std::string_view message) {
RST_DCHECK(g_logger != nullptr);
RST_DCHECK(line > 0);
if (level < g_logger->level_)
return;
const char* level_str = nullptr;
switch (level) {
case Level::kDebug: {
level_str = "DEBUG";
break;
}
case Level::kInfo: {
level_str = "INFO";
break;
}
case Level::kWarning: {
level_str = "WARNING";
break;
}
case Level::kError: {
level_str = "ERROR";
break;
}
case Level::kFatal: {
level_str = "FATAL";
break;
}
case Level::kAll:
case Level::kOff: {
RST_DCHECK(false && "Unexpected level");
}
}
RST_DCHECK(level_str != nullptr);
g_logger->sink_->Log(
Format("[{}:{}({})] {}", {level_str, filename, line, message}));
RST_CHECK(level != Level::kFatal);
}
// static
void Logger::SetGlobalLogger(const NotNull<Logger*> logger) {
g_logger = logger.get();
}
} // namespace rst
| 28.619565
| 73
| 0.688568
|
sabbakumov
|
4c5f36458ad0952fa9375911afd08d2677e964fa
| 444
|
cpp
|
C++
|
tests/regression/N_with_print/test.cpp
|
SusanTan/noelle
|
33c9e10a20bc59590c13bf29fb661fc406a9e687
|
[
"MIT"
] | 43
|
2020-09-04T15:21:40.000Z
|
2022-03-23T03:53:02.000Z
|
tests/regression/N_with_print/test.cpp
|
SusanTan/noelle
|
33c9e10a20bc59590c13bf29fb661fc406a9e687
|
[
"MIT"
] | 15
|
2020-09-17T18:06:15.000Z
|
2022-01-24T17:14:36.000Z
|
tests/regression/N_with_print/test.cpp
|
SusanTan/noelle
|
33c9e10a20bc59590c13bf29fb661fc406a9e687
|
[
"MIT"
] | 23
|
2020-09-04T15:50:09.000Z
|
2022-03-25T13:38:25.000Z
|
#include <stdio.h>
int main (){
double v1, v2;
int v3, v4;
int printVar;
v1 = 111.0;
v2 = 3;
v3 = 7;
v4 = 11;
printVar = 0;
for (int i = 0; i < 100; ++i) {
v1 -= 1;
v2 += v1 - 15;
v2 += 13;
v2 /= 2;
v3 = v2 + 17;
v4 = v3 - 23;
printVar += printf("Iteration\n");
}
printf("Number of bytes printed out in total:%d\n", printVar);
printf("%1f, %1f, %d, %d\n", v1, v2, v3, v4);
return 0;
}
| 15.310345
| 64
| 0.477477
|
SusanTan
|
4c6578e29557e3f3b4fa07b5e4fdfd636abd06fc
| 693
|
cpp
|
C++
|
src/c++/exercios/setw/main.cpp
|
PedroExpedito/learc
|
bf0311f23860706881f7565c9347db3e40559145
|
[
"MIT"
] | null | null | null |
src/c++/exercios/setw/main.cpp
|
PedroExpedito/learc
|
bf0311f23860706881f7565c9347db3e40559145
|
[
"MIT"
] | null | null | null |
src/c++/exercios/setw/main.cpp
|
PedroExpedito/learc
|
bf0311f23860706881f7565c9347db3e40559145
|
[
"MIT"
] | 1
|
2020-05-18T12:20:10.000Z
|
2020-05-18T12:20:10.000Z
|
#include <iostream>
#include <iomanip>
#include <string>
// Operador setw ele pega um fluxo e coloca dentro de um campo de N caracteres e
// justifica a direita
using namespace std;
using std::left;
class People {
public:
string name;
int age;
People(const string& name, const int& age) {
this->name.assign(name);
this->age = age;
}
};
int main(void) {
People p1("Pedro",20);
People p2("Marcos", 30);
People p3("Felipe", 33);
cout << setw(20) << left << p1.name << setw(10) << p1.age << endl;
cout << setw(20) << setfill('.') << p2.name << setw(10) << p2.age << endl;
cout << setw(20) << p3.name << setw(10) << p3.age << endl ;
return 0;
}
| 20.382353
| 80
| 0.594517
|
PedroExpedito
|
4c66651c8d769a4a3403d41cc32bbb9a4eda28bb
| 30,629
|
cpp
|
C++
|
avs/vis_avs/r_colormap.cpp
|
semiessessi/vis_avs
|
e99a3803e9de9032e0e6759963b2c2798f3443ef
|
[
"BSD-3-Clause"
] | 18
|
2020-07-30T11:55:23.000Z
|
2022-02-25T02:39:15.000Z
|
avs/vis_avs/r_colormap.cpp
|
semiessessi/vis_avs
|
e99a3803e9de9032e0e6759963b2c2798f3443ef
|
[
"BSD-3-Clause"
] | 34
|
2021-01-13T02:02:12.000Z
|
2022-03-23T12:09:55.000Z
|
avs/vis_avs/r_colormap.cpp
|
semiessessi/vis_avs
|
e99a3803e9de9032e0e6759963b2c2798f3443ef
|
[
"BSD-3-Clause"
] | 3
|
2021-03-18T12:53:58.000Z
|
2021-10-02T20:24:41.000Z
|
/*
Reconstructed by decompiling the original colormap.ape v1.3 binary.
Credits:
Steven Wittens (a.k.a. "Unconed" -> https://acko.net), for the original Colormap,
& the Ghidra authors.
Most of the code deals with handling the UI interactions (all the Win32 UI API calls
were thankfully plainly visible in the decompiled binary), and the actual mapping
code is fairly straightforward.
The original implementation used MMX asm, which has been updated to using SSE2/SSSE3
intrinsics. The code could further be sped up by leveraging the "gather" instructions
available with Intel's AVX2 extension (ca. 2014 and later CPU models) to load colors by
index from the baked map.
*/
#include "c_colormap.h"
#include <cstdio>
#include <time.h>
#include "r_defs.h"
// Integer range-mapping macros. Avoid truncation by multiplying first.
// Map point A from one value range to another.
// Get distance from A to B (in B-range) by mapping A to B.
#define GET_INT() (data[pos] | (data[pos+1] << 8) | (data[pos+2] << 16) | (data[pos+3] << 24))
#define PUT_INT(y) data[pos] = (y) & 0xff; \
data[pos+1] = ((y) >> 8) & 0xff; \
data[pos+2] = ((y) >> 16) & 0xff; \
data[pos+3] = ((y) >> 24) & 0xff
C_ColorMap::C_ColorMap() :
config{
COLORMAP_COLOR_KEY_RED,
COLORMAP_BLENDMODE_REPLACE,
COLORMAP_MAP_CYCLE_NONE,
0, // adjustable alpha
0, // [unused]
0, // don't-skip-fast-beats is unchecked
11, // default map cycle speed
},
current_map{0},
next_map{0},
change_animation_step{COLORMAP_MAP_CYCLE_ANIMATION_STEPS},
disable_map_change{0}
{
for(unsigned int i = 0; i < COLORMAP_NUM_MAPS; i++) {
this->maps[i].enabled = i == 0;
this->maps[i].length = 2;
this->maps[i].map_id = this->get_new_id();
this->maps[i].colors = NULL;
memset(this->maps[i].filename, 0, COLORMAP_MAP_FILENAME_MAXLEN);
this->make_default_map(i);
}
}
C_ColorMap::~C_ColorMap() {
for(unsigned int i = 0; i < COLORMAP_NUM_MAPS; i++) {
delete[] this->maps[i].colors;
}
}
int C_ColorMap::get_new_id() {
return this->next_id++;
}
void C_ColorMap::make_default_map(int map_index) {
delete[] this->maps[map_index].colors;
this->maps[map_index].colors = new map_color[2];
this->maps[map_index].colors[0].position = 0;
this->maps[map_index].colors[0].color = 0x000000;
this->maps[map_index].colors[0].color_id = this->get_new_id();
this->maps[map_index].colors[1].position = 255;
this->maps[map_index].colors[1].color = 0xffffff;
this->maps[map_index].colors[1].color_id = this->get_new_id();
this->bake_full_map(map_index);
}
void C_ColorMap::bake_full_map(int map_index) {
unsigned int cache_index = 0;
unsigned int color_index = 0;
if(this->maps[map_index].length < 1) {
return;
}
this->sort_colors(map_index);
map_color first = this->maps[map_index].colors[0];
for(; cache_index < first.position; cache_index++) {
this->baked_maps[map_index].colors[cache_index] = first.color;
}
for(; color_index < this->maps[map_index].length - 1; color_index++) {
map_color from = this->maps[map_index].colors[color_index];
map_color to = this->maps[map_index].colors[color_index + 1];
for(; cache_index < to.position; cache_index++) {
int rel_i = cache_index - from.position;
int w = to.position - from.position;
int lerp = NUM_COLOR_VALUES * (float)rel_i / (float)w;
this->baked_maps[map_index].colors[cache_index] = BLEND_ADJ_NOMMX(to.color, from.color, lerp);
}
}
map_color last = this->maps[map_index].colors[color_index];
for(; cache_index < NUM_COLOR_VALUES; cache_index++) {
this->baked_maps[map_index].colors[cache_index] = last.color;
}
}
void C_ColorMap::add_map_color(int map_index, unsigned int position, int color) {
if(this->maps[map_index].length >= COLORMAP_MAX_COLORS) {
return;
}
map_color* new_map_colors = new map_color[this->maps[map_index].length + 1];
for(unsigned int i = 0, a = 0; i < this->maps[map_index].length; i++) {
if(a == 0 && position >= this->maps[map_index].colors[i].position) {
new_map_colors[i].position = position;
new_map_colors[i].color = color;
new_map_colors[i].color_id = this->get_new_id();
a = 1;
}
new_map_colors[i + a] = this->maps[map_index].colors[i];
}
map_color* old_map_colors = this->maps[map_index].colors;
this->maps[map_index].colors = new_map_colors;
this->maps[map_index].length += 1;
this->sort_colors(map_index);
delete[] old_map_colors;
}
void C_ColorMap::remove_map_color(int map_index, int remove_id) {
if(this->maps[map_index].length <= 1) {
return;
}
map_color* new_map_colors = new map_color[this->maps[map_index].length];
for(unsigned int i = 0, a = 0; i < this->maps[map_index].length - 1; i++) {
if(this->maps[map_index].colors[i].color_id == remove_id) {
a = 1;
}
new_map_colors[i] = this->maps[map_index].colors[i + a];
}
map_color* old_map_colors = this->maps[map_index].colors;
this->maps[map_index].length -= 1;
this->maps[map_index].colors = new_map_colors;
this->sort_colors(map_index);
delete[] old_map_colors;
}
int compare_colors(const void* color1, const void* color2) {
int diff = ((map_color*)color1)->position - ((map_color*)color2)->position;
if (diff == 0) {
// TODO [bugfix,feature]: If color positions are the same, the brighter color
// gets sorted higher. This is somewhat arbitrary. We should try and sort by
// previous position, so that when dragging a color, it does not flip until its
// position actually becomes less than the other.
diff = ((map_color*)color1)->color - ((map_color*)color2)->color;
}
return diff;
}
void C_ColorMap::sort_colors(int map_index) {
qsort(this->maps[map_index].colors, this->maps[map_index].length, sizeof(map_color), compare_colors);
}
bool C_ColorMap::any_maps_enabled() {
bool any_maps_enabled = false;
for(unsigned int i = 0; i < COLORMAP_NUM_MAPS; i++) {
if(this->maps[i].enabled) {
any_maps_enabled = true;
break;
}
}
return any_maps_enabled;
}
baked_map* C_ColorMap::animate_map_frame(int is_beat) {
this->next_map %= COLORMAP_NUM_MAPS;
if(this->config.map_cycle_mode == COLORMAP_MAP_CYCLE_NONE || this->disable_map_change) {
this->change_animation_step = 0;
return &this->baked_maps[this->current_map];
} else {
this->change_animation_step += this->config.map_cycle_speed;
this->change_animation_step = min(this->change_animation_step, COLORMAP_MAP_CYCLE_ANIMATION_STEPS);
if(is_beat && (!this->config.dont_skip_fast_beats || this->change_animation_step == COLORMAP_MAP_CYCLE_ANIMATION_STEPS)) {
if(this->any_maps_enabled()) {
do {
if(this->config.map_cycle_mode == COLORMAP_MAP_CYCLE_BEAT_RANDOM) {
this->next_map = rand() % COLORMAP_NUM_MAPS;
} else{
this->next_map = (this->next_map + 1) % COLORMAP_NUM_MAPS;
}
} while(!this->maps[this->next_map].enabled);
}
this->change_animation_step = 0;
}
if(this->change_animation_step == 0) {
this->reset_tween_map();
} else if(this->change_animation_step == COLORMAP_MAP_CYCLE_ANIMATION_STEPS) {
this->current_map = this->next_map;
this->reset_tween_map();
} else {
if(this->current_map != this->next_map) {
this->animation_step();
} else {
this->reset_tween_map();
}
}
return &this->tween_map;
}
}
inline void C_ColorMap::animation_step() {
for(unsigned int i = 0; i < NUM_COLOR_VALUES; i++) {
this->tween_map.colors[i] = BLEND_ADJ_NOMMX(
this->baked_maps[this->next_map].colors[i],
this->baked_maps[this->current_map].colors[i],
this->change_animation_step
);
}
return;
}
inline void C_ColorMap::animation_step_sse2() {
for(unsigned int i = 0; i < NUM_COLOR_VALUES; i += 4) {
// __m128i four_current_values = _mm_loadu_si128((__m128i*)&(this->baked_maps[this->current_map].colors[i]));
// __m128i four_next_values = _mm_loadu_si128((__m128i*)&(this->baked_maps[this->next_map].colors[i]));
// __m128i blend_lerp = _mm_set1_epi8((unsigned char)this->change_animation_step);
/* TODO */
}
return;
}
inline void C_ColorMap::reset_tween_map() {
memcpy(&this->tween_map, &this->baked_maps[this->current_map], sizeof(baked_map));
}
inline int C_ColorMap::get_key(int color) {
int r, g, b;
switch(this->config.color_key) {
case COLORMAP_COLOR_KEY_RED:
return color >> 16 & 0xff;
case COLORMAP_COLOR_KEY_GREEN:
return color >> 8 & 0xff;
case COLORMAP_COLOR_KEY_BLUE:
return color & 0xff;
case COLORMAP_COLOR_KEY_RGB_SUM_HALF:
return min(((color >> 16 & 0xff) + (color >> 8 & 0xff) + (color & 0xff)) / 2, NUM_COLOR_VALUES - 1);
case COLORMAP_COLOR_KEY_MAX:
r = color >> 16 & 0xff;
g = color >> 8 & 0xff;
b = color & 0xff;
r = max(r, g);
return max(r, b);
default:
case COLORMAP_COLOR_KEY_RGB_AVERAGE:
return ((color >> 16 & 0xff) + (color >> 8 & 0xff) + (color & 0xff)) / 3;
}
}
void C_ColorMap::blend(baked_map* blend_map, int *framebuffer, int w, int h) {
int four_px_colors[4];
int four_keys[4];
switch(this->config.blendmode) {
case COLORMAP_BLENDMODE_REPLACE:
for(int i = 0; i < w * h; i += 4) {
for(int k = 0; k < 4; k++) {
four_keys[k] = this->get_key(framebuffer[i + k]);
framebuffer[i + k] = blend_map->colors[four_keys[k]];
}
}
break;
case COLORMAP_BLENDMODE_ADDITIVE:
for(int i = 0; i < w * h; i += 4) {
for(int k = 0; k < 4; k++) {
four_keys[k] = this->get_key(framebuffer[i + k]);
four_px_colors[k] = blend_map->colors[four_keys[k]];
framebuffer[i + k] = BLEND(framebuffer[i + k], four_px_colors[k]);
}
}
break;
case COLORMAP_BLENDMODE_MAXIMUM:
for(int i = 0; i < w * h; i += 4) {
for(int k = 0; k < 4; k++) {
four_keys[k] = this->get_key(framebuffer[i + k]);
four_px_colors[k] = blend_map->colors[four_keys[k]];
framebuffer[i + k] = BLEND_MAX(framebuffer[i + k], four_px_colors[k]);
}
}
break;
case COLORMAP_BLENDMODE_MINIMUM:
for(int i = 0; i < w * h; i += 4) {
for(int k = 0; k < 4; k++) {
four_keys[k] = this->get_key(framebuffer[i + k]);
four_px_colors[k] = blend_map->colors[four_keys[k]];
framebuffer[i + k] = BLEND_MIN(framebuffer[i + k], four_px_colors[k]);
}
}
break;
case COLORMAP_BLENDMODE_5050:
for(int i = 0; i < w * h; i += 4) {
for(int k = 0; k < 4; k++) {
four_keys[k] = this->get_key(framebuffer[i + k]);
four_px_colors[k] = blend_map->colors[four_keys[k]];
framebuffer[i + k] = BLEND_AVG(framebuffer[i + k], four_px_colors[k]);
}
}
break;
case COLORMAP_BLENDMODE_SUB1:
for(int i = 0; i < w * h; i += 4) {
for(int k = 0; k < 4; k++) {
four_keys[k] = this->get_key(framebuffer[i + k]);
four_px_colors[k] = blend_map->colors[four_keys[k]];
framebuffer[i + k] = BLEND_SUB(framebuffer[i + k], four_px_colors[k]);
}
}
break;
case COLORMAP_BLENDMODE_SUB2:
for(int i = 0; i < w * h; i += 4) {
for(int k = 0; k < 4; k++) {
four_keys[k] = this->get_key(framebuffer[i + k]);
four_px_colors[k] = blend_map->colors[four_keys[k]];
framebuffer[i + k] = BLEND_SUB(four_px_colors[k], framebuffer[i + k]);
}
}
break;
case COLORMAP_BLENDMODE_MULTIPLY:
for(int i = 0; i < w * h; i += 4) {
for(int k = 0; k < 4; k++) {
four_keys[k] = this->get_key(framebuffer[i + k]);
four_px_colors[k] = blend_map->colors[four_keys[k]];
framebuffer[i + k] = BLEND_MUL(framebuffer[i + k], four_px_colors[k]);
}
}
break;
case COLORMAP_BLENDMODE_XOR:
for(int i = 0; i < w * h; i += 4) {
for(int k = 0; k < 4; k++) {
four_keys[k] = this->get_key(framebuffer[i + k]);
four_px_colors[k] = blend_map->colors[four_keys[k]];
framebuffer[i + k] ^= four_px_colors[k];
}
}
break;
case COLORMAP_BLENDMODE_ADJUSTABLE:
for(int i = 0; i < w * h; i += 4) {
for(int k = 0; k < 4; k++) {
four_keys[k] = this->get_key(framebuffer[i + k]);
four_px_colors[k] = blend_map->colors[four_keys[k]];
framebuffer[i + k] = BLEND_ADJ_NOMMX(four_px_colors[k], framebuffer[i + k], this->config.adjustable_alpha);
}
}
break;
}
}
inline __m128i C_ColorMap::get_key_ssse3(__m128i color4) {
// Gather uint8s from certain source locations. (0xff => dest will be zero.) Collect
// the respective channels into the pixel's lower 8bits.
__m128i gather_red = _mm_set_epi32(0xffffff0e, 0xffffff0a, 0xffffff06, 0xffffff02);
__m128i gather_green = _mm_set_epi32(0xffffff0d, 0xffffff09, 0xffffff05, 0xffffff01);
__m128i gather_blue = _mm_set_epi32(0xffffff0c, 0xffffff08, 0xffffff04, 0xffffff00);
__m128i max_channel_value = _mm_set1_epi32(NUM_COLOR_VALUES - 1);
__m128i r, g;
__m128 color4f;
switch(this->config.color_key) {
case COLORMAP_COLOR_KEY_RED:
return _mm_shuffle_epi8(color4, gather_red);
case COLORMAP_COLOR_KEY_GREEN:
return _mm_shuffle_epi8(color4, gather_green);
case COLORMAP_COLOR_KEY_BLUE:
return _mm_shuffle_epi8(color4, gather_blue);
case COLORMAP_COLOR_KEY_RGB_SUM_HALF:
r = _mm_shuffle_epi8(color4, gather_red);
g = _mm_shuffle_epi8(color4, gather_green);
color4 = _mm_shuffle_epi8(color4, gather_blue);
color4 = _mm_add_epi32(color4, r);
// Correct average, round up on odd sum, i.e.: (a+b+c + 1) >> 1:
//color4 = _mm_avg_epu16(color4, g);
// Original Colormap behavior, round down on .5, i.e. (a+b+c) >> 1:
color4 = _mm_add_epi32(color4, g);
color4 = _mm_srli_epi32(color4, 1);
return _mm_min_epi16(color4, max_channel_value);
case COLORMAP_COLOR_KEY_MAX:
r = _mm_shuffle_epi8(color4, gather_red);
g = _mm_shuffle_epi8(color4, gather_green);
color4 = _mm_shuffle_epi8(color4, gather_blue);
color4 = _mm_max_epu8(color4, r);
return _mm_max_epu8(color4, g);
default:
case COLORMAP_COLOR_KEY_RGB_AVERAGE:
r = _mm_shuffle_epi8(color4, gather_red);
g = _mm_shuffle_epi8(color4, gather_green);
color4 = _mm_shuffle_epi8(color4, gather_blue);
color4 = _mm_add_epi16(color4, r);
color4 = _mm_add_epi16(color4, g);
// For inputs up to 255 * 3, float32 division returns the same results as
// integer division
color4f = _mm_cvtepi32_ps(color4);
color4f = _mm_div_ps(color4f, _mm_set1_ps(3.0f));
return _mm_cvtps_epi32(color4f);
}
}
void C_ColorMap::blend_ssse3(baked_map* blend_map, int *framebuffer, int w, int h) {
__m128i framebuffer_4px;
int four_keys[4];
__m128i colors_4px;
__m128i extend_lo_p8_to_p16 = _mm_set_epi32(0xff07ff06, 0xff05ff04, 0xff03ff02, 0xff01ff00);
__m128i extend_hi_p8_to_p16 = _mm_set_epi32(0xff0fff0e, 0xff0dff0c, 0xff0bff0a, 0xff09ff08);
__m128i framebuffer_2_px[2];
__m128i colors_2_px[2];
switch(this->config.blendmode) {
case COLORMAP_BLENDMODE_REPLACE:
for(int i = 0; i < w * h; i += 4) {
framebuffer_4px = _mm_loadu_si128((__m128i*)&framebuffer[i]);
_mm_store_si128((__m128i*)four_keys, this->get_key_ssse3(framebuffer_4px));
for(int k = 0; k < 4; k++) {
framebuffer[i + k] = blend_map->colors[four_keys[k]];
}
}
break;
case COLORMAP_BLENDMODE_ADDITIVE:
for(int i = 0; i < w * h; i += 4) {
framebuffer_4px = _mm_loadu_si128((__m128i*)&framebuffer[i]);
_mm_store_si128((__m128i*)four_keys, this->get_key_ssse3(framebuffer_4px));
colors_4px = _mm_set_epi32(blend_map->colors[four_keys[3]],
blend_map->colors[four_keys[2]],
blend_map->colors[four_keys[1]],
blend_map->colors[four_keys[0]]);
framebuffer_4px = _mm_adds_epu8(framebuffer_4px, colors_4px);
_mm_store_si128((__m128i*)&framebuffer[i], framebuffer_4px);
}
break;
case COLORMAP_BLENDMODE_MAXIMUM:
for(int i = 0; i < w * h; i += 4) {
framebuffer_4px = _mm_loadu_si128((__m128i*)&framebuffer[i]);
_mm_store_si128((__m128i*)four_keys, this->get_key_ssse3(framebuffer_4px));
colors_4px = _mm_set_epi32(blend_map->colors[four_keys[3]],
blend_map->colors[four_keys[2]],
blend_map->colors[four_keys[1]],
blend_map->colors[four_keys[0]]);
framebuffer_4px = _mm_max_epu8(framebuffer_4px, colors_4px);
_mm_store_si128((__m128i*)&framebuffer[i], framebuffer_4px);
}
break;
case COLORMAP_BLENDMODE_MINIMUM:
for(int i = 0; i < w * h; i += 4) {
framebuffer_4px = _mm_loadu_si128((__m128i*)&framebuffer[i]);
_mm_store_si128((__m128i*)four_keys, this->get_key_ssse3(framebuffer_4px));
colors_4px = _mm_set_epi32(blend_map->colors[four_keys[3]],
blend_map->colors[four_keys[2]],
blend_map->colors[four_keys[1]],
blend_map->colors[four_keys[0]]);
framebuffer_4px = _mm_min_epu8(framebuffer_4px, colors_4px);
_mm_store_si128((__m128i*)&framebuffer[i], framebuffer_4px);
}
break;
case COLORMAP_BLENDMODE_5050:
for(int i = 0; i < w * h; i += 4) {
framebuffer_4px = _mm_loadu_si128((__m128i*)&framebuffer[i]);
_mm_store_si128((__m128i*)four_keys, this->get_key_ssse3(framebuffer_4px));
colors_4px = _mm_set_epi32(blend_map->colors[four_keys[3]],
blend_map->colors[four_keys[2]],
blend_map->colors[four_keys[1]],
blend_map->colors[four_keys[0]]);
framebuffer_4px = _mm_avg_epu8(framebuffer_4px, colors_4px);
_mm_store_si128((__m128i*)&framebuffer[i], framebuffer_4px);
}
break;
case COLORMAP_BLENDMODE_SUB1:
for(int i = 0; i < w * h; i += 4) {
framebuffer_4px = _mm_loadu_si128((__m128i*)&framebuffer[i]);
_mm_store_si128((__m128i*)four_keys, this->get_key_ssse3(framebuffer_4px));
colors_4px = _mm_set_epi32(blend_map->colors[four_keys[3]],
blend_map->colors[four_keys[2]],
blend_map->colors[four_keys[1]],
blend_map->colors[four_keys[0]]);
framebuffer_4px = _mm_subs_epu8(framebuffer_4px, colors_4px);
_mm_store_si128((__m128i*)&framebuffer[i], framebuffer_4px);
}
break;
case COLORMAP_BLENDMODE_SUB2:
for(int i = 0; i < w * h; i += 4) {
framebuffer_4px = _mm_loadu_si128((__m128i*)&framebuffer[i]);
_mm_store_si128((__m128i*)four_keys, this->get_key_ssse3(framebuffer_4px));
colors_4px = _mm_set_epi32(blend_map->colors[four_keys[3]],
blend_map->colors[four_keys[2]],
blend_map->colors[four_keys[1]],
blend_map->colors[four_keys[0]]);
framebuffer_4px = _mm_subs_epu8(colors_4px, framebuffer_4px);
_mm_store_si128((__m128i*)&framebuffer[i], framebuffer_4px);
}
break;
case COLORMAP_BLENDMODE_MULTIPLY:
for(int i = 0; i < w * h; i += 4) {
framebuffer_4px = _mm_loadu_si128((__m128i*)&framebuffer[i]);
_mm_store_si128((__m128i*)four_keys, this->get_key_ssse3(framebuffer_4px));
colors_4px = _mm_set_epi32(blend_map->colors[four_keys[3]],
blend_map->colors[four_keys[2]],
blend_map->colors[four_keys[1]],
blend_map->colors[four_keys[0]]);
// Unfortunately intel CPUs do not have a packed unsigned 8bit multiply.
// So the calculation becomes a matter of extending both sides of the
// multiplication to 16 bits, which doubles the size, resulting in 2
// packed 128bit values.
framebuffer_2_px[0] = _mm_shuffle_epi8(framebuffer_4px, extend_lo_p8_to_p16);
framebuffer_2_px[1] = _mm_shuffle_epi8(framebuffer_4px, extend_hi_p8_to_p16);
colors_2_px[0] = _mm_shuffle_epi8(colors_4px, extend_lo_p8_to_p16);
colors_2_px[1] = _mm_shuffle_epi8(colors_4px, extend_hi_p8_to_p16);
// We can then packed-multiply the half-filled 16bit (only the lower 8
// bits are non-zero) values. Thus we are interested only in the lower
// 16 bits of the 32bit result.
framebuffer_2_px[0] = _mm_mullo_epi16(framebuffer_2_px[0], colors_2_px[0]);
framebuffer_2_px[1] = _mm_mullo_epi16(framebuffer_2_px[1], colors_2_px[1]);
// Divide by 256 again, to normalize. This loses accuracy, because
// 0xff * 0xff => 0xfe, but it's the way Multiply works throughout AVS.
framebuffer_2_px[0] = _mm_srli_epi16(framebuffer_2_px[0], 8);
framebuffer_2_px[1] = _mm_srli_epi16(framebuffer_2_px[1], 8);
// Pack the expanded 16bit values back into 8bit values.
framebuffer_4px = _mm_packus_epi16(framebuffer_2_px[0], framebuffer_2_px[1]);
_mm_store_si128((__m128i*)&framebuffer[i], framebuffer_4px);
}
break;
case COLORMAP_BLENDMODE_XOR:
for(int i = 0; i < w * h; i += 4) {
framebuffer_4px = _mm_loadu_si128((__m128i*)&framebuffer[i]);
_mm_store_si128((__m128i*)four_keys, this->get_key_ssse3(framebuffer_4px));
colors_4px = _mm_set_epi32(blend_map->colors[four_keys[3]],
blend_map->colors[four_keys[2]],
blend_map->colors[four_keys[1]],
blend_map->colors[four_keys[0]]);
framebuffer_4px = _mm_xor_si128(framebuffer_4px, colors_4px);
_mm_store_si128((__m128i*)&framebuffer[i], framebuffer_4px);
}
break;
case COLORMAP_BLENDMODE_ADJUSTABLE:
__m128i v = _mm_set1_epi16((unsigned char)this->config.adjustable_alpha);
__m128i i_v = _mm_set1_epi16(COLORMAP_ADJUSTABLE_BLEND_MAX - this->config.adjustable_alpha);
for(int i = 0; i < w * h; i += 4) {
framebuffer_4px = _mm_loadu_si128((__m128i*)&framebuffer[i]);
_mm_store_si128((__m128i*)four_keys, this->get_key_ssse3(framebuffer_4px));
colors_4px = _mm_set_epi32(blend_map->colors[four_keys[3]],
blend_map->colors[four_keys[2]],
blend_map->colors[four_keys[1]],
blend_map->colors[four_keys[0]]);
// See Multiply blend case for details. This is basically the same
// thing, except that each side gets multiplied with v and 1-v
// respectively and then added together.
framebuffer_2_px[0] = _mm_shuffle_epi8(framebuffer_4px, extend_lo_p8_to_p16);
framebuffer_2_px[1] = _mm_shuffle_epi8(framebuffer_4px, extend_hi_p8_to_p16);
colors_2_px[0] = _mm_shuffle_epi8(colors_4px, extend_lo_p8_to_p16);
colors_2_px[1] = _mm_shuffle_epi8(colors_4px, extend_hi_p8_to_p16);
framebuffer_2_px[0] = _mm_mullo_epi16(framebuffer_2_px[0], i_v);
framebuffer_2_px[1] = _mm_mullo_epi16(framebuffer_2_px[1], i_v);
colors_2_px[0] = _mm_mullo_epi16(colors_2_px[0], v);
colors_2_px[1] = _mm_mullo_epi16(colors_2_px[1], v);
framebuffer_2_px[0] = _mm_adds_epu16(framebuffer_2_px[0], colors_2_px[0]);
framebuffer_2_px[1] = _mm_adds_epu16(framebuffer_2_px[1], colors_2_px[1]);
framebuffer_2_px[0] = _mm_srli_epi16(framebuffer_2_px[0], 8);
framebuffer_2_px[1] = _mm_srli_epi16(framebuffer_2_px[1], 8);
framebuffer_4px = _mm_packus_epi16(framebuffer_2_px[0], framebuffer_2_px[1]);
_mm_store_si128((__m128i*)&framebuffer[i], framebuffer_4px);
}
break;
}
}
int C_ColorMap::render(char visdata[2][2][576], int is_beat, int *framebuffer, int *fbout, int w, int h) {
(void)visdata;
(void)fbout;
baked_map* blend_map = this->animate_map_frame(is_beat);
this->blend_ssse3(blend_map, framebuffer, w, h);
return 0;
}
char *C_ColorMap::get_desc(void) {
return MOD_NAME;
}
bool C_ColorMap::load_map_header(unsigned char *data, int len, int map_index, int pos) {
if(len - pos < (int)COLORMAP_SAVE_MAP_HEADER_SIZE) {
return false;
}
this->maps[map_index].enabled = GET_INT();
pos += 4;
this->maps[map_index].length = GET_INT();
pos += 4;
this->maps[map_index].map_id = this->get_new_id();
pos += 4;
strncpy(this->maps[map_index].filename, (char*)&data[pos], COLORMAP_MAP_FILENAME_MAXLEN - 1);
this->maps[map_index].filename[COLORMAP_MAP_FILENAME_MAXLEN - 1] = '\0';
return true;
}
bool C_ColorMap::load_map_colors(unsigned char *data, int len, int map_index, int pos) {
delete[] this->maps[map_index].colors;
this->maps[map_index].colors = new map_color[this->maps[map_index].length];
unsigned int i;
for(i = 0; i < this->maps[map_index].length; i++) {
if(len - pos < (int)sizeof(map_color)) {
return false;
}
this->maps[map_index].colors[i].position = GET_INT();
pos += 4;
this->maps[map_index].colors[i].color = GET_INT();
pos += 4;
this->maps[map_index].colors[i].color_id = this->get_new_id();
pos += 4;
}
return true;
}
void C_ColorMap::load_config(unsigned char *data, int len) {
if (len >= (int)sizeof(colormap_apeconfig))
memcpy(&this->config, data, sizeof(colormap_apeconfig));
bool success = true;
unsigned int pos = sizeof(colormap_apeconfig);
for(int map_index = 0; map_index < COLORMAP_NUM_MAPS; map_index++) {
success = this->load_map_header(data, len, map_index, pos);
pos += COLORMAP_SAVE_MAP_HEADER_SIZE;
}
for(int map_index = 0; map_index < COLORMAP_NUM_MAPS; map_index++) {
success = this->load_map_colors(data, len, map_index, pos);
if(!success) {
break;
}
this->bake_full_map(map_index);
pos += this->maps[map_index].length * sizeof(map_color);
}
}
int C_ColorMap::save_config(unsigned char *data) {
memcpy(data, &this->config, sizeof(colormap_apeconfig));
int pos = sizeof(colormap_apeconfig);
for(int map_index = 0; map_index < COLORMAP_NUM_MAPS; map_index++) {
PUT_INT(this->maps[map_index].enabled);
pos += 4;
PUT_INT(this->maps[map_index].length);
pos += 4;
PUT_INT(this->maps[map_index].map_id);
pos += 4;
memset((char*)&data[pos], 0, COLORMAP_MAP_FILENAME_MAXLEN);
strncpy((char*)&data[pos], this->maps[map_index].filename, COLORMAP_MAP_FILENAME_MAXLEN - 1);
pos += COLORMAP_MAP_FILENAME_MAXLEN;
}
for(int map_index = 0; map_index < COLORMAP_NUM_MAPS; map_index++) {
for(unsigned int i = 0; i < this->maps[map_index].length; i++) {
PUT_INT(this->maps[map_index].colors[i].position);
pos += 4;
PUT_INT(this->maps[map_index].colors[i].color);
pos += 4;
PUT_INT(this->maps[map_index].colors[i].color_id);
pos += 4;
}
}
return pos;
}
C_RBASE *R_ColorMap(char *desc) {
srand(time(NULL));
if (desc) {
strcpy(desc, MOD_NAME);
return NULL;
}
return (C_RBASE *) new C_ColorMap();
}
| 46.128012
| 130
| 0.576676
|
semiessessi
|
4c68adc5dd974c8b3bea3a17e0368e16acf8262d
| 598
|
cpp
|
C++
|
LazyFibonacci/Solution/Fibonacci.cpp
|
AssafTzurEl/interview-workshop
|
fe070eb660488723f5f6e878ac8441291bb1559e
|
[
"MIT"
] | null | null | null |
LazyFibonacci/Solution/Fibonacci.cpp
|
AssafTzurEl/interview-workshop
|
fe070eb660488723f5f6e878ac8441291bb1559e
|
[
"MIT"
] | null | null | null |
LazyFibonacci/Solution/Fibonacci.cpp
|
AssafTzurEl/interview-workshop
|
fe070eb660488723f5f6e878ac8441291bb1559e
|
[
"MIT"
] | null | null | null |
#include "Fibonacci.h"
Fibonacci::fsize_t Fibonacci::Get(size_t n)
{
if (s_cache.size() <= n)
{
// n hasn't been requested before, build it:
auto fib_n = Get(n - 1) + Get(n - 2);
// then populate the cache, to allow laziness in the future:
s_cache.push_back(fib_n);
}
// else - n is already in. Either way, we now have it cached:
return s_cache[n];
}
// Don't forget to initialize your statics!
// Starting with two values, to prevent the call to "Get(n-2)" above from being negative.
std::vector<Fibonacci::fsize_t> Fibonacci::s_cache{ 0, 1 };
| 33.222222
| 89
| 0.638796
|
AssafTzurEl
|
4c69010ccad5c58056ce9790cfc9bfd73bfb7966
| 7,805
|
cpp
|
C++
|
test/test_mains/all_tests.cpp
|
BlaMaeda/abed
|
b10eebd2155d22d516ea5c6a1c31c45128a37122
|
[
"BSD-3-Clause"
] | null | null | null |
test/test_mains/all_tests.cpp
|
BlaMaeda/abed
|
b10eebd2155d22d516ea5c6a1c31c45128a37122
|
[
"BSD-3-Clause"
] | null | null | null |
test/test_mains/all_tests.cpp
|
BlaMaeda/abed
|
b10eebd2155d22d516ea5c6a1c31c45128a37122
|
[
"BSD-3-Clause"
] | null | null | null |
#include <iostream>
#include <vector>
#include "../include/dataset.hpp"
#include "../include/mlp.hpp"
#include "../include/tester.hpp"
#include "../include/perceptron.hpp"
#include "../include/bagging.hpp"
#include "../include/svm.hpp"
using namespace std;
using namespace abed;
void test_mlp () {
const double MLP_IRIS = 0.93;
const double MLP_ECOLI = 0.78;
const double MLP_YEAST = 0.49;
const double MAX_ERROR = 0.05;
const unsigned int MAX_IT = 100; //XXX
const unsigned int NO_FOLDS = 3;
Classifier* classifier;
// IRIS
{
StaticDataSet sds("iris.ssv");
unsigned int dimension = sds.get_dimension();
unsigned int no_classes = sds.get_no_classes();
vector<unsigned int> hl;
hl.push_back(dimension);
hl.push_back(dimension);
classifier = new MLP(dimension, no_classes, hl);
Tester tester(classifier, &sds);
tester.cross_validation(NO_FOLDS, MAX_ERROR, MAX_IT);
cout << "MLP - IRIS" << endl;
cout << "Expected value: ~" << MLP_IRIS << endl;
cout << "Obtained value: " << tester.get_percentage() << endl;
cout << "---------------" << endl;
delete classifier;
}
// ECOLI
{
StaticDataSet sds("ecoli.ssv");
unsigned int dimension = sds.get_dimension();
unsigned int no_classes = sds.get_no_classes();
vector<unsigned int> hl;
hl.push_back(dimension);
hl.push_back(dimension);
classifier = new MLP(dimension, no_classes, hl);
Tester tester(classifier, &sds);
tester.cross_validation(NO_FOLDS, MAX_ERROR, MAX_IT);
cout << "MLP - ECOLI" << endl;
cout << "Expected value: ~" << MLP_ECOLI << endl;
cout << "Obtained value: " << tester.get_percentage() << endl;
cout << "---------------" << endl;
delete classifier;
}
// YEAST
{
StaticDataSet sds("yeast.ssv");
unsigned int dimension = sds.get_dimension();
unsigned int no_classes = sds.get_no_classes();
vector<unsigned int> hl;
hl.push_back(dimension);
hl.push_back(dimension);
classifier = new MLP(dimension, no_classes, hl);
Tester tester(classifier, &sds);
tester.cross_validation(NO_FOLDS, MAX_ERROR, MAX_IT);
cout << "MLP - YEAST" << endl;
cout << "Expected value: ~" << MLP_YEAST << endl;
cout << "Obtained value: " << tester.get_percentage() << endl;
cout << "---------------" << endl;
delete classifier;
}
}
void test_svm () {
const double SVM_IRIS = 0.96;
const double SVM_ECOLI = 0.74;
const double SVM_YEAST = 0.35;
const double MAX_ERROR = 0.05;
const unsigned int MAX_IT = 1000;
const unsigned int NO_FOLDS = 3;
Classifier* classifier;
// IRIS
{
StaticDataSet sds("iris.ssv");
unsigned int dimension = sds.get_dimension();
unsigned int no_classes = sds.get_no_classes();
classifier = new SVM(dimension, no_classes);
Tester tester(classifier, &sds);
tester.cross_validation(NO_FOLDS, MAX_ERROR, MAX_IT);
cout << "SVM - IRIS" << endl;
cout << "Expected value: ~" << SVM_IRIS << endl;
cout << "Obtained value: " << tester.get_percentage() << endl;
cout << "---------------" << endl;
delete classifier;
}
// ECOLI
{
StaticDataSet sds("ecoli.ssv");
unsigned int dimension = sds.get_dimension();
unsigned int no_classes = sds.get_no_classes();
classifier = new SVM(dimension, no_classes);
Tester tester(classifier, &sds);
tester.cross_validation(NO_FOLDS, MAX_ERROR, MAX_IT);
cout << "SVM - ECOLI" << endl;
cout << "Expected value: ~" << SVM_ECOLI << endl;
cout << "Obtained value: " << tester.get_percentage() << endl;
cout << "---------------" << endl;
delete classifier;
}
// YEAST
{
StaticDataSet sds("yeast.ssv");
unsigned int dimension = sds.get_dimension();
unsigned int no_classes = sds.get_no_classes();
classifier = new SVM(dimension, no_classes);
Tester tester(classifier, &sds);
tester.cross_validation(NO_FOLDS, MAX_ERROR, MAX_IT);
cout << "SVM - YEAST" << endl;
cout << "Expected value: ~" << SVM_YEAST << endl;
cout << "Obtained value: " << tester.get_percentage() << endl;
cout << "---------------" << endl;
delete classifier;
}
}
void test_bagging_mlp () {
const double BAG_MLP_IRIS = 0.94;
const double BAG_MLP_ECOLI = 0.85;
const double BAG_MLP_YEAST = 0.54;
const double MAX_ERROR = 0.05;
const unsigned int MAX_IT = 1000;
const unsigned int NO_FOLDS = 3;
// IRIS
{
StaticDataSet sds("iris.ssv");
unsigned int dimension = sds.get_dimension();
unsigned int no_classes = sds.get_no_classes();
Bagging bagging(dimension, no_classes);
vector<unsigned int> hl;
hl.push_back(dimension);
bagging.add_classifier(new MLP(dimension, no_classes, hl));
bagging.add_classifier(new MLP(dimension, no_classes, hl));
bagging.add_classifier(new MLP(dimension, no_classes, hl));
bagging.add_classifier(new MLP(dimension, no_classes, hl));
bagging.add_classifier(new MLP(dimension, no_classes, hl));
Tester tester(&bagging, &sds);
tester.cross_validation(NO_FOLDS, MAX_ERROR, MAX_IT);
cout << "Bagging-MLP - IRIS" << endl;
cout << "Expected value: ~" << BAG_MLP_IRIS << endl;
cout << "Obtained value: " << tester.get_percentage() << endl;
cout << "---------------" << endl;
}
// ECOLI
{
StaticDataSet sds("ecoli.ssv");
unsigned int dimension = sds.get_dimension();
unsigned int no_classes = sds.get_no_classes();
Bagging bagging(dimension, no_classes);
vector<unsigned int> hl;
hl.push_back(dimension);
bagging.add_classifier(new MLP(dimension, no_classes, hl));
bagging.add_classifier(new MLP(dimension, no_classes, hl));
bagging.add_classifier(new MLP(dimension, no_classes, hl));
bagging.add_classifier(new MLP(dimension, no_classes, hl));
bagging.add_classifier(new MLP(dimension, no_classes, hl));
Tester tester(&bagging, &sds);
tester.cross_validation(NO_FOLDS, MAX_ERROR, MAX_IT);
cout << "Bagging-MLP - ECOLI" << endl;
cout << "Expected value: ~" << BAG_MLP_ECOLI << endl;
cout << "Obtained value: " << tester.get_percentage() << endl;
cout << "---------------" << endl;
}
// YEAST
{
StaticDataSet sds("yeast.ssv");
unsigned int dimension = sds.get_dimension();
unsigned int no_classes = sds.get_no_classes();
Bagging bagging(dimension, no_classes);
vector<unsigned int> hl;
hl.push_back(dimension);
bagging.add_classifier(new MLP(dimension, no_classes, hl));
bagging.add_classifier(new MLP(dimension, no_classes, hl));
bagging.add_classifier(new MLP(dimension, no_classes, hl));
bagging.add_classifier(new MLP(dimension, no_classes, hl));
bagging.add_classifier(new MLP(dimension, no_classes, hl));
Tester tester(&bagging, &sds);
tester.cross_validation(NO_FOLDS, MAX_ERROR, MAX_IT);
cout << "Bagging-MLP - YEAST" << endl;
cout << "Expected value: ~" << BAG_MLP_YEAST << endl;
cout << "Obtained value: " << tester.get_percentage() << endl;
cout << "---------------" << endl;
}
}
// All tests
int main () {
srand(time(NULL));
//test_mlp();
//test_svm();
test_bagging_mlp();
return 0;
}
| 32.252066
| 70
| 0.594619
|
BlaMaeda
|
4c6ac57505c53becc16588dab2b3661fdcde7269
| 10,564
|
cpp
|
C++
|
src/game/shared/swarm/asw_powerup_shared.cpp
|
BlueNovember/alienswarm-reactivedrop
|
ffaca58157f9fdd36e5c48e8d7d34d8ca958017e
|
[
"CC0-1.0"
] | null | null | null |
src/game/shared/swarm/asw_powerup_shared.cpp
|
BlueNovember/alienswarm-reactivedrop
|
ffaca58157f9fdd36e5c48e8d7d34d8ca958017e
|
[
"CC0-1.0"
] | null | null | null |
src/game/shared/swarm/asw_powerup_shared.cpp
|
BlueNovember/alienswarm-reactivedrop
|
ffaca58157f9fdd36e5c48e8d7d34d8ca958017e
|
[
"CC0-1.0"
] | null | null | null |
#include "cbase.h"
#ifdef CLIENT_DLL
#include "c_asw_player.h"
#include "c_asw_marine.h"
#include "c_asw_weapon.h"
#include "c_asw_marine_resource.h"
#define CASW_Marine C_ASW_Marine
#define CASW_Weapon C_ASW_Weapon
#define CASW_Pickup C_ASW_Pickup
#define CASW_Powerup C_ASW_Powerup
#define CASW_Powerup_Bullets C_ASW_Powerup_Bullets
#define CASW_Powerup_Freeze_Bullets C_ASW_Powerup_Freeze_Bullets
#define CASW_Powerup_Fire_Bullets C_ASW_Powerup_Fire_Bullets
#define CASW_Powerup_Electric_Bullets C_ASW_Powerup_Electric_Bullets
#define CASW_Powerup_Chemical_Bullets C_ASW_Powerup_Chemical_Bullets
#define CASW_Powerup_Explosive_Bullets C_ASW_Powerup_Explosive_Bullets
#define CASW_Powerup_Increased_Speed C_ASW_Powerup_Increased_Speed
#else
#include "asw_game_resource.h"
#include "asw_marine.h"
#include "asw_weapon.h"
#include "asw_player.h"
#include "asw_marine_resource.h"
#include "cvisibilitymonitor.h"
#endif
#include "particle_parse.h"
#include "asw_gamerules.h"
#include "asw_shareddefs.h"
#include "asw_powerup_shared.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define ITEM_PICKUP_BOX_BLOAT_POWERUP 38
#define PICKUP_POWERUP_VISIBILITY_RANGE 500.0f
//IMPLEMENT_SERVERCLASS_ST(CASW_Powerup, DT_ASW_Powerup)
//END_SEND_TABLE()
IMPLEMENT_NETWORKCLASS_ALIASED( ASW_Powerup, DT_ASW_Powerup );
BEGIN_NETWORK_TABLE( CASW_Powerup, DT_ASW_Powerup )
#ifndef CLIENT_DLL
#else
#endif
END_NETWORK_TABLE()
LINK_ENTITY_TO_CLASS( asw_powerup, CASW_Powerup );
PRECACHE_REGISTER( asw_powerup );
ConVar asw_powerup_friction( "asw_powerup_friction", "-0.5f", FCVAR_CHEAT | FCVAR_REPLICATED );
ConVar asw_powerup_gravity( "asw_powerup_gravity", "1.0f", FCVAR_CHEAT | FCVAR_REPLICATED );
ConVar asw_powerup_elasticity( "asw_powerup_elasticity", "0.6f", FCVAR_CHEAT | FCVAR_REPLICATED );
CASW_Powerup::CASW_Powerup()
{
m_nPowerupType = 0;
m_flPowerupDuration = -1;
m_flCanPickupMaxTime = 0;
m_bSpawnDelayDenyPickup = true;
}
CASW_Powerup::~CASW_Powerup()
{
}
#ifndef CLIENT_DLL
void CASW_Powerup::Spawn( void )
{
BaseClass::Spawn();
//m_nSkin = m_nPowerupType;
SetModel( GetPowerupModelName() );
DispatchParticleEffect( GetIdleParticleName(), GetAbsOrigin(), vec3_angle, PATTACH_ABSORIGIN_FOLLOW, this );
//EmitSound("ASW_Powerup.Drop");
// This will make them not collide with the player, but will collide
// against other items + weapons
SetCollisionGroup( COLLISION_GROUP_DEBRIS );
CollisionProp()->UseTriggerBounds( true, ITEM_PICKUP_BOX_BLOAT_POWERUP );
// ignore touch
//SetTouch(&CASW_Powerup::ItemTouch);
SetMoveType( MOVETYPE_FLYGRAVITY, MOVECOLLIDE_FLY_BOUNCE );
// Tumble in air
QAngle vecAngVelocity( 0, random->RandomFloat( -100, 100 ), 0 );
SetLocalAngularVelocity( vecAngVelocity );
SetGravity( asw_powerup_gravity.GetFloat() );
SetFriction( asw_powerup_friction.GetFloat() );
SetElasticity( asw_powerup_elasticity.GetFloat() );
VisibilityMonitor_AddEntity( this, PICKUP_POWERUP_VISIBILITY_RANGE, NULL, NULL );
}
void CASW_Powerup::Precache( void )
{
BaseClass::Precache( );
PrecacheModel( GetPowerupModelName() );
//PrecacheScriptSound( "ASW_Powerup.Drop" );
//PrecacheScriptSound( GetPickupSoundName() );
PrecacheParticleSystem( GetIdleParticleName() );
PrecacheParticleSystem( GetPickupParticleName() );
}
void CASW_Powerup::SetIsSpawnFlipping( float flMaxPickupDelay )
{
m_flCanPickupMaxTime = gpGlobals->curtime + flMaxPickupDelay;
}
/*
void CASW_Powerup::ItemTouch( CBaseEntity *pOther )
{
return;
if ( (pOther->IsWorld() || m_flCanPickupMaxTime <= gpGlobals->curtime) && m_bSpawnDelayDenyPickup == true )
{
m_bSpawnDelayDenyPickup = false;
return;
}
if ( !pOther || pOther->Classify() != CLASS_ASW_MARINE )
return;
if ( m_bSpawnDelayDenyPickup == true && m_flCanPickupMaxTime > gpGlobals->curtime )
return;
CASW_Marine * RESTRICT pMarine = assert_cast<CASW_Marine*>( pOther );
// incapacitated or nonexistent marines cannot pick up crystals.
if ( !pMarine )
return;
PickupPowerup( pMarine );
DispatchParticleEffect( GetPickupParticleName(), GetAbsOrigin(), vec3_angle, PATTACH_ABSORIGIN_FOLLOW, this );
pMarine->CreatePowerupPickupIcon( this, iFXType, iAmount );
int iFXType = 0;
// send a message to c_asw_fx to show the particle effect
CRecipientFilter filter;
filter.AddAllPlayers();
UserMessageBegin( filter, "ASWPickupPowerBall" );
WRITE_SHORT( pOther->entindex() );
WRITE_SHORT( iFXType );
WRITE_FLOAT( WorldSpaceCenter().x );
WRITE_FLOAT( WorldSpaceCenter().y );
WRITE_FLOAT( WorldSpaceCenter().z );
MessageEnd();
// tell it to remove itself
SetCollisionGroup( COLLISION_GROUP_DEBRIS );
SetTouch( NULL );
SetMoveType( MOVETYPE_NONE );
//UTIL_Remove( this );
SetThink( &CASW_Powerup::SUB_Remove );
SetNextThink( gpGlobals->curtime + 0.1f );
}
*/
void CASW_Powerup::ActivateUseIcon( CASW_Marine* pMarine, int nHoldType )
{
if ( nHoldType == ASW_USE_HOLD_START )
return;
PickupPowerup( pMarine );
}
void CASW_Powerup::PickupPowerup( CASW_Marine *pMarine )
{
if ( !pMarine )
return;
//pMarine->EmitSound( GetPickupSoundName() );
pMarine->AddPowerup( m_nPowerupType, gpGlobals->curtime + m_flPowerupDuration );
DispatchParticleEffect( GetPickupParticleName(), GetAbsOrigin(), vec3_angle, PATTACH_ABSORIGIN_FOLLOW, this );
// tell it to remove itself
SetCollisionGroup( COLLISION_GROUP_DEBRIS );
SetTouch( NULL );
SetMoveType( MOVETYPE_NONE );
//UTIL_Remove( this );
SetThink( &CASW_Powerup::SUB_Remove );
SetNextThink( gpGlobals->curtime + 0.1f );
}
#endif
//-------------
// Bullet-based powerups
// these can only be picked up if the player is currently wielding a bullet-based weapon
//-------------
IMPLEMENT_NETWORKCLASS_ALIASED( ASW_Powerup_Bullets, DT_ASW_Powerup_Bullets );
BEGIN_NETWORK_TABLE( CASW_Powerup_Bullets, DT_ASW_Powerup_Bullets )
END_NETWORK_TABLE()
bool CASW_Powerup_Bullets::AllowedToPickup(CASW_Marine *pMarine)
{
if ( !pMarine )
return false;
if ( !ASWGameRules()->MarineCanPickupPowerup( pMarine, this ) )
return false;
return true;
/*
bool bInRange = ( GetAbsOrigin().DistTo( pMarine->GetAbsOrigin() ) < HEALTSTTATION_USE_AREA_RANGE );
return bInRange && !pMarine->IsIncap() && !pMarine->IsInfested();
*/
}
#ifndef CLIENT_DLL
void CASW_Powerup_Bullets::ActivateUseIcon( CASW_Marine* pMarine, int nHoldType )
{
if ( nHoldType == ASW_USE_HOLD_START )
return;
if ( ASWGameRules()->MarineCanPickupPowerup( pMarine, this ) )
PickupPowerup( pMarine );
}
#endif
//-------------
// Freeze Bullets
//-------------
IMPLEMENT_NETWORKCLASS_ALIASED( ASW_Powerup_Freeze_Bullets, DT_ASW_Powerup_Freeze_Bullets );
BEGIN_NETWORK_TABLE( CASW_Powerup_Freeze_Bullets, DT_ASW_Powerup_Freeze_Bullets )
END_NETWORK_TABLE()
LINK_ENTITY_TO_CLASS( asw_powerup_freeze_bullets, CASW_Powerup_Freeze_Bullets );
PRECACHE_REGISTER( asw_powerup_freeze_bullets );
CASW_Powerup_Freeze_Bullets::CASW_Powerup_Freeze_Bullets()
{
m_nPowerupType = POWERUP_TYPE_FREEZE_BULLETS;
#ifdef CLIENT_DLL
Q_snprintf(m_szUseIconText, sizeof(m_szUseIconText), "#asw_take_pow_freeze_bullets");
#endif
}
//-------------
// Fire Bullets
//-------------
IMPLEMENT_NETWORKCLASS_ALIASED( ASW_Powerup_Fire_Bullets, DT_ASW_Powerup_Fire_Bullets );
BEGIN_NETWORK_TABLE( CASW_Powerup_Fire_Bullets, DT_ASW_Powerup_Fire_Bullets )
END_NETWORK_TABLE()
LINK_ENTITY_TO_CLASS( asw_powerup_fire_bullets, CASW_Powerup_Fire_Bullets );
PRECACHE_REGISTER( asw_powerup_fire_bullets );
CASW_Powerup_Fire_Bullets::CASW_Powerup_Fire_Bullets()
{
m_nPowerupType = POWERUP_TYPE_FIRE_BULLETS;
#ifdef CLIENT_DLL
Q_snprintf(m_szUseIconText, sizeof(m_szUseIconText), "#asw_take_pow_fire_bullets");
#endif
}
//-------------
// Electric Bullets
//-------------
IMPLEMENT_NETWORKCLASS_ALIASED( ASW_Powerup_Electric_Bullets, DT_ASW_Powerup_Electric_Bullets );
BEGIN_NETWORK_TABLE( CASW_Powerup_Electric_Bullets, DT_ASW_Powerup_Electric_Bullets )
END_NETWORK_TABLE()
LINK_ENTITY_TO_CLASS( asw_powerup_electric_bullets, CASW_Powerup_Electric_Bullets );
PRECACHE_REGISTER( asw_powerup_electric_bullets );
CASW_Powerup_Electric_Bullets::CASW_Powerup_Electric_Bullets()
{
m_nPowerupType = POWERUP_TYPE_ELECTRIC_BULLETS;
#ifdef CLIENT_DLL
Q_snprintf(m_szUseIconText, sizeof(m_szUseIconText), "#asw_take_pow_elec_bullets");
#endif
}
//-------------
// Chem Bullets
//-------------
IMPLEMENT_NETWORKCLASS_ALIASED( ASW_Powerup_Chemical_Bullets, DT_ASW_Powerup_Chemical_Bullets );
BEGIN_NETWORK_TABLE( CASW_Powerup_Chemical_Bullets, DT_ASW_Powerup_Chemical_Bullets )
END_NETWORK_TABLE()
LINK_ENTITY_TO_CLASS( asw_powerup_chemical_bullets, CASW_Powerup_Chemical_Bullets );
PRECACHE_REGISTER( asw_powerup_chemical_bullets );
CASW_Powerup_Chemical_Bullets::CASW_Powerup_Chemical_Bullets()
{
//m_nPowerupType = POWERUP_TYPE_CHEMICAL_BULLETS;
#ifdef CLIENT_DLL
Q_snprintf(m_szUseIconText, sizeof(m_szUseIconText), "#asw_take_pow_chem_bullets");
#endif
}
//-------------
// EXPLODEY Bullets
//-------------
IMPLEMENT_NETWORKCLASS_ALIASED( ASW_Powerup_Explosive_Bullets, DT_ASW_Powerup_Explosive_Bullets );
BEGIN_NETWORK_TABLE( CASW_Powerup_Explosive_Bullets, DT_ASW_Powerup_Explosive_Bullets )
END_NETWORK_TABLE()
LINK_ENTITY_TO_CLASS( asw_powerup_explosive_bullets, CASW_Powerup_Explosive_Bullets );
PRECACHE_REGISTER( asw_powerup_explosive_bullets );
CASW_Powerup_Explosive_Bullets::CASW_Powerup_Explosive_Bullets()
{
//m_nPowerupType = POWERUP_TYPE_EXPLOSIVE_BULLETS;
#ifdef CLIENT_DLL
Q_snprintf(m_szUseIconText, sizeof(m_szUseIconText), "#asw_take_pow_explo_bullets");
#endif
}
//-------------
// Increased Speed
//-------------
IMPLEMENT_NETWORKCLASS_ALIASED( ASW_Powerup_Increased_Speed, DT_ASW_Powerup_Increased_Speed );
BEGIN_NETWORK_TABLE( CASW_Powerup_Increased_Speed, DT_ASW_Powerup_Increased_Speed )
END_NETWORK_TABLE()
LINK_ENTITY_TO_CLASS( asw_powerup_increased_speed, CASW_Powerup_Increased_Speed );
PRECACHE_REGISTER( asw_powerup_increased_speed );
CASW_Powerup_Increased_Speed::CASW_Powerup_Increased_Speed()
{
m_nPowerupType = POWERUP_TYPE_INCREASED_SPEED;
m_flPowerupDuration = 15.0f;
#ifdef CLIENT_DLL
Q_snprintf(m_szUseIconText, sizeof(m_szUseIconText), "#asw_take_pow_inc_speed");
#endif
}
| 29.757746
| 112
| 0.763347
|
BlueNovember
|
4c6f6c5c2f73f1d53c36d6c673754ac72a8a7bca
| 600
|
cpp
|
C++
|
Class-05/Problem-23.cpp
|
Emrul-Hasan-Emon/Intermediate-Session-2021
|
188b82eb3f063a203186ebfb6b01acaa3ab12b02
|
[
"MIT"
] | 2
|
2021-12-06T17:57:11.000Z
|
2022-01-15T14:34:00.000Z
|
Class-05/Problem-23.cpp
|
Emrul-Hasan-Emon/Intermediate-Session-2021
|
188b82eb3f063a203186ebfb6b01acaa3ab12b02
|
[
"MIT"
] | null | null | null |
Class-05/Problem-23.cpp
|
Emrul-Hasan-Emon/Intermediate-Session-2021
|
188b82eb3f063a203186ebfb6b01acaa3ab12b02
|
[
"MIT"
] | null | null | null |
You are given a number consists of n digits. Find whether the number is multiple of 3 or not.
As this is a very big number this will not if into even in long long range. So, this number has to be taken also in string. And if summation of every digit in
string is divisible by 3 then whole number is divisible by 3.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
string s;
cin>>s;
n=0;
for(int i=0; i<s.size(); i++)
{
n=n+(s[i]-'0');
}
if(n%3==0)
cout<<"Divisible by 3"<<endl;
else
cout<<"Not Divisible by 3"<<endl;
}
| 25
| 158
| 0.621667
|
Emrul-Hasan-Emon
|
4c6ff00d5a94d6f49e5bbc083b5cf378be340821
| 486
|
cpp
|
C++
|
Naive_Chef.cpp
|
amit9amarwanshi/The_Quiet_Revolution
|
7713787ef27c0c144e4c2d852d826ee1c4176a95
|
[
"MIT"
] | null | null | null |
Naive_Chef.cpp
|
amit9amarwanshi/The_Quiet_Revolution
|
7713787ef27c0c144e4c2d852d826ee1c4176a95
|
[
"MIT"
] | null | null | null |
Naive_Chef.cpp
|
amit9amarwanshi/The_Quiet_Revolution
|
7713787ef27c0c144e4c2d852d826ee1c4176a95
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
#define ASCII_SIZE 256
#define ll long long int
int main(){
ll t,n,n1,a,b,c,j,temp,l,s=0;
cin>>t;
while(t--){
cin>>n>>a>>b;
ll ca=0;
ll cb=0;
for(ll i=0;i<n;i++){
cin>>temp;
if(temp==a) ca++;
if(temp==b) cb++;
}
double k1=(double) ca/n;
double k2=(double) cb/n;
double k=k1*k2;
printf("%.10f\n",k);
}
return 0;
}
| 20.25
| 33
| 0.450617
|
amit9amarwanshi
|
dbcce8568ab929eb8e5f32963eb396a1ad26b60a
| 3,713
|
cc
|
C++
|
omaha/tools/MsiTagger/msi_tag_tool.cc
|
theroguekiller1/tablet-a
|
5f5207f1cb936f380368f623f2128749a289c777
|
[
"Apache-2.0"
] | 2
|
2019-09-06T20:53:41.000Z
|
2021-03-09T08:41:24.000Z
|
omaha/tools/MsiTagger/msi_tag_tool.cc
|
theroguekiller1/tablet-a
|
5f5207f1cb936f380368f623f2128749a289c777
|
[
"Apache-2.0"
] | 1
|
2018-12-19T12:23:39.000Z
|
2018-12-19T12:23:39.000Z
|
omaha/tools/MsiTagger/msi_tag_tool.cc
|
theroguekiller1/tablet-a
|
5f5207f1cb936f380368f623f2128749a289c777
|
[
"Apache-2.0"
] | 1
|
2019-09-06T20:54:10.000Z
|
2019-09-06T20:54:10.000Z
|
// Copyright 2013 Google 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.
// ========================================================================
//
// This is a naive tool to write tags to MSI packages. It just blindly adds
// tags without checking:
// 1. Whether the input file is a valid MSI package.
// 2. Whether the file is tagged already.
// Tag format:
//
// +-------------------------------------+
// ~ .............................. ~
// | .............................. |
// | End of MSI file | End of raw MSI.
// +-------------------------------------+
// | Magic number 'Gact' | Tag starts
// | Tag string length |
// | tag string |
// +-------------------------------------+
#include <fstream> // NOLINT(readability/streams)
#include <limits>
#include "omaha/base/file.h"
#include "omaha/base/path.h"
#include "omaha/base/utils.h"
using omaha::CreateDir;
using omaha::ConcatenatePath;
using omaha::File;
using omaha::GetCurrentDir;
using omaha::GetDirectoryFromPath;
using omaha::GetFileFromPath;
// Output a uint16 to the file. Always in big endian.
void write_uint16(std::ofstream* file, uint16 value) {
char c = static_cast<char>((value & 0xFF00) >> 8);
file->write(&c, 1);
c = static_cast<char>(value & 0x00FF);
file->write(&c, 1);
}
int WriteMsiTag(
const TCHAR* in_file,
const TCHAR* out_file,
const TCHAR* tag) {
int tag_length = lstrlen(tag);
if (tag_length > std::numeric_limits<uint16>::max()) {
return -1;
}
std::ifstream in;
std::ofstream out;
in.open(in_file, std::ifstream::in | std::ifstream::binary);
out.open(out_file, std::ofstream::out | std::ofstream::binary);
if (!in.is_open() || !out.is_open()) {
return -1;
}
// Copy MSI package first.
out << in.rdbuf();
// Then append the tags to the end of file.
const char kMagicNumber[] = "Gact";
out.write(kMagicNumber, arraysize(kMagicNumber) - 1);
// Write tag length.
write_uint16(&out, static_cast<uint16>(tag_length));
// Actual tag.
std::string tag_ansi(tag, tag + tag_length);
out.write(tag_ansi.data(), tag_length);
in.close();
out.close();
return S_OK;
}
int _tmain(int argc, _TCHAR* argv[]) {
if (argc != 4) {
_tprintf(_T("Incorrect number of arguments!\n"));
_tprintf(_T("Usage: MsiTagger <source_msi> <outputfile> <tag>\n"));
_tprintf(_T("Example: MsiTagger Setup.msi TaggedSetup.msi BRAND=GGLS\n"));
return -1;
}
const TCHAR* file = argv[1];
if (!File::Exists(file)) {
_tprintf(_T("File \"%s\" not found!\n"), file);
return -1;
}
CString dir = GetDirectoryFromPath(argv[2]);
CString path = ConcatenatePath(GetCurrentDir(), dir);
ASSERT1(!path.IsEmpty());
if (!File::Exists(path)) {
HRESULT hr = CreateDir(path, NULL);
if (FAILED(hr)) {
_tprintf(_T("Could not create dir %s\n"),
static_cast<const TCHAR*>(path));
return hr;
}
}
ASSERT1(File::Exists(path));
CString file_name = GetFileFromPath(argv[2]);
CString out_path = ConcatenatePath(path, file_name);
ASSERT1(!out_path.IsEmpty());
return WriteMsiTag(file, out_path, argv[3]);
}
| 29.704
| 78
| 0.605171
|
theroguekiller1
|
dbd2cb2bc93c582dd30ffabab0512915516d58db
| 1,473
|
cpp
|
C++
|
srcs/Application.cpp
|
Globicodeur/N-Puzzle
|
2b6e23d509a40d1089b5212e04fb86e237519228
|
[
"MIT"
] | null | null | null |
srcs/Application.cpp
|
Globicodeur/N-Puzzle
|
2b6e23d509a40d1089b5212e04fb86e237519228
|
[
"MIT"
] | null | null | null |
srcs/Application.cpp
|
Globicodeur/N-Puzzle
|
2b6e23d509a40d1089b5212e04fb86e237519228
|
[
"MIT"
] | null | null | null |
#include "Application.hpp"
#include "options/Options.hpp"
#include "parsing/Parser.hpp"
#include "runtime/Solver.hpp"
Application::Application(int argc, char **argv) {
Options::parseFromCommandLine(argc, argv);
}
void Application::run(void) {
using MaybeState = std::optional<parsing::ParsedPuzzle>;
parsing::Parser parser;
MaybeState initial, goal;
if (!Options::initialFile.empty())
initial = parser.parse(Options::initialFile);
if (!Options::goalFile.empty())
goal = parser.parse(Options::goalFile);
#ifdef DEBUG
// STATIC composition (for debugging purposes and because fuck compilers)
constexpr bool uniform = true;
constexpr bool ida = false;
using StaticHeuristics = algorithm::heuristics::Composition<
algorithm::heuristics::ManhattanDistance
, algorithm::heuristics::LinearConflict
// , algorithm::heuristics::MisplacedTiles
// , algorithm::heuristics::MisplacedRowsAndColumns
>;
using StaticSolver = algorithm::Solver<
StaticHeuristics::template Composer,
uniform,
ida
>;
StaticSolver debugSolver { initial, goal };
debugSolver.solve([](const auto & solution) {
std::cout << solution << std::endl;
});
#else
// RUNTIME composition
runtime::Solver solver { initial, goal };
solver.solve(); // This line is the nightmare of every compiler
#endif
std::cout << "\n==============" << std::endl;
}
| 28.882353
| 77
| 0.662593
|
Globicodeur
|
dbd82a8c06408d7fe3288e805f3ad6c3ccde1eeb
| 883
|
cpp
|
C++
|
solutions/21-E-Merge-Two-Sorted-Lists/main.cpp
|
ARW2705/leet-code-solutions
|
fa551e5b15f5340e5be3b832db39638bcbf0dc78
|
[
"MIT"
] | null | null | null |
solutions/21-E-Merge-Two-Sorted-Lists/main.cpp
|
ARW2705/leet-code-solutions
|
fa551e5b15f5340e5be3b832db39638bcbf0dc78
|
[
"MIT"
] | null | null | null |
solutions/21-E-Merge-Two-Sorted-Lists/main.cpp
|
ARW2705/leet-code-solutions
|
fa551e5b15f5340e5be3b832db39638bcbf0dc78
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "../../utilities/singly-linked-node.hpp"
#include "../../utilities/print-linked-list.cpp"
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 != nullptr && l2 != nullptr) {
if (l1->val > l2->val) {
std::swap(l1, l2);
}
l1->next = mergeTwoLists(l1->next, l2);
} else if (l1 == nullptr) {
return l2;
}
return l1;
}
int main() {
ListNode* l4a = new ListNode(4);
ListNode* l2a = new ListNode(2, l4a);
ListNode* l1a = new ListNode(1, l2a);
ListNode* l4b = new ListNode(4);
ListNode* l3b = new ListNode(3, l4b);
ListNode* l1b = new ListNode(1, l3b);
ListNode* r1 = mergeTwoLists(l1a, l1b);
printLinkedList(r1);
ListNode* r2 = mergeTwoLists(nullptr, nullptr);
printLinkedList(r2);
ListNode* l0 = new ListNode(0);
ListNode* r3 = mergeTwoLists(nullptr, l0);
printLinkedList(r3);
return 0;
}
| 24.527778
| 53
| 0.635334
|
ARW2705
|
dbd9433a7a45e3dba49338d7076dd9e791352da5
| 884
|
cpp
|
C++
|
HackerRankEulerProblems/60/P047_DistinctPrimesFactors.cpp
|
wingkinl/HackerRankEulerProblems
|
3b5cf8945dc1d4f0a2214103f2e0414caf07a18a
|
[
"Apache-2.0"
] | null | null | null |
HackerRankEulerProblems/60/P047_DistinctPrimesFactors.cpp
|
wingkinl/HackerRankEulerProblems
|
3b5cf8945dc1d4f0a2214103f2e0414caf07a18a
|
[
"Apache-2.0"
] | null | null | null |
HackerRankEulerProblems/60/P047_DistinctPrimesFactors.cpp
|
wingkinl/HackerRankEulerProblems
|
3b5cf8945dc1d4f0a2214103f2e0414caf07a18a
|
[
"Apache-2.0"
] | null | null | null |
#include "P047_DistinctPrimesFactors.h"
#include <iostream>
#include "libs/prime.h"
std::vector<unsigned int> P047_DistinctPrimesFactors::Solve(unsigned int n, unsigned int k)
{
unsigned int max = n + k - 1;
std::vector<unsigned int> primes(max + 1, 0);
for (unsigned int ii = 2; ii <= max; ++ii)
{
if (primes[ii] == 0)
{
for (unsigned int jj = ii; jj <= max; jj += ii)
++primes[jj];
}
}
std::vector<unsigned int> results;
for (unsigned int ii = 2, continuos_match = 0; ii <= max; ++ii)
{
if (primes[ii] == k)
{
++continuos_match;
if (continuos_match >= k)
results.push_back(ii - k + 1);
}
else
{
continuos_match = 0;
}
}
return results;
}
void P047_DistinctPrimesFactors::main()
{
std::ios_base::sync_with_stdio(false);
unsigned int n = 20, k = 2;
std::cin >> n >> k;
for (auto res : Solve(n, k))
std::cout << res << "\n";
}
| 20.090909
| 91
| 0.61086
|
wingkinl
|
dbe2836c9846d23e0906f29af661dd4708b124e2
| 6,179
|
cpp
|
C++
|
speedcc/platform/android/speedcc/src/main/cpp/SCAndroidAppEnv.cpp
|
kevinwu1024/SpeedCC
|
7b32e3444236d8aebf8198ebc3fede8faf201dee
|
[
"MIT"
] | 7
|
2018-03-10T02:01:49.000Z
|
2021-09-14T15:42:10.000Z
|
speedcc/platform/android/speedcc/src/main/cpp/SCAndroidAppEnv.cpp
|
kevinwu1024/SpeedCC
|
7b32e3444236d8aebf8198ebc3fede8faf201dee
|
[
"MIT"
] | null | null | null |
speedcc/platform/android/speedcc/src/main/cpp/SCAndroidAppEnv.cpp
|
kevinwu1024/SpeedCC
|
7b32e3444236d8aebf8198ebc3fede8faf201dee
|
[
"MIT"
] | 1
|
2018-03-10T02:01:58.000Z
|
2018-03-10T02:01:58.000Z
|
/****************************************************************************
Copyright (c) 2017-2020 Kevin Wu (Wu Feng)
github: http://github.com/kevinwu1024
Licensed under the MIT License (the "License"); you may not use this file except
in compliance with the License. You may obtain a copy of the License at
http://opensource.org/licenses/MIT
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 NON INFRINGEMENT. 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 <stdlib.h>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "../../../../../../../cocos2d-x/v3/cocos/platform/android/jni/JniHelper.h"
#include <android/log.h>
#define CLASS_NAME "org/speedcc/lib/JNISystem"
using namespace cocos2d;
#ifdef __cplusplus
extern "C"
{
#endif // __cplusplus
// 0: unknown; 1: portrait; 2: portrait upside down;
// 3: landscape right; 4: landscape left
int scGetDeviceOrientation()
{
int nRet = 0;
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME,
"getOrientation", "()I"))
{
nRet = t.env->CallStaticIntMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
return nRet;
}
int scGetBundleID(char* pszBuffer, const int nBufferSize)
{
int nRet = 0;
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME,
"getPackageName", "()Ljava/lang/String;"))
{
jstring s = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID);
std::string strResult = JniHelper::jstring2string(s);
t.env->DeleteLocalRef(s);
t.env->DeleteLocalRef(t.classID);
const int len = (int)strResult.size();
if(pszBuffer!=NULL && nBufferSize>len+2)
{
strcpy(pszBuffer,strResult.c_str());
nRet = len;
}
else
{
nRet = len+2;
}
}
return nRet;
}
int scGetProductName(char* pszBuffer,const int nBufferSize)
{
int nRet = 0;
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME,
"getProductName", "()Ljava/lang/String;"))
{
jstring s = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID);
std::string strResult = JniHelper::jstring2string(s);
t.env->DeleteLocalRef(s);
t.env->DeleteLocalRef(t.classID);
const int len = (int)strResult.size();
if(pszBuffer!=NULL && nBufferSize>len+2)
{
strcpy(pszBuffer,strResult.c_str());
nRet = len;
}
else
{
nRet = len+2;
}
}
return nRet;
}
bool scGetAppVersion(int* pMajor,int* pMinor,int* pFix)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME,
"getAppVersion", "()Ljava/lang/String;"))
{
jstring s = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID);
std::string strResult = JniHelper::jstring2string(s);
t.env->DeleteLocalRef(s);
t.env->DeleteLocalRef(t.classID);
std::vector<std::string> strNumberVer;
std::stringstream ss(strResult);
std::string item;
while (std::getline(ss, item, '.'))
{
strNumberVer.push_back(item);
}
int i = 0;
for (const auto& it : strNumberVer)
{
switch (i++)
{
case 0:
if (pMajor)
*pMajor = atoi(it.c_str());
break;
case 1:
if (pMinor)
*pMinor = atoi(it.c_str());
break;
case 2:
if (pFix)
*pFix = atoi(it.c_str());
break;
default:
break;
}
}
return true;
}
return false;
}
int scGetMonthName(char* pszBuf,const int nBufSize,const int nMonth,const bool bShort)
{
int nRet = 0;
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME,
"getMonthName", "(IZ)Ljava/lang/String;"))
{
jstring s = (jstring) t.env->CallStaticObjectMethod(t.classID,t.methodID,(jint)nMonth,(jboolean)bShort);
std::string strMonName = JniHelper::jstring2string(s);
t.env->DeleteLocalRef(s);
t.env->DeleteLocalRef(t.classID);
if(pszBuf && nBufSize>strMonName.size())
{
nRet = (int)strMonName.size();
strcpy(pszBuf,strMonName.c_str());
}
else if(pszBuf==NULL)
{
nRet = (int)strMonName.size() + 2;
}
}
return nRet;
}
int scGetWeekName(char* pszBuf,const int nBufSize,const int nMonth,const bool bShort)
{
int nRet = 0;
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME,
"getWeekName", "(IZ)Ljava/lang/String;"))
{
jstring s = (jstring) t.env->CallStaticObjectMethod(t.classID,t.methodID,(jint)nMonth,(jboolean)bShort);
std::string strWeekName = JniHelper::jstring2string(s);
t.env->DeleteLocalRef(s);
t.env->DeleteLocalRef(t.classID);
if(pszBuf && nBufSize>strWeekName.size())
{
nRet = (int)strWeekName.size();
strcpy(pszBuf,strWeekName.c_str());
}
else if(pszBuf==NULL)
{
nRet = (int)strWeekName.size() + 2;
}
}
return nRet;
}
#ifdef __cplusplus
}
#endif // __cplusplus
| 27.833333
| 112
| 0.547014
|
kevinwu1024
|
dbe74f299aac0e18e2064c5cb03b708f6580c10d
| 694
|
ipp
|
C++
|
asteria/src/details/utils.ipp
|
LiXiaYu/asteria
|
1f715f910decb55817ce5f6a310675f9724f1b7d
|
[
"BSD-3-Clause"
] | null | null | null |
asteria/src/details/utils.ipp
|
LiXiaYu/asteria
|
1f715f910decb55817ce5f6a310675f9724f1b7d
|
[
"BSD-3-Clause"
] | null | null | null |
asteria/src/details/utils.ipp
|
LiXiaYu/asteria
|
1f715f910decb55817ce5f6a310675f9724f1b7d
|
[
"BSD-3-Clause"
] | null | null | null |
// This file is part of Asteria.
// Copyleft 2018 - 2022, LH_Mouse. All wrongs reserved.
#ifndef ASTERIA_UTILS_HPP_
# error Please include <asteria/utils.hpp> instead.
#endif
namespace asteria {
namespace details_utils {
extern const uint8_t cctype_table[128];
struct Quote_Wrapper
{
const char* str;
size_t len;
};
tinyfmt&
operator<<(tinyfmt& fmt, const Quote_Wrapper& q);
struct Paragraph_Wrapper
{
size_t indent;
size_t hanging;
};
tinyfmt&
operator<<(tinyfmt& fmt, const Paragraph_Wrapper& q);
struct Formatted_errno
{
int err;
};
tinyfmt&
operator<<(tinyfmt& fmt, const Formatted_errno& e);
} // namespace details_utils
} // namespace asteria
| 16.926829
| 55
| 0.713256
|
LiXiaYu
|
dbeaf4de6922cdb4e57871e662dfc706634870ed
| 2,373
|
cpp
|
C++
|
src/lib/tools/followredirectreply.cpp
|
pejakm/qupzilla
|
c1901cd81d9d3488a7dc1f25b777fb56f67cb39e
|
[
"BSD-3-Clause"
] | 1
|
2015-11-02T17:31:21.000Z
|
2015-11-02T17:31:21.000Z
|
src/lib/tools/followredirectreply.cpp
|
pejakm/qupzilla
|
c1901cd81d9d3488a7dc1f25b777fb56f67cb39e
|
[
"BSD-3-Clause"
] | null | null | null |
src/lib/tools/followredirectreply.cpp
|
pejakm/qupzilla
|
c1901cd81d9d3488a7dc1f25b777fb56f67cb39e
|
[
"BSD-3-Clause"
] | null | null | null |
/* ============================================================
* QupZilla - WebKit based browser
* Copyright (C) 2010-2014 David Rosca <nowrep@gmail.com>
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
* ============================================================ */
#include "followredirectreply.h"
#include <QNetworkAccessManager>
FollowRedirectReply::FollowRedirectReply(const QUrl &url, QNetworkAccessManager* manager)
: QObject()
, m_manager(manager)
, m_redirectCount(0)
{
m_reply = m_manager->get(QNetworkRequest(url));
connect(m_reply, SIGNAL(finished()), this, SLOT(replyFinished()));
}
QNetworkReply* FollowRedirectReply::reply() const
{
return m_reply;
}
QUrl FollowRedirectReply::originalUrl() const
{
return m_reply->request().url();
}
QUrl FollowRedirectReply::url() const
{
return m_reply->url();
}
QNetworkReply::NetworkError FollowRedirectReply::error() const
{
return m_reply->error();
}
QString FollowRedirectReply::errorString() const
{
return m_reply->errorString();
}
QByteArray FollowRedirectReply::readAll()
{
return m_reply->readAll();
}
void FollowRedirectReply::replyFinished()
{
int replyStatus = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if ((replyStatus != 301 && replyStatus != 302) || m_redirectCount == 5) {
emit finished();
return;
}
m_redirectCount++;
QUrl redirectUrl = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
m_reply->close();
m_reply->deleteLater();
m_reply = m_manager->get(QNetworkRequest(redirectUrl));
connect(m_reply, SIGNAL(finished()), this, SLOT(replyFinished()));
}
FollowRedirectReply::~FollowRedirectReply()
{
m_reply->close();
m_reply->deleteLater();
}
| 27.917647
| 95
| 0.68563
|
pejakm
|
dbee9c0986427d0283ed532b8da80bd922d82a72
| 3,356
|
cpp
|
C++
|
Modules/TArc/Sources/TArc/Controls/Private/LineEdit.cpp
|
Serviak/dava.engine
|
d51a26173a3e1b36403f846ca3b2e183ac298a1a
|
[
"BSD-3-Clause"
] | 1
|
2020-11-14T10:18:24.000Z
|
2020-11-14T10:18:24.000Z
|
Modules/TArc/Sources/TArc/Controls/Private/LineEdit.cpp
|
Serviak/dava.engine
|
d51a26173a3e1b36403f846ca3b2e183ac298a1a
|
[
"BSD-3-Clause"
] | null | null | null |
Modules/TArc/Sources/TArc/Controls/Private/LineEdit.cpp
|
Serviak/dava.engine
|
d51a26173a3e1b36403f846ca3b2e183ac298a1a
|
[
"BSD-3-Clause"
] | 1
|
2020-09-05T21:16:17.000Z
|
2020-09-05T21:16:17.000Z
|
#include "TArc/Controls/LineEdit.h"
#include "TArc/Controls/Private/TextValidator.h"
#include <Base/FastName.h>
#include <Reflection/ReflectedMeta.h>
namespace DAVA
{
namespace TArc
{
LineEdit::LineEdit(const Params& params, DataWrappersProcessor* wrappersProcessor, Reflection model, QWidget* parent)
: ControlProxyImpl<QLineEdit>(params, ControlDescriptor(params.fields), wrappersProcessor, model, parent)
{
SetupControl();
}
LineEdit::LineEdit(const Params& params, ContextAccessor* accessor, Reflection model, QWidget* parent)
: ControlProxyImpl<QLineEdit>(params, ControlDescriptor(params.fields), accessor, model, parent)
{
SetupControl();
}
void LineEdit::SetupControl()
{
connections.AddConnection(this, &QLineEdit::editingFinished, MakeFunction(this, &LineEdit::EditingFinished));
TextValidator* validator = new TextValidator(this, this);
setValidator(validator);
}
void LineEdit::EditingFinished()
{
RETURN_IF_MODEL_LOST(void());
if (!isReadOnly())
{
String newText = text().toStdString();
if (GetFieldValue<String>(Fields::Text, "") != newText)
{
wrapper.SetFieldValue(GetFieldName(Fields::Text), newText);
}
}
}
void LineEdit::UpdateControl(const ControlDescriptor& descriptor)
{
RETURN_IF_MODEL_LOST(void());
bool readOnlyChanged = descriptor.IsChanged(Fields::IsReadOnly);
bool textChanged = descriptor.IsChanged(Fields::Text);
if (readOnlyChanged || textChanged)
{
DAVA::Reflection fieldValue = model.GetField(descriptor.GetName(Fields::Text));
DVASSERT(fieldValue.IsValid());
setReadOnly(IsValueReadOnly(descriptor, Fields::Text, Fields::IsReadOnly));
if (textChanged)
{
QString newText = QString::fromStdString(fieldValue.GetValue().Cast<String>());
if (newText != text())
{
setText(newText);
}
}
}
if (descriptor.IsChanged(Fields::IsEnabled))
{
setEnabled(GetFieldValue<bool>(Fields::IsEnabled, true));
}
if (descriptor.IsChanged(Fields::PlaceHolder))
{
setPlaceholderText(QString::fromStdString(GetFieldValue<String>(Fields::PlaceHolder, "")));
}
}
M::ValidationResult LineEdit::Validate(const Any& value) const
{
RETURN_IF_MODEL_LOST(M::ValidationResult());
Reflection field = model.GetField(GetFieldName(Fields::Text));
DVASSERT(field.IsValid());
M::ValidationResult r;
r.state = M::ValidationResult::eState::Valid;
const M::Validator* validator = GetFieldValue<const M::Validator*>(Fields::Validator, nullptr);
if (validator != nullptr)
{
r = validator->Validate(value, field.GetValue());
}
if (r.state == Metas::ValidationResult::eState::Invalid)
{
return r;
}
validator = field.GetMeta<M::Validator>();
if (validator != nullptr)
{
r = validator->Validate(value, field.GetValue());
}
return r;
}
void LineEdit::ShowHint(const QString& message)
{
NotificationParams notifParams;
notifParams.title = "Invalid value";
notifParams.message.message = message.toStdString();
notifParams.message.type = ::DAVA::Result::RESULT_ERROR;
controlParams.ui->ShowNotification(controlParams.wndKey, notifParams);
}
} // namespace TArc
} // namespace DAVA
| 28.683761
| 117
| 0.679976
|
Serviak
|
dbf4b95d04ae70e13a8f51f20bb2923f8b84e572
| 4,053
|
cpp
|
C++
|
src/app/medInria/medExportVideoDialog.cpp
|
aarrieul/medInria-public
|
0cd113a6b41e40497f1472630e9afa8e688ba85a
|
[
"BSD-4-Clause",
"BSD-1-Clause"
] | 61
|
2015-04-14T13:00:50.000Z
|
2022-03-09T22:22:18.000Z
|
src/app/medInria/medExportVideoDialog.cpp
|
aarrieul/medInria-public
|
0cd113a6b41e40497f1472630e9afa8e688ba85a
|
[
"BSD-4-Clause",
"BSD-1-Clause"
] | 510
|
2016-02-03T13:28:18.000Z
|
2022-03-23T10:23:44.000Z
|
src/app/medInria/medExportVideoDialog.cpp
|
mathildemerle/medInria-public
|
e8c517ef6263c1d98a62b79ca7aad30a21b61094
|
[
"BSD-4-Clause",
"BSD-1-Clause"
] | 36
|
2015-03-03T22:58:19.000Z
|
2021-12-28T18:19:23.000Z
|
/*=========================================================================
medInria
Copyright (c) INRIA 2013. All rights reserved.
See LICENSE.txt for details in the root of the sources or:
https://github.com/medInria/medInria-public/blob/master/LICENSE.txt
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
=========================================================================*/
#include "medExportVideoDialog.h"
#include <medComboBox.h>
#include <medIntParameterL.h>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QSpinBox>
#include <QVBoxLayout>
class medExportVideoDialogPrivate
{
public:
medComboBox *typeCombobox;
medIntParameterL *nbStep;
int numberOfFrames;
int numberOfSlices;
};
medExportVideoDialog::medExportVideoDialog(QWidget *parent, int numberOfFrames, int numberOfSlices): QDialog(parent,
Qt::Dialog | Qt::WindowCloseButtonHint), d (new medExportVideoDialogPrivate)
{
QVBoxLayout *dialogLayout = new QVBoxLayout;
// Warning
QLabel *warningLabel = new QLabel(tr("Warning: do not hide your view during the process!\n"
"This tool uses screenshots of the view to record your video.\n"));
warningLabel->setStyleSheet("font-weight: bold; color: red");
dialogLayout->addWidget(warningLabel);
// Type layout
QHBoxLayout *typeLayout = new QHBoxLayout;
QLabel *explanationLabel = new QLabel(tr("Please choose a video recording type"));
typeLayout->addWidget(explanationLabel);
d->typeCombobox = new medComboBox;
d->typeCombobox->addItem("Time", ExportVideoName::TIME);
d->typeCombobox->addItem("Rotation", ExportVideoName::ROTATION);
d->typeCombobox->addItem("Slice", ExportVideoName::SLICE);
typeLayout->addWidget(d->typeCombobox);
QObject::connect (d->typeCombobox, SIGNAL(activated(int)), this, SLOT(adaptWidgetForMethod(int)));
dialogLayout->addLayout(typeLayout);
// Step parameter
QHBoxLayout *stepLayout = new QHBoxLayout;
d->nbStep = new medIntParameterL("Recording step", this);
d->nbStep->setValue(1);
d->numberOfFrames = numberOfFrames;
d->nbStep->setRange(1, numberOfFrames);
d->nbStep->getSlider()->setOrientation(Qt::Horizontal);
stepLayout->addWidget(d->nbStep->getLabel());
stepLayout->addWidget(d->nbStep->getSlider());
stepLayout->addWidget(d->nbStep->getSpinBox());
d->numberOfSlices = numberOfSlices;
dialogLayout->addLayout(stepLayout);
// OK/Cancel buttons
QHBoxLayout *buttonLayout = new QHBoxLayout;
QPushButton *okButton = new QPushButton(tr("OK"));
QPushButton *cancelButton = new QPushButton(tr("Cancel"));
buttonLayout->addWidget(okButton);
buttonLayout->addWidget(cancelButton);
dialogLayout->addLayout(buttonLayout);
connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancel()));
connect(okButton, SIGNAL(clicked()), this, SLOT(validate()));
setLayout(dialogLayout);
setModal(true);
}
medExportVideoDialog::~medExportVideoDialog()
{
delete d;
}
void medExportVideoDialog::cancel()
{
this->reject();
}
void medExportVideoDialog::validate()
{
this->accept();
}
QVector<int> medExportVideoDialog::value()
{
QVector<int> resultsVector;
resultsVector.append(d->typeCombobox->currentIndex());
resultsVector.append(d->nbStep->value());
return resultsVector;
}
void medExportVideoDialog::adaptWidgetForMethod(int method)
{
switch (method)
{
case ExportVideoName::TIME:
{
d->nbStep->setRange(1, d->numberOfFrames);
break;
}
case ExportVideoName::ROTATION:
{
d->nbStep->setRange(1, 360);
break;
}
case ExportVideoName::SLICE:
{
d->nbStep->setRange(1, d->numberOfSlices);
break;
}
default:
{
break;
}
}
}
| 28.744681
| 116
| 0.65211
|
aarrieul
|
dbfc683c3c8e0e9ba9a20450964146aaf5fb9807
| 215
|
cpp
|
C++
|
Youtube/Staticcpp.cpp
|
lance-lh/learning-c-plusplus
|
90342cc5d26a5adb87aa3e97795d4bbfca7bef52
|
[
"MIT"
] | 1
|
2019-03-27T13:00:02.000Z
|
2019-03-27T13:00:02.000Z
|
Youtube/Staticcpp.cpp
|
lance-lh/learning-c-plusplus
|
90342cc5d26a5adb87aa3e97795d4bbfca7bef52
|
[
"MIT"
] | null | null | null |
Youtube/Staticcpp.cpp
|
lance-lh/learning-c-plusplus
|
90342cc5d26a5adb87aa3e97795d4bbfca7bef52
|
[
"MIT"
] | 1
|
2021-01-12T22:01:28.000Z
|
2021-01-12T22:01:28.000Z
|
//static int s_Variable = 5; // this variable is only linked internally inside this translation unit. if no keyword "static", the variable will have a global scope.
int s_Variable = 5;
static void Function()
{
}
| 23.888889
| 164
| 0.739535
|
lance-lh
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.