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
4d8426a505d338378dd931b5294a6a1abd2ff169
2,754
cpp
C++
RCVersionTests/HelperTests.cpp
mekmak/RCVersion
d6da9cbcf66a5bd09e06796328b341463c7da549
[ "MIT" ]
null
null
null
RCVersionTests/HelperTests.cpp
mekmak/RCVersion
d6da9cbcf66a5bd09e06796328b341463c7da549
[ "MIT" ]
null
null
null
RCVersionTests/HelperTests.cpp
mekmak/RCVersion
d6da9cbcf66a5bd09e06796328b341463c7da549
[ "MIT" ]
1
2022-01-11T03:01:37.000Z
2022-01-11T03:01:37.000Z
#include "stdafx.h" #include "AutoFree.h" #include "AutoHClose.h" #include "TestLogger.h" #include "Logger.h" #include <MessageBuffer.h> TEST(AutoFree, NullNoCrash) { void* ptr = nullptr; { ASSERT_EQ(nullptr, ptr); AutoFree af(ptr); } } TEST(AutoFree, Normal) { void* ptr = malloc(100); { ASSERT_NE(nullptr, ptr); AutoFree af(ptr); } } TEST(AutoFree, ExplicitFree) { void* ptr = malloc(100); { ASSERT_NE(nullptr, ptr); AutoFree af(ptr); af.Free(); } } TEST(AutoHClose, NullNoCrash) { HANDLE h = nullptr; { ASSERT_NE(INVALID_HANDLE_VALUE, h); AutoHClose ahc(h); } } TEST(AutoHClose, Normal) { HANDLE h = CreateEvent(nullptr, false, false, nullptr); { ASSERT_NE(INVALID_HANDLE_VALUE, h); AutoHClose ahc(h); } DWORD flags = 0; EXPECT_EQ(0, ::GetHandleInformation(h, &flags)); EXPECT_EQ(ERROR_INVALID_HANDLE, GetLastError()); } TEST(AutoHClose, ExplicitClose) { HANDLE h = CreateEvent(nullptr, false, false, nullptr); { ASSERT_NE(INVALID_HANDLE_VALUE, h); AutoHClose ahc(h); ahc.Close(); DWORD flags = 0; EXPECT_EQ(0, ::GetHandleInformation(h, &flags)); EXPECT_EQ(ERROR_INVALID_HANDLE, GetLastError()); } } TEST(Logger, Normal) { TestLogger tl; Logger logger(tl); EXPECT_FALSE(logger.Error(11, L"Number=%d String=%s", 1234, L"test001")); EXPECT_NE(nullptr, wcsstr(tl.messages.c_str(), L"1234")); EXPECT_NE(nullptr, wcsstr(tl.messages.c_str(), L"test001")); logger.Log(0, L"Number=%d String=%s", 321, L"test02"); EXPECT_NE(nullptr, wcsstr(tl.messages.c_str(), L"321")); EXPECT_NE(nullptr, wcsstr(tl.messages.c_str(), L"test02")); } TEST(MessageBuffer, SetClearSetClear) { MessageBuffer mb; mb.set(L"abcde"); EXPECT_STREQ(L"abcde", mb.message()); mb.clear(); EXPECT_STREQ(L"", mb.message()); mb.set("bcdefg"); EXPECT_STREQ(L"bcdefg", mb.message()); mb.clear(); EXPECT_STREQ(L"", mb.message()); } TEST(MessageBuffer, SetSetClear) { MessageBuffer mb; mb.set(L"abcde"); EXPECT_STREQ(L"abcde", mb.message()); mb.set("bcdefg"); EXPECT_STREQ(L"bcdefg", mb.message()); } TEST(MessageBuffer, AppendAppendClear) { MessageBuffer mb; mb.append(L"abcde"); EXPECT_STREQ(L"abcde", mb.message()); mb.append("bcdefg"); EXPECT_STREQ(L"abcdebcdefg", mb.message()); mb.clear(); EXPECT_STREQ(L"", mb.message()); } TEST(MessageBuffer, FormatFormat) { MessageBuffer mb; mb.format(L"Number=%d String=%hs", 123, "abcd"); EXPECT_STREQ(L"Number=123 String=abcd", mb.message()); mb.format(L" Number=%d String=%s", 234, L"pqrs"); EXPECT_STREQ(L"Number=123 String=abcd Number=234 String=pqrs", mb.message()); }
22.390244
80
0.645243
mekmak
4d85e8014b3dc0b3b9eb45ed06eb3c5b8147ebeb
106
cpp
C++
effective-modern-cpp/test_pimpl.cpp
miaogen123/daily-coding
5d7f463ad1fee5e512aeb36206526b53b9a781f6
[ "MIT" ]
19
2018-07-06T06:53:56.000Z
2022-01-01T16:36:26.000Z
effective-modern-cpp/test_pimpl.cpp
miaogen123/daily-coding
5d7f463ad1fee5e512aeb36206526b53b9a781f6
[ "MIT" ]
null
null
null
effective-modern-cpp/test_pimpl.cpp
miaogen123/daily-coding
5d7f463ad1fee5e512aeb36206526b53b9a781f6
[ "MIT" ]
17
2019-03-27T23:18:43.000Z
2021-01-18T11:17:57.000Z
#include<iostream> #include"pimpl.h" using namespace std; int main(void) { Pimpl Hello; return 0; }
8.153846
20
0.688679
miaogen123
4d866efd0ab4cd6437cadb2778ef83d4d9e7b322
472
hpp
C++
library/ATF/_apex_send_transInfo.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/_apex_send_transInfo.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/_apex_send_transInfo.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <_apex_send_trans.hpp> START_ATF_NAMESPACE namespace Info { using _apex_send_transsize2_ptr = int (WINAPIV*)(struct _apex_send_trans*); using _apex_send_transsize2_clbk = int (WINAPIV*)(struct _apex_send_trans*, _apex_send_transsize2_ptr); }; // end namespace Info END_ATF_NAMESPACE
31.466667
111
0.754237
lemkova
4d8863992957782b84517a902dbdced3c6b7e4cd
10,410
cpp
C++
src/states/approach_object.cpp
betwo/sbc15_fsm
6b5c3d202487dcda8fd2df3dcc904226a3f149a9
[ "MIT" ]
null
null
null
src/states/approach_object.cpp
betwo/sbc15_fsm
6b5c3d202487dcda8fd2df3dcc904226a3f149a9
[ "MIT" ]
null
null
null
src/states/approach_object.cpp
betwo/sbc15_fsm
6b5c3d202487dcda8fd2df3dcc904226a3f149a9
[ "MIT" ]
null
null
null
/// HEADER #include "approach_object.h" /// COMPONENT #include "global_state.h" namespace { template <typename T> int sgn(T val) { return (T(0) < val) - (val < T(0)); } } // namespace ApproachObject::ApproachObject(State* parent, double distance, double velocity) : State(parent) , event_approached(this, "approached the object") , event_orientation_mismatch(this, "the orientation of the object is wrong") , event_failure(this, "approach failed") , distance_(distance) , velocity_(velocity) , observe_time_(5.0) , keep_time_(observe_time_.toSec() + 5.0) { } void ApproachObject::entryAction() { GlobalState& global = GlobalState::getInstance(); std::function<void(const sbc15_msgs::ObjectConstPtr&)> cb = [this](const sbc15_msgs::ObjectConstPtr& o) { if (o->type == type) { GlobalState& global = GlobalState::getInstance(); tf::Stamped<tf::Pose> pose; tf::poseMsgToTF(o->pose, pose); tf::Transform trafo_to_base_link; auto it = frame_to_base_link.find(o->header.frame_id); if (it == frame_to_base_link.end()) { trafo_to_base_link = global.getTransform("/arm_base_link", o->header.frame_id, o->header.stamp, ros::Duration(0.5)); frame_to_base_link[o->header.frame_id] = trafo_to_base_link; } else { trafo_to_base_link = it->second; } tf::Pose object_base_link = trafo_to_base_link * pose; tf::Vector3 pos = object_base_link.getOrigin(); if (pos.z() > -0.35 && pos.z() < 0.35) { tf::Vector3 z_up(0, 0, 1); tf::Vector3 z_obj = tf::quatRotate(object_base_link.getRotation(), z_up); double angle = std::abs(z_up.angle(z_obj)); double max_angle = type == sbc15_msgs::Object::OBJECT_CUP ? M_PI / 2 : M_PI / 4; if ((angle < max_angle) || (M_PI - angle) < max_angle) { double d = pose.getOrigin().length(); if (d < distance_ * 5) { tf::Transform trafo_to_odom = global.getTransform("/odom", "/arm_base_link", o->header.stamp, ros::Duration(0.5)); tf::Pose object_odom = trafo_to_odom * object_base_link; tf::Vector3 error = (start_pose_odom_.getOrigin() - object_odom.getOrigin()); if (error.length() < 0.5) { sbc15_msgs::ObjectPtr o_odom = boost::make_shared<sbc15_msgs::Object>(*o); o_odom->header.frame_id = "/odom"; tf::poseTFToMsg(object_odom, o_odom->pose); objects_.push_back(o_odom); ROS_INFO_STREAM("seeing object"); } else { ROS_INFO_STREAM("drop object @ " << object_odom.getOrigin().x() << " / " << object_odom.getOrigin().y() << " with start pose " << start_pose_odom_.getOrigin().x() << " / " << start_pose_odom_.getOrigin().y() << " with offset " << error.x() << " / " << error.y()); } } else { ROS_INFO_STREAM("drop object @ " << pose.getOrigin().x() << " / " << pose.getOrigin().y() << " with start pose " << start_pose_odom_.getOrigin().x() << " / " << start_pose_odom_.getOrigin().y() << " with distance " << d); } } else { ROS_INFO_STREAM("drop object with angle " << angle); } } else { ROS_INFO_STREAM("drop object with height " << pos.z()); } } ros::Time now = ros::Time::now(); while (!objects_.empty() && objects_.front()->header.stamp + keep_time_ < now) { objects_.pop_front(); } }; sub_objects = global.nh.subscribe<sbc15_msgs::Object>("/objects", 100, cb); start_time_ = ros::Time::now(); sbc15_msgs::ObjectPtr current_object = global.getCurrentObject(); type = current_object->type; tf::poseMsgToTF(current_object->pose, start_pose_odom_); tf::Transform trafo_to_odom = global.getTransform("/odom", current_object->header.frame_id, current_object->header.stamp, ros::Duration(2.0)); start_pose_odom_ = trafo_to_odom * start_pose_odom_; last_error_pos_ = std::numeric_limits<double>::infinity(); last_error_ang_ = std::numeric_limits<double>::infinity(); } void ApproachObject::exitAction() { sub_objects = ros::Subscriber(); } void ApproachObject::iteration() { ros::Time now = ros::Time::now(); if (start_time_ + observe_time_ > now) { return; } if (objects_.empty()) { event_failure.trigger(); } else { sbc15_msgs::ObjectConstPtr target = objects_.back(); position(target); } } void ApproachObject::position(const sbc15_msgs::ObjectConstPtr& object_odom) { GlobalState& global = GlobalState::getInstance(); tf::Stamped<tf::Pose> pose_object_odom; tf::poseMsgToTF(object_odom->pose, pose_object_odom); tf::Transform odom_to_base_link = global.getTransform("/arm_base_link", "/odom"); tf::Pose object_base_link = odom_to_base_link * pose_object_odom; tf::Vector3 pos = object_base_link.getOrigin(); double normXY = hypot(pos.x(), pos.y()); pos -= 0.14 * tf::Vector3(pos.x() / normXY, pos.y() / normXY, 0); global.setCurrentArmGoal(pos.x(), pos.y(), pos.z(), M_PI_2, std::atan2(pos.y(), pos.x())); ROS_INFO_STREAM("going to object @" << object_base_link.getOrigin().x() << "\t / " << object_base_link.getOrigin().y()); double d = distance_; switch (type) { case sbc15_msgs::Object::OBJECT_CUP: { double dp = d + 0.04; tf::Vector3 object_pos = object_base_link.getOrigin(); tf::Vector3 desired_pos = object_pos - dp * (object_pos.normalized()); tf::Pose error = tf::Pose(tf::createQuaternionFromYaw(std::atan2(desired_pos.y(), desired_pos.x())), desired_pos); driveToPose(error); break; } case sbc15_msgs::Object::OBJECT_BATTERY: { double dp = d + 0.1; double obj_yaw = tf::getYaw(object_base_link.getRotation()); tf::Pose desired_pose_a(tf::createQuaternionFromYaw(0), tf::Vector3(dp, 0.0, 0.0)); tf::Pose error_a = object_base_link * desired_pose_a.inverse(); error_a.setRotation(tf::createQuaternionFromYaw(obj_yaw)); tf::Pose desired_pose_b(tf::createQuaternionFromYaw(0), tf::Vector3(-dp, 0.0, 0.0)); tf::Pose error_b = object_base_link * desired_pose_b.inverse(); error_b.setRotation(tf::createQuaternionFromYaw(obj_yaw + M_PI)); tf::Pose error; if (error_a.getOrigin().length() < error_b.getOrigin().length()) { error = error_a; } else { error = error_b; } // TODO: call event_orientation_mismatch ! visualization_msgs::Marker orientation_marker = global.makeMarker(0.0, 1.0, 0.0, "error", 1); orientation_marker.header.frame_id = "/arm_base_link"; orientation_marker.pose.position.x = error.getOrigin().x(); orientation_marker.pose.position.y = error.getOrigin().y(); tf::quaternionTFToMsg(error.getRotation(), orientation_marker.pose.orientation); orientation_marker.type = visualization_msgs::Marker::ARROW; orientation_marker.scale.x = 0.5; orientation_marker.scale.y = 0.075; orientation_marker.scale.z = 0.075; global.mark(orientation_marker); error.setRotation(tf::createQuaternionFromYaw(std::atan2(error.getOrigin().y(), error.getOrigin().x()))); driveToPose(error); } break; default: event_failure.trigger(); return; } } void ApproachObject::driveToPose(const tf::Pose& error) { geometry_msgs::Twist twist; double error_yaw = tf::getYaw(error.getRotation()); double e = std::hypot(error.getOrigin().x(), error.getOrigin().y()); bool pos_good = e < 0.01 || (e < 0.07 && e > last_error_pos_); bool ang_good = std::abs(error_yaw) < M_PI / 4 || (std::abs(error_yaw) < M_PI / 2 && error_yaw > last_error_ang_); ROS_INFO_STREAM("pos error: " << e << "\tangular error: " << error_yaw); if (pos_good && ang_good) { event_approached.trigger(); } else { double ex = error.getOrigin().x(); double ey = error.getOrigin().y(); twist.linear.x = ex * 0.6; twist.linear.y = ey * 0.6; double speed = hypot(twist.linear.x, twist.linear.y); double max_speed = 0.1; double min_speed = 0.005; if (speed > max_speed) { twist.linear.x *= max_speed / speed; twist.linear.y *= max_speed / speed; } else if (speed < min_speed) { twist.linear.x *= min_speed / speed; twist.linear.y *= min_speed / speed; } twist.angular.z = error_yaw * 0.5; } last_error_pos_ = e; last_error_ang_ = error_yaw; GlobalState& global = GlobalState::getInstance(); global.move(twist); visualization_msgs::Marker error_marker = global.makeMarker(1.0, 0.0, 0.0, "error", 0); error_marker.header.frame_id = "/arm_base_link"; geometry_msgs::Point start, end; end.x = error.getOrigin().x(); end.y = error.getOrigin().y(); error_marker.points.push_back(start); error_marker.points.push_back(end); error_marker.type = visualization_msgs::Marker::ARROW; error_marker.scale.x = 0.025; error_marker.scale.y = 0.075; error_marker.scale.z = 0; global.mark(error_marker); ROS_INFO_STREAM("error is " << error.getOrigin().x() << "\t / " << error.getOrigin().y() << ", yaw: " << error_yaw); }
37.178571
120
0.563401
betwo
4d8d667d2d8f36c79781bb361420c3abcc9f8bec
4,265
cpp
C++
aws-cpp-sdk-mediaconvert/source/model/ContainerType.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-mediaconvert/source/model/ContainerType.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-mediaconvert/source/model/ContainerType.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/mediaconvert/model/ContainerType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace MediaConvert { namespace Model { namespace ContainerTypeMapper { static const int F4V_HASH = HashingUtils::HashString("F4V"); static const int ISMV_HASH = HashingUtils::HashString("ISMV"); static const int M2TS_HASH = HashingUtils::HashString("M2TS"); static const int M3U8_HASH = HashingUtils::HashString("M3U8"); static const int CMFC_HASH = HashingUtils::HashString("CMFC"); static const int MOV_HASH = HashingUtils::HashString("MOV"); static const int MP4_HASH = HashingUtils::HashString("MP4"); static const int MPD_HASH = HashingUtils::HashString("MPD"); static const int MXF_HASH = HashingUtils::HashString("MXF"); static const int RAW_HASH = HashingUtils::HashString("RAW"); ContainerType GetContainerTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == F4V_HASH) { return ContainerType::F4V; } else if (hashCode == ISMV_HASH) { return ContainerType::ISMV; } else if (hashCode == M2TS_HASH) { return ContainerType::M2TS; } else if (hashCode == M3U8_HASH) { return ContainerType::M3U8; } else if (hashCode == CMFC_HASH) { return ContainerType::CMFC; } else if (hashCode == MOV_HASH) { return ContainerType::MOV; } else if (hashCode == MP4_HASH) { return ContainerType::MP4; } else if (hashCode == MPD_HASH) { return ContainerType::MPD; } else if (hashCode == MXF_HASH) { return ContainerType::MXF; } else if (hashCode == RAW_HASH) { return ContainerType::RAW; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<ContainerType>(hashCode); } return ContainerType::NOT_SET; } Aws::String GetNameForContainerType(ContainerType enumValue) { switch(enumValue) { case ContainerType::F4V: return "F4V"; case ContainerType::ISMV: return "ISMV"; case ContainerType::M2TS: return "M2TS"; case ContainerType::M3U8: return "M3U8"; case ContainerType::CMFC: return "CMFC"; case ContainerType::MOV: return "MOV"; case ContainerType::MP4: return "MP4"; case ContainerType::MPD: return "MPD"; case ContainerType::MXF: return "MXF"; case ContainerType::RAW: return "RAW"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace ContainerTypeMapper } // namespace Model } // namespace MediaConvert } // namespace Aws
31.131387
92
0.582884
curiousjgeorge
4d903f8a3926963e403e03f996be4d0c511644ec
236
cpp
C++
Game/Client/WXClient/Network/PacketHandler/CGAskDetaiXinFaListHandler.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/Client/WXClient/Network/PacketHandler/CGAskDetaiXinFaListHandler.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/Client/WXClient/Network/PacketHandler/CGAskDetaiXinFaListHandler.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
#include "StdAfx.h" #include "CGAskDetailXinFaList.h" uint CGAskSkillClassHandler::Execute( CGAskSkillClass* pPacket, Player* pPlayer ) { __ENTER_FUNCTION return PACKET_EXE_CONTINUE ; __LEAVE_FUNCTION return PACKET_EXE_ERROR ; }
15.733333
81
0.800847
hackerlank
4d94b0c0b152611dde13cd5bfec4f9b4b75a10d4
3,884
cpp
C++
cpp/main13.cpp
hangyejiadao1993/Algorithm
4b3677cccb2efb4ffa7aacea6404dfe43a973780
[ "Apache-2.0" ]
null
null
null
cpp/main13.cpp
hangyejiadao1993/Algorithm
4b3677cccb2efb4ffa7aacea6404dfe43a973780
[ "Apache-2.0" ]
null
null
null
cpp/main13.cpp
hangyejiadao1993/Algorithm
4b3677cccb2efb4ffa7aacea6404dfe43a973780
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<queue> using namespace std; template<class T> struct TreeNode { T data; TreeNode<T> *left; TreeNode<T> *right; TreeNode(const T &x):data(x), left(NULL), right(NULL){} }; template<class T> bool IsComplete(TreeNode<T>*root){ //树为空,返回错误 if (root==NULL) { return false; } //树不为空 queue<TreeNode<T>*>q; q.push(root); while (!q.empty()) { TreeNode<T> *top=q.front(); if (top->left&&top->right) { q.pop(); q.push(top->left); q.push(top->right); } //如果该节点左孩子为空,右孩子不为空,则一定不是完全二叉树 if (top->left==NULL&&top->right) { return false; } //如果该节点左孩子不为空,右孩子为空或者该节点为叶子节点,则该节点之后的所有结点都是叶子节点 if ((top->left&&top->right==NULL)||(top->left==NULL&&top->right==NULL)) { if (NULL!=top->left&&NULL==top->right) { q.push(top->left); } q.pop(); while (!q.empty()) { top=q.front(); if (top->left==NULL&&top->right==NULL) { q.pop(); }else { return false; } } return true; } } return true; } //慢二叉树 void test1(){ // 1 // 2 3 // 4 5 6 7 TreeNode<int> *node1 = new TreeNode<int>(1); TreeNode<int> *node2 = new TreeNode<int>(2); TreeNode<int> *node3 = new TreeNode<int>(3); TreeNode<int> *node4 = new TreeNode<int>(4); TreeNode<int> *node5 = new TreeNode<int>(5); TreeNode<int> *node6 = new TreeNode<int>(6); TreeNode<int> *node7 = new TreeNode<int>(7); node1->left = node2; node1->right = node3; node2->left = node4; node2->right = node5; node3->left = node6; node3->right = node7; cout << IsComplete<int>(node1) << endl; } //二叉树为空 void test2() { cout << IsComplete<int>(NULL) << endl; } //3.二叉树不为空,也不是满二叉树,遇到一个结点左孩子为空,右孩子不为空 void test3() { // 1 // 2 3 // 4 5 7 TreeNode<int> *node1 = new TreeNode<int>(1); TreeNode<int> *node2 = new TreeNode<int>(2); TreeNode<int> *node3 = new TreeNode<int>(3); TreeNode<int> *node4 = new TreeNode<int>(4); TreeNode<int> *node5 = new TreeNode<int>(5); TreeNode<int> *node7 = new TreeNode<int>(7); node1->left = node2; node1->right = node3; node2->left = node4; node2->right = node5; node3->right = node7; cout << IsComplete<int>(node1) << endl; } //4.二叉树不为空,也不是满二叉树,遇到叶子节点,则该叶子节点之后的所有结点都为叶子节点 void test4() { // 1 // 2 3 // 4 5 TreeNode<int> *node1 = new TreeNode<int>(1); TreeNode<int> *node2 = new TreeNode<int>(2); TreeNode<int> *node3 = new TreeNode<int>(3); TreeNode<int> *node4 = new TreeNode<int>(4); TreeNode<int> *node5 = new TreeNode<int>(5); node1->left = node2; node1->right = node3; node2->left = node4; node2->right = node5; cout << IsComplete<int>(node1) << endl; } //4.二叉树不为空,也不是满二叉树,遇到左孩子不为空,右孩子为空的结点,则该节点之后的所有结点都为叶子节点 void test5() { // 1 // 2 3 // 4 5 6 TreeNode<int> *node1 = new TreeNode<int>(1); TreeNode<int> *node2 = new TreeNode<int>(2); TreeNode<int> *node3 = new TreeNode<int>(3); TreeNode<int> *node4 = new TreeNode<int>(4); TreeNode<int> *node5 = new TreeNode<int>(5); TreeNode<int> *node6 = new TreeNode<int>(6); node1->left = node2; node1->right = node3; node2->left = node4; node2->right = node5; node3->left = node6; cout << IsComplete<int>(node1) << endl; } int main() { test1(); test2(); test3(); test4(); test5(); system("pause"); return 0; }
22.982249
78
0.512616
hangyejiadao1993
4d9a7b0efb14557ce6932aed1f527ba70a057483
20,074
cpp
C++
src/Core/AssetModule/AssetModule.cpp
Adminotech/tundra
8270097dbf79c3ec1935cf66c7979eeef9c24c0e
[ "Apache-2.0" ]
null
null
null
src/Core/AssetModule/AssetModule.cpp
Adminotech/tundra
8270097dbf79c3ec1935cf66c7979eeef9c24c0e
[ "Apache-2.0" ]
null
null
null
src/Core/AssetModule/AssetModule.cpp
Adminotech/tundra
8270097dbf79c3ec1935cf66c7979eeef9c24c0e
[ "Apache-2.0" ]
null
null
null
// For conditions of distribution and use, see copyright notice in LICENSE #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "AssetModule.h" #include "LocalAssetProvider.h" #include "HttpAssetProvider.h" #include "HttpAssetStorage.h" #include "Framework.h" #include "Profiler.h" #include "CoreException.h" #include "AssetAPI.h" #include "LocalAssetStorage.h" #include "ConsoleAPI.h" #include "Application.h" #include "CoreTypes.h" #include "KristalliProtocolModule.h" #include "TundraLogicModule.h" #include "TundraMessages.h" #include "Client.h" #include "Server.h" #include "UserConnectedResponseData.h" #include "UserConnection.h" #include "MsgAssetDeleted.h" #include "MsgAssetDiscovery.h" #include <kNetBuildConfig.h> #include <kNet/MessageConnection.h> #include <QDir> #include "StaticPluginRegistry.h" #include "MemoryLeakCheck.h" AssetModule::AssetModule() :IModule("Asset") { } AssetModule::~AssetModule() { } void AssetModule::Load() { Fw()->Asset()->RegisterAssetProvider(MAKE_SHARED(HttpAssetProvider, Fw())); } void AssetModule::Initialize() { QString systemAssetDir = Application::InstallationDirectory() + "data/assets"; AssetStoragePtr storage = Fw()->Asset()->AssetProvider<LocalAssetProvider>()->AddStorageDirectory(systemAssetDir, "System", true, false); // AssetStoragePtr storage = local->AddStorageDirectory(systemAssetDir, "System", true, QFileInfo(systemAssetDir).isWritable()); storage->SetReplicated(false); // If we are a server, don't pass this storage to the client. Fw()->RegisterDynamicObject("assetModule", this); Fw()->Console()->RegisterCommand( "requestAsset", "Request asset from server. Usage: requestAsset(assetRef, assetType)", this, SLOT(ConsoleRequestAsset(const QString &, const QString &))); Fw()->Console()->RegisterCommand( "addAssetStorage", "Usage: addAssetStorage(storageString), f.ex.: " "addAssetStorage(name=MyAssets;type=HttpAssetStorage;src=http://www.myserver.com/;default;)", this, SLOT(AddAssetStorage(const QString &))); Fw()->Console()->RegisterCommand( "listAssetStorages", "Serializes all currently registered asset storages to the console output log.", this, SLOT(ListAssetStorages())); Fw()->Console()->RegisterCommand( "refreshHttpStorages", "Refreshes known assetrefs for all http asset storages", this, SLOT(ConsoleRefreshHttpStorages())); Fw()->Console()->RegisterCommand( "dumpAssetTransfers", "Dumps debugging information of current asset transfers to console", this, SLOT(ConsoleDumpAssetTransfers())); Fw()->Console()->RegisterCommand( "dumpAssets", "Lists all assets known to the Asset API", this, SLOT(ConsoleDumpAssets())); ProcessCommandLineOptions(); TundraLogic::Server *server = Fw()->Module<TundraLogicModule>()->GetServer().get(); connect(server, SIGNAL(UserConnected(u32, UserConnection *, UserConnectedResponseData *)), this, SLOT(ServerNewUserConnected(u32, UserConnection *, UserConnectedResponseData *))); TundraLogic::Client *client = Fw()->Module<TundraLogicModule>()->GetClient().get(); connect(client, SIGNAL(Connected(UserConnectedResponseData *)), this, SLOT(ClientConnectedToServer(UserConnectedResponseData *))); connect(client, SIGNAL(Disconnected()), this, SLOT(ClientDisconnectedFromServer())); KristalliProtocolModule *kristalli = Fw()->Module<KristalliProtocolModule>(); connect(kristalli, SIGNAL(NetworkMessageReceived(kNet::MessageConnection *, kNet::packet_id_t, kNet::message_id_t, const char *, size_t)), this, SLOT(HandleKristalliMessage(kNet::MessageConnection*, kNet::packet_id_t, kNet::message_id_t, const char*, size_t)), Qt::UniqueConnection); // Connect to asset uploads & deletions from storage to be able to broadcast asset discovery & deletion messages connect(Fw()->Asset(), SIGNAL(AssetUploaded(const QString &)), this, SLOT(OnAssetUploaded(const QString &))); connect(Fw()->Asset(), SIGNAL(AssetDeletedFromStorage(const QString&)), this, SLOT(OnAssetDeleted(const QString&))); } void AssetModule::ProcessCommandLineOptions() { const bool hasFile = Fw()->HasCommandLineParameter("--file"); const bool hasStorage = Fw()->HasCommandLineParameter("--storage"); const QStringList files = Fw()->CommandLineParameters("--file"); const QStringList storages = Fw()->CommandLineParameters("--storage"); if (hasFile && files.isEmpty()) LogError("AssetModule: --file specified without a value."); if (hasStorage && storages.isEmpty()) LogError("AssetModule: --storage specified without a value."); foreach(const QString &file, files) { AssetStoragePtr storage = Fw()->Asset()->DeserializeAssetStorageFromString(file.trimmed(), false); Fw()->Asset()->SetDefaultAssetStorage(storage); } foreach(const QString &storageName, storages) { AssetStoragePtr storage = Fw()->Asset()->DeserializeAssetStorageFromString(storageName.trimmed(), false); if (files.isEmpty()) // If "--file" was not specified, then use "--storage" as the default. (If both are specified, "--file" takes precedence over "--storage"). Fw()->Asset()->SetDefaultAssetStorage(storage); } if (Fw()->HasCommandLineParameter("--defaultstorage")) { QStringList defaultStorages = Fw()->CommandLineParameters("--defaultstorage"); if (defaultStorages.size() == 1) { AssetStoragePtr defaultStorage = Fw()->Asset()->AssetStorageByName(defaultStorages[0]); if (!defaultStorage) LogError("Cannot set storage \"" + defaultStorages[0] + "\" as the default storage, since it doesn't exist!"); else Fw()->Asset()->SetDefaultAssetStorage(defaultStorage); } else LogError("Parameter --defaultstorage may be specified exactly once, and must contain a single value!"); } } void AssetModule::ConsoleRefreshHttpStorages() { RefreshHttpStorages(); } void AssetModule::ConsoleRequestAsset(const QString &assetRef, const QString &assetType) { Fw()->Asset()->RequestAsset(assetRef, assetType, true); } void AssetModule::AddAssetStorage(const QString &storageString) { Fw()->Asset()->DeserializeAssetStorageFromString(storageString, false); } void AssetModule::ListAssetStorages() { LogInfo("Registered storages: "); foreach(const AssetStoragePtr &storage, Fw()->Asset()->AssetStorages()) { QString storageString = storage->SerializeToString(); if (Fw()->Asset()->DefaultAssetStorage() == storage) storageString += ";default"; LogInfo(storageString); } } void AssetModule::LoadAllLocalAssetsWithSuffix(const QString &suffix, const QString &assetType) { foreach(const AssetStoragePtr &s, Fw()->Asset()->AssetStorages()) { LocalAssetStorage *storage = dynamic_cast<LocalAssetStorage*>(s.get()); if (storage) storage->LoadAllAssetsOfType(Fw()->Asset(), suffix, assetType); } } void AssetModule::RefreshHttpStorages() { foreach(const AssetStoragePtr &s, Fw()->Asset()->AssetStorages()) { HttpAssetStorage *storage = dynamic_cast<HttpAssetStorage*>(s.get()); if (storage) storage->RefreshAssetRefs(); } } void AssetModule::ServerNewUserConnected(u32 /*connectionID*/, UserConnection *connection, UserConnectedResponseData *responseData) { QDomDocument &doc = responseData->responseData; QDomElement assetRoot = doc.createElement("asset"); doc.appendChild(assetRoot); // Did we get a new user from the same computer the server is running at? bool isLocalhostConnection = false; KNetUserConnection* kNetConn = dynamic_cast<KNetUserConnection*>(connection); if (kNetConn && kNetConn->connection) { isLocalhostConnection = (kNetConn->connection->RemoteEndPoint().IPToString() == "127.0.0.1" || kNetConn->connection->LocalEndPoint().IPToString() == kNetConn->connection->RemoteEndPoint().IPToString()); } // Serialize all storages to the client. If the client is from the same computer than the server, we can also serialize the LocalAssetStorages. std::vector<AssetStoragePtr> storages = Fw()->Asset()->AssetStorages(); for(size_t i = 0; i < storages.size(); ++i) { bool isLocalStorage = (dynamic_cast<LocalAssetStorage*>(storages[i].get()) != 0); if (storages[i]->IsReplicated() && (!isLocalStorage || isLocalhostConnection)) { QDomElement storage = doc.createElement("storage"); storage.setAttribute("data", storages[i]->SerializeToString(!isLocalhostConnection)); assetRoot.appendChild(storage); } } // Specify which storage to use as default. AssetStoragePtr defaultStorage = Fw()->Asset()->DefaultAssetStorage(); bool defaultStorageIsLocal = (dynamic_cast<LocalAssetStorage*>(defaultStorage.get()) != 0); if (defaultStorage && (!defaultStorageIsLocal || isLocalhostConnection)) { QDomElement storage = doc.createElement("defaultStorage"); storage.setAttribute("name", defaultStorage->Name()); assetRoot.appendChild(storage); if (!defaultStorage->IsReplicated()) LogWarning("Server specified the client to use the storage \"" + defaultStorage->Name() + "\" as default, but it is not a replicated storage!"); } // Fill the same data as JSON for web clients QVariantMap storageData; storageData["default"] = true; storageData["name"] = defaultStorage->Name(); storageData["type"] = defaultStorage->Type(); storageData["src"] = defaultStorage->BaseURL(); responseData->responseDataJson["storage"] = storageData; } void AssetModule::DetermineStorageTrustStatus(AssetStoragePtr storage) { // If the --trustserverstorages command line parameter is set, we trust each storage exactly the way the server does. ///\todo Make the a end-user option at runtime/connection time to specify per-server instance whether --trustserverstorages is in effect. if (!Fw()->HasCommandLineParameter("--trustserverstorages")) { ///\todo Read from ConfigAPI whether to set false/ask/true here. ///\todo If the trust state is 'ask', show a *non-modal* notification -> config dialog if the user wants to trust content from this source. storage->SetTrustState(IAssetStorage::StorageAskTrust); } } void AssetModule::ClientConnectedToServer(UserConnectedResponseData *responseData) { QDomDocument &doc = responseData->responseData; QDomElement assetRoot = doc.firstChildElement("asset"); if (!assetRoot.isNull()) { for (QDomElement storage = assetRoot.firstChildElement("storage"); !storage.isNull(); storage = storage.nextSiblingElement("storage")) { QString storageData = storage.attribute("data"); bool connectedToRemoteServer = true; // If false, we connected to localhost. ///\todo Determine here whether we connected to localhost, and if so, set connectedToRemoteServer = false. AssetStoragePtr assetStorage = Fw()->Asset()->DeserializeAssetStorageFromString(storageData, connectedToRemoteServer); // Remember that this storage was received from the server, so we can later stop using it when we disconnect (and possibly reconnect to another server). if (assetStorage) { assetStorage->SetReplicated(true); // We got this from the server. if (connectedToRemoteServer) // If connected to localhost, we always trust the same storages the server is trusting, so don't need to call DetermineStorageTrustStatus. DetermineStorageTrustStatus(assetStorage); storagesReceivedFromServer.push_back(assetStorage); } } QDomElement defaultStorage = assetRoot.firstChildElement("defaultStorage"); if (!defaultStorage.isNull()) { QString defaultStorageName = defaultStorage.attribute("name"); AssetStoragePtr defaultStoragePtr = Fw()->Asset()->AssetStorageByName(defaultStorageName); if (defaultStoragePtr) Fw()->Asset()->SetDefaultAssetStorage(defaultStoragePtr); } } } void AssetModule::ClientDisconnectedFromServer() { for(size_t i = 0; i < storagesReceivedFromServer.size(); ++i) { AssetStoragePtr storage = storagesReceivedFromServer[i].lock(); if (storage) Fw()->Asset()->RemoveAssetStorage(storage->Name()); } storagesReceivedFromServer.clear(); } void AssetModule::HandleKristalliMessage(kNet::MessageConnection* source, kNet::packet_id_t, kNet::message_id_t id, const char* data, size_t numBytes) { switch (id) { case cAssetDiscoveryMessage: { MsgAssetDiscovery msg(data, numBytes); HandleAssetDiscovery(source, msg); } break; case cAssetDeletedMessage: { MsgAssetDeleted msg(data, numBytes); HandleAssetDeleted(source, msg); } break; } } void AssetModule::HandleAssetDiscovery(kNet::MessageConnection* source, MsgAssetDiscovery& msg) { QString assetRef = QString::fromStdString(BufferToString(msg.assetRef)); QString assetType = QString::fromStdString(BufferToString(msg.assetType)); // Check for possible malicious discovery message and ignore it. Otherwise let AssetAPI handle if (!ShouldReplicateAssetDiscovery(assetRef)) return; // If we are server, the message had to come from a client, and we replicate it to everyone except the sender if (Fw()->Module<TundraLogicModule>()->IsServer()) foreach(UserConnectionPtr userConn, Fw()->Module<KristalliProtocolModule>()->UserConnections()) { KNetUserConnection* kNetConn = dynamic_cast<KNetUserConnection*>(userConn.get()); if (kNetConn->connection != source) userConn->Send(msg); } // Then let assetAPI handle locally Fw()->Asset()->HandleAssetDiscovery(assetRef, assetType); } void AssetModule::HandleAssetDeleted(kNet::MessageConnection* source, MsgAssetDeleted& msg) { QString assetRef = QString::fromStdString(BufferToString(msg.assetRef)); // Check for possible malicious delete message and ignore it. Otherwise let AssetAPI handle if (!ShouldReplicateAssetDiscovery(assetRef)) return; // If we are server, the message had to come from a client, and we replicate it to everyone except the sender if (Fw()->Module<TundraLogicModule>()->IsServer()) foreach(UserConnectionPtr userConn, Fw()->Module<KristalliProtocolModule>()->UserConnections()) { KNetUserConnection* kNetConn = dynamic_cast<KNetUserConnection*>(userConn.get()); if (kNetConn->connection != source) userConn->Send(msg); } // Then let assetAPI handle locally Fw()->Asset()->HandleAssetDeleted(assetRef); } void AssetModule::OnAssetUploaded(const QString& assetRef) { // Check whether the asset upload needs to be replicated if (!ShouldReplicateAssetDiscovery(assetRef)) return; /// \todo Would preferably need the asset type as well for the msg. MsgAssetDiscovery msg; msg.assetRef = StringToBuffer(assetRef.toStdString()); /// @bug Convert to UTF-8 instead! TundraLogicModule* tundra = Fw()->Module<TundraLogicModule>(); if (tundra->IsServer()) // We are server, send to everyone { foreach(UserConnectionPtr userConn, Fw()->Module<KristalliProtocolModule>()->UserConnections()) userConn->Send(msg); } else // We are client, send to server { kNet::MessageConnection* connection = tundra->GetClient()->MessageConnection(); if (connection) connection->Send(msg); } } void AssetModule::OnAssetDeleted(const QString& assetRef) { // Check whether the asset delete needs to be replicated if (!ShouldReplicateAssetDiscovery(assetRef)) return; MsgAssetDeleted msg; msg.assetRef = StringToBuffer(assetRef.toStdString()); /// @bug Convert to UTF-8 instead! TundraLogicModule* tundra = Fw()->Module<TundraLogicModule>(); if (tundra->IsServer()) // We are server, send to everyone { foreach(UserConnectionPtr userConn, Fw()->Module<KristalliProtocolModule>()->UserConnections()) userConn->Send(msg); } else // We are client, send to server { kNet::MessageConnection* connection = tundra->GetClient()->MessageConnection(); if (connection) connection->Send(msg); } } void AssetModule::ConsoleDumpAssetTransfers() { AssetAPI* asset = Fw()->Asset(); LogInfo("Current transfers:"); const AssetTransferMap& currentTransfers = asset->CurrentTransfers(); for(AssetTransferMap::const_iterator i = currentTransfers.begin(); i != currentTransfers.end(); ++i) { AssetPtr assetPtr = asset->FindAsset(i->first); unsigned numPendingDependencies = assetPtr ? asset->NumPendingDependencies(assetPtr) : 0; if (numPendingDependencies > 0) { LogInfo(i->first + ", " + QString::number(numPendingDependencies) + " pending dependencies"); std::vector<AssetReference> refs = assetPtr->FindReferences(); for(size_t i = 0; i < refs.size(); ++i) LogInfo(" Depends on \"" + refs[i].ref + "\", of type \"" + refs[i].type + "\""); } else LogInfo(i->first); } LogInfo("Ready asset transfers:"); const std::vector<AssetTransferPtr> &readyTransfers = asset->DebugGetReadyTransfers(); for(unsigned i = 0; i < readyTransfers.size(); ++i) LogInfo(readyTransfers[i]->source.ref); /* const AssetAPI::AssetDependenciesMap &dependencies = asset->DebugGetAssetDependencies(); LogInfo("Asset dependencies:"); for (AssetAPI::AssetDependenciesMap::const_iterator i = dependencies.begin(); i != dependencies.end(); ++i) LogInfo("\"" + i->first + "\" -> \"" + i->second + "\""); */ } void AssetModule::ConsoleDumpAssets() { LogInfo("Current assets:"); const AssetMap& assets = Fw()->Asset()->Assets(); for(AssetMap::const_iterator i = assets.begin(); i != assets.end(); ++i) { QString name = i->first; if (!i->second->IsLoaded()) name += " (unloaded)"; LogInfo(name); } } bool AssetModule::ShouldReplicateAssetDiscovery(const QString& assetRef) { QString protocol; AssetAPI::AssetRefType type = AssetAPI::ParseAssetRef(assetRef, &protocol); if (type == AssetAPI::AssetRefInvalid || type == AssetAPI::AssetRefLocalPath || type == AssetAPI::AssetRefLocalUrl || type == AssetAPI::AssetRefRelativePath) return false; else { AssetPtr asset = Fw()->Asset()->FindAsset(assetRef); AssetStoragePtr storage = asset ? asset->AssetStorage() : AssetStoragePtr(); // If the storage exists, simply check that it's replicated and it is an HttpAssetStorage /// \todo Evaluate whether asset discovery should be/needs to be supported for other assetstorages if (storage && storage->IsReplicated() && dynamic_cast<HttpAssetStorage*>(storage.get()) != 0) return true; // If the storage does not exist, check the protocol part of the ref. if (!storage) { if (protocol.compare("http", Qt::CaseInsensitive) == 0 || protocol.compare("https", Qt::CaseInsensitive) == 0) return true; } } return false; } extern "C" { #ifndef ANDROID DLLEXPORT void TundraPluginMain(Framework *fw) #else DEFINE_STATIC_PLUGIN_MAIN(AssetModule) #endif { Framework::SetInstance(fw); // Inside this DLL, remember the pointer to the global framework object. fw->RegisterModule(new AssetModule()); } }
41.304527
183
0.679735
Adminotech
4da034dff5655986cb39303b916a473a46c172ff
20,339
cpp
C++
framework/command_record.cpp
ohmaya/vulkan_best_practice_for_mobile_developers
356cf5229687346adcde2ca08875aa77a8bf530a
[ "MIT" ]
null
null
null
framework/command_record.cpp
ohmaya/vulkan_best_practice_for_mobile_developers
356cf5229687346adcde2ca08875aa77a8bf530a
[ "MIT" ]
null
null
null
framework/command_record.cpp
ohmaya/vulkan_best_practice_for_mobile_developers
356cf5229687346adcde2ca08875aa77a8bf530a
[ "MIT" ]
null
null
null
/* Copyright (c) 2019, Arm Limited and Contributors * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "command_record.h" #include "common/error.h" #include "common/logging.h" #include "core/descriptor_set_layout.h" #include "core/device.h" #include "core/shader_module.h" #include "rendering/render_context.h" namespace vkb { CommandRecord::CommandRecord(Device &device) : device{device} {} void CommandRecord::reset() { // Clear stream content stream.str(""); pipeline_state.reset(); resource_binding_state.reset(); descriptor_set_layout_state.clear(); render_pass_bindings.clear(); descriptor_set_bindings.clear(); pipeline_bindings.clear(); } Device &CommandRecord::get_device() { return device; } const std::ostringstream &CommandRecord::get_stream() const { return stream; } std::vector<RenderPassBinding> &CommandRecord::get_render_pass_bindings() { return render_pass_bindings; } const std::vector<PipelineBinding> &CommandRecord::get_pipeline_bindings() const { return pipeline_bindings; } const std::vector<DescriptorSetBinding> &CommandRecord::get_descriptor_set_bindings() const { return descriptor_set_bindings; } void CommandRecord::begin(VkCommandBufferUsageFlags flags) { // Write command parameters write(stream, CommandType::Begin, flags); } void CommandRecord::end() { // Write command parameters write(stream, CommandType::End); } void vkb::CommandRecord::begin_render_pass(const RenderTarget & render_target, const std::vector<LoadStoreInfo> &load_store_infos, const std::vector<VkClearValue> & clear_values, const VkSubpassContents contents) { // Reset pipeline state pipeline_state.reset(); resource_binding_state.reset(); descriptor_set_layout_state.clear(); RenderPassBinding render_pass_binding{stream.tellp(), render_target}; render_pass_binding.load_store_infos = load_store_infos; render_pass_binding.clear_values = clear_values; render_pass_binding.contents = contents; // Add first subpass to render pass auto &subpass = render_pass_binding.subpasses.emplace_back(SubpassDesc{stream.tellp()}); subpass.input_attachments = render_target.get_input_attachments(); subpass.output_attachments = render_target.get_output_attachments(); // Update blend state attachments auto blend_state = pipeline_state.get_color_blend_state(); blend_state.attachments.resize(subpass.output_attachments.size()); pipeline_state.set_color_blend_state(blend_state); // Add render pass render_pass_bindings.push_back(render_pass_binding); } void CommandRecord::next_subpass() { // Increment subpass index pipeline_state.set_subpass_index(pipeline_state.get_subpass_index() + 1); // Add subpass to render pass auto &render_pass_desc = render_pass_bindings.back(); auto &subpass = render_pass_desc.subpasses.emplace_back(SubpassDesc{stream.tellp()}); subpass.input_attachments = render_pass_desc.render_target.get_input_attachments(); subpass.output_attachments = render_pass_desc.render_target.get_output_attachments(); // Update blend state attachments auto blend_state = pipeline_state.get_color_blend_state(); blend_state.attachments.resize(subpass.output_attachments.size()); pipeline_state.set_color_blend_state(blend_state); // Descriptor set descriptor_set_layout_state.clear(); resource_binding_state.reset(); // Write command parameters write(stream, CommandType::NextSubpass); } void CommandRecord::prepare_pipeline_bindings(CommandRecord &recorder, RenderPassBinding &render_pass_desc) { // Iterate over each graphics state that was bound within the subpass for (auto &subpass_desc : render_pass_desc.subpasses) { for (auto &pipeline_desc : subpass_desc.pipeline_descs) { pipeline_desc.pipeline_state.set_render_pass(*render_pass_desc.render_pass); auto &pipeline = device.get_resource_cache().request_graphics_pipeline(pipeline_desc.pipeline_state); recorder.pipeline_bindings.push_back({pipeline_desc.event_id, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline}); } } } void CommandRecord::resolve_subpasses() { auto &render_pass_desc = render_pass_bindings.back(); std::vector<SubpassInfo> subpasses(render_pass_desc.subpasses.size()); auto subpass_it = render_pass_desc.subpasses.begin(); for (auto &subpass_desc : subpasses) { subpass_desc.input_attachments = subpass_it->input_attachments; subpass_desc.output_attachments = subpass_it->output_attachments; ++subpass_it; } render_pass_desc.render_pass = &device.get_resource_cache().request_render_pass(render_pass_desc.render_target.get_attachments(), render_pass_desc.load_store_infos, subpasses); render_pass_desc.framebuffer = &device.get_resource_cache().request_framebuffer(render_pass_desc.render_target, *render_pass_desc.render_pass); prepare_pipeline_bindings(*this, render_pass_desc); } void CommandRecord::execute_commands(std::vector<vkb::CommandBuffer *> &sec_cmd_bufs) { auto &render_pass_desc = render_pass_bindings.back(); // Also update render pass and pipeline descriptions for every secondary command buffer for (auto &cmd_buf : sec_cmd_bufs) { auto &sec_render_pass_desc = cmd_buf->get_recorder().render_pass_bindings.back(); sec_render_pass_desc.render_pass = render_pass_desc.render_pass; sec_render_pass_desc.framebuffer = render_pass_desc.framebuffer; prepare_pipeline_bindings(cmd_buf->get_recorder(), sec_render_pass_desc); } write(stream, CommandType::ExecuteCommands, to_u32(render_pass_bindings.size() - 1), sec_cmd_bufs); } void CommandRecord::end_render_pass() { write(stream, CommandType::EndRenderPass); } void CommandRecord::bind_pipeline_layout(PipelineLayout &pipeline_layout) { pipeline_state.set_pipeline_layout(pipeline_layout); } void CommandRecord::set_specialization_constant(uint32_t constant_id, const std::vector<uint8_t> &data) { pipeline_state.set_specialization_constant(constant_id, data); } void CommandRecord::push_constants(uint32_t offset, const std::vector<uint8_t> &values) { const PipelineLayout &pipeline_layout = pipeline_state.get_pipeline_layout(); VkShaderStageFlags shader_stage = pipeline_layout.get_push_constant_range_stage(offset, to_u32(values.size())); if (shader_stage) { // Write command parameters write(stream, CommandType::PushConstants, pipeline_layout.get_handle(), shader_stage, offset, values); } else { LOGW("Push constant range [{}, {}] not found", offset, values.size()); } } void CommandRecord::bind_buffer(const core::Buffer &buffer, VkDeviceSize offset, VkDeviceSize range, uint32_t set, uint32_t binding, uint32_t array_element) { resource_binding_state.bind_buffer(buffer, offset, range, set, binding, array_element); } void CommandRecord::bind_image(const core::ImageView &image_view, const core::Sampler &sampler, uint32_t set, uint32_t binding, uint32_t array_element) { resource_binding_state.bind_image(image_view, sampler, set, binding, array_element); } void CommandRecord::bind_input(const core::ImageView &image_view, uint32_t set, uint32_t binding, uint32_t array_element) { resource_binding_state.bind_input(image_view, set, binding, array_element); } void CommandRecord::bind_vertex_buffers(uint32_t first_binding, const std::vector<std::reference_wrapper<const vkb::core::Buffer>> &buffers, const std::vector<VkDeviceSize> &offsets) { std::vector<VkBuffer> native_buffers(buffers.size(), VK_NULL_HANDLE); std::transform(buffers.begin(), buffers.end(), native_buffers.begin(), [](const core::Buffer &buffer) { return buffer.get_handle(); }); // Write command parameters write(stream, CommandType::BindVertexBuffers, first_binding, native_buffers, offsets); } void CommandRecord::bind_index_buffer(const core::Buffer &buffer, VkDeviceSize offset, VkIndexType index_type) { // Write command parameters write(stream, CommandType::BindIndexBuffer, buffer.get_handle(), offset, index_type); } void CommandRecord::set_viewport_state(const ViewportState &state_info) { pipeline_state.set_viewport_state(state_info); } void CommandRecord::set_vertex_input_state(const VertexInputState &state_info) { pipeline_state.set_vertex_input_state(state_info); } void CommandRecord::set_input_assembly_state(const InputAssemblyState &state_info) { pipeline_state.set_input_assembly_state(state_info); } void CommandRecord::set_rasterization_state(const RasterizationState &state_info) { pipeline_state.set_rasterization_state(state_info); } void CommandRecord::set_multisample_state(const MultisampleState &state_info) { pipeline_state.set_multisample_state(state_info); } void CommandRecord::set_depth_stencil_state(const DepthStencilState &state_info) { pipeline_state.set_depth_stencil_state(state_info); } void CommandRecord::set_color_blend_state(const ColorBlendState &state_info) { pipeline_state.set_color_blend_state(state_info); } void CommandRecord::set_viewport(uint32_t first_viewport, const std::vector<VkViewport> &viewports) { // Write command parameters write(stream, CommandType::SetViewport, first_viewport, viewports); } void CommandRecord::set_scissor(uint32_t first_scissor, const std::vector<VkRect2D> &scissors) { // Write command parameters write(stream, CommandType::SetScissor, first_scissor, scissors); } void CommandRecord::set_line_width(float line_width) { // Write command parameters write(stream, CommandType::SetLineWidth, line_width); } void CommandRecord::set_depth_bias(float depth_bias_constant_factor, float depth_bias_clamp, float depth_bias_slope_factor) { // Write command parameters write(stream, CommandType::SetDepthBias, depth_bias_constant_factor, depth_bias_clamp, depth_bias_slope_factor); } void CommandRecord::set_blend_constants(const std::array<float, 4> &blend_constants) { // Write command parameters write(stream, CommandType::SetBlendConstants, blend_constants); } void CommandRecord::set_depth_bounds(float min_depth_bounds, float max_depth_bounds) { // Write command parameters write(stream, CommandType::SetDepthBounds, min_depth_bounds, max_depth_bounds); } void CommandRecord::draw(uint32_t vertex_count, uint32_t instance_count, uint32_t first_vertex, uint32_t first_instance) { flush_pipeline_state(VK_PIPELINE_BIND_POINT_GRAPHICS); flush_descriptor_state(VK_PIPELINE_BIND_POINT_GRAPHICS); // Write command parameters write(stream, CommandType::Draw, vertex_count, instance_count, first_vertex, first_instance); } void CommandRecord::draw_indexed(uint32_t index_count, uint32_t instance_count, uint32_t first_index, int32_t vertex_offset, uint32_t first_instance) { flush_pipeline_state(VK_PIPELINE_BIND_POINT_GRAPHICS); flush_descriptor_state(VK_PIPELINE_BIND_POINT_GRAPHICS); // Write command parameters write(stream, CommandType::DrawIndexed, index_count, instance_count, first_index, vertex_offset, first_instance); } void CommandRecord::draw_indexed_indirect(const core::Buffer &buffer, VkDeviceSize offset, uint32_t draw_count, uint32_t stride) { flush_pipeline_state(VK_PIPELINE_BIND_POINT_GRAPHICS); flush_descriptor_state(VK_PIPELINE_BIND_POINT_GRAPHICS); // Write command parameters write(stream, CommandType::DrawIndexedIndirect, buffer.get_handle(), offset, draw_count, stride); } void CommandRecord::dispatch(uint32_t group_count_x, uint32_t group_count_y, uint32_t group_count_z) { flush_pipeline_state(VK_PIPELINE_BIND_POINT_COMPUTE); flush_descriptor_state(VK_PIPELINE_BIND_POINT_COMPUTE); // Write command parameters write(stream, CommandType::Dispatch, group_count_x, group_count_y, group_count_z); } void CommandRecord::dispatch_indirect(const core::Buffer &buffer, VkDeviceSize offset) { flush_pipeline_state(VK_PIPELINE_BIND_POINT_COMPUTE); flush_descriptor_state(VK_PIPELINE_BIND_POINT_COMPUTE); // Write command parameters write(stream, CommandType::DispatchIndirect, buffer.get_handle(), offset); } void CommandRecord::update_buffer(const core::Buffer &buffer, VkDeviceSize offset, const std::vector<uint8_t> &data) { // Write command parameters write(stream, CommandType::UpdateBuffer, buffer.get_handle(), offset, data); } void CommandRecord::blit_image(const core::Image &src_img, const core::Image &dst_img, const std::vector<VkImageBlit> &regions) { // Write command parameters write(stream, CommandType::BlitImage, src_img.get_handle(), dst_img.get_handle(), regions); } void CommandRecord::copy_image(const core::Image &src_img, const core::Image &dst_img, const std::vector<VkImageCopy> &regions) { // Write command parameters write(stream, CommandType::CopyImage, src_img.get_handle(), dst_img.get_handle(), regions); } void CommandRecord::copy_buffer_to_image(const core::Buffer &buffer, const core::Image &image, const std::vector<VkBufferImageCopy> &regions) { // Write command parameters write(stream, CommandType::CopyBufferToImage, buffer.get_handle(), image.get_handle(), regions); } void CommandRecord::image_memory_barrier(const core::ImageView &image_view, const ImageMemoryBarrier &memory_barrier) { // Write command parameters write(stream, CommandType::ImageMemoryBarrier, image_view.get_image().get_handle(), image_view.get_subresource_range(), memory_barrier); } void CommandRecord::buffer_memory_barrier(const core::Buffer &buffer, VkDeviceSize offset, VkDeviceSize size, const BufferMemoryBarrier &memory_barrier) { // Write command parameters write(stream, CommandType::BufferMemoryBarrier, buffer.get_handle(), offset, size, memory_barrier); } void CommandRecord::flush_pipeline_state(VkPipelineBindPoint pipeline_bind_point) { // Create a new pipeline in the command stream only if the graphics state changed if (!pipeline_state.is_dirty()) { return; } // Clear dirty bit for graphics state pipeline_state.clear_dirty(); if (pipeline_bind_point == VK_PIPELINE_BIND_POINT_GRAPHICS) { const PipelineLayout &pipeline_layout = pipeline_state.get_pipeline_layout(); SubpassDesc &subpass = render_pass_bindings.back().subpasses.back(); // Add graphics state to the current subpass subpass.pipeline_descs.push_back({stream.tellp(), pipeline_state}); } else if (pipeline_bind_point == VK_PIPELINE_BIND_POINT_COMPUTE) { auto &pipeline = device.get_resource_cache().request_compute_pipeline(pipeline_state); pipeline_bindings.push_back({stream.tellp(), pipeline_bind_point, pipeline}); } else { throw "Only graphics and compute pipeline bind points are supported now"; } } void CommandRecord::flush_descriptor_state(VkPipelineBindPoint pipeline_bind_point) { PipelineLayout &pipeline_layout = const_cast<PipelineLayout &>(pipeline_state.get_pipeline_layout()); const auto &set_bindings = pipeline_layout.get_bindings(); std::unordered_set<uint32_t> update_sets; // Iterate over pipeline layout sets for (auto &set_it : set_bindings) { auto descriptor_set_layout_it = descriptor_set_layout_state.find(set_it.first); // Check if set was bound before if (descriptor_set_layout_it != descriptor_set_layout_state.end()) { // Add set to later update it if is different from the current pipeline layout's set if (descriptor_set_layout_it->second->get_handle() != pipeline_layout.get_set_layout(set_it.first).get_handle()) { update_sets.emplace(set_it.first); } } } // Remove bound descriptor set layouts which don't exists in the pipeline layout for (auto set_it = descriptor_set_layout_state.begin(); set_it != descriptor_set_layout_state.end();) { if (!pipeline_layout.has_set_layout(set_it->first)) { set_it = descriptor_set_layout_state.erase(set_it); } else { ++set_it; } } // Check if descriptor set needs to be created if (resource_binding_state.is_dirty() || !update_sets.empty()) { // Clear dirty bit flag resource_binding_state.clear_dirty(); // Iterate over all set bindings for (auto &set_it : resource_binding_state.get_set_bindings()) { // Skip if set bindings don't have changes if (!set_it.second.is_dirty() && (update_sets.find(set_it.first) == update_sets.end())) { continue; } // Clear dirty flag for binding set resource_binding_state.clear_dirty(set_it.first); // Skip set layout if it doesn't exists if (!pipeline_layout.has_set_layout(set_it.first)) { continue; } DescriptorSetLayout &descriptor_set_layout = pipeline_layout.get_set_layout(set_it.first); // Make descriptor set layout bound for current set descriptor_set_layout_state[set_it.first] = &descriptor_set_layout; BindingMap<VkDescriptorBufferInfo> buffer_infos; BindingMap<VkDescriptorImageInfo> image_infos; std::vector<uint32_t> dynamic_offsets; // Iterate over all resource bindings for (auto &binding_it : set_it.second.get_resource_bindings()) { auto binding_index = binding_it.first; auto &binding_resources = binding_it.second; VkDescriptorSetLayoutBinding binding_info; // Check if binding exists in the pipeline layout if (!descriptor_set_layout.get_layout_binding(binding_index, binding_info)) { continue; } // Iterate over all binding resources for (auto &element_it : binding_resources) { auto arrayElement = element_it.first; auto &resource_info = element_it.second; // Get buffer info if (resource_info.is_buffer() && is_buffer_descriptor_type(binding_info.descriptorType)) { VkDescriptorBufferInfo buffer_info = resource_info.get_buffer_info(); if (is_dynamic_buffer_descriptor_type(binding_info.descriptorType)) { dynamic_offsets.push_back(to_u32(buffer_info.offset)); buffer_info.offset = 0; } buffer_infos[binding_index][arrayElement] = buffer_info; } // Get image info else if (resource_info.is_image_only() || resource_info.is_sampler_only() || resource_info.is_image_sampler()) { VkDescriptorImageInfo image_info = resource_info.get_image_info(); if (resource_info.is_image_only() || resource_info.is_image_sampler()) { const vkb::core::ImageView &image_view = resource_info.get_image_view(); // Add iamge layout info based on descriptor type switch (binding_info.descriptorType) { case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: if (is_depth_stencil_format(image_view.get_format())) { image_info.imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; } else { image_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; } break; case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: image_info.imageLayout = VK_IMAGE_LAYOUT_GENERAL; break; default: continue; } } image_infos[binding_index][arrayElement] = std::move(image_info); } } } auto &descriptor_set = device.get_resource_cache().request_descriptor_set(descriptor_set_layout, buffer_infos, image_infos); descriptor_set_bindings.push_back({stream.tellp(), pipeline_bind_point, pipeline_layout, set_it.first, descriptor_set, dynamic_offsets}); } } } } // namespace vkb
34.125839
182
0.77521
ohmaya
4da086a38fe7ba3b9a7d38f3756e6dc737eb38eb
14,663
cpp
C++
code/src/rflib/core/RandomForest.cpp
pkainz/MICCAI2015
933e9e52d244ad1179713fe2f1dbb749d9e1f8d5
[ "Apache-2.0" ]
23
2015-12-14T06:06:45.000Z
2022-03-25T10:51:42.000Z
code/src/rflib/core/RandomForest.cpp
pkainz/MICCAI2015
933e9e52d244ad1179713fe2f1dbb749d9e1f8d5
[ "Apache-2.0" ]
3
2016-08-18T13:16:30.000Z
2017-04-01T15:04:00.000Z
code/src/rflib/core/RandomForest.cpp
pkainz/MICCAI2015
933e9e52d244ad1179713fe2f1dbb749d9e1f8d5
[ "Apache-2.0" ]
8
2015-08-18T10:31:06.000Z
2020-12-30T13:55:01.000Z
/* * RandomForest.cpp * * Author: Samuel Schulter, Paul Wohlhart, Christian Leistner, Amir Saffari, Peter M. Roth, Horst Bischof * Institution: Graz, University of Technology, Austria * */ #ifndef RANDOMFOREST_CPP_ #define RANDOMFOREST_CPP_ #include "RandomForest.h" template<typename Sample, typename Label, typename SplitFunction, typename SplitEvaluator, typename LeafNodeStatistics, typename AppContext> RandomForest<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>::RandomForest(RFCoreParameters* hpin, AppContext* appcontextin) : m_hp(hpin), m_appcontext(appcontextin) { } template<typename Sample, typename Label, typename SplitFunction, typename SplitEvaluator, typename LeafNodeStatistics, typename AppContext> RandomForest<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>::~RandomForest() { // Free the trees for (int i = 0; i < m_trees.size(); i++) delete(this->m_trees[i]); } template<typename Sample, typename Label, typename SplitFunction, typename SplitEvaluator, typename LeafNodeStatistics, typename AppContext> void RandomForest<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>::Train(DataSet<Sample, Label>& dataset) { // This is the standard random forest training procedure ... vector<DataSet<Sample, Label> > inbag_dataset(m_hp->m_num_trees), outbag_dataset(m_hp->m_num_trees); this->BaggingForTrees(dataset, inbag_dataset, outbag_dataset); // Train the trees m_trees.resize(m_hp->m_num_trees); for (int t = 0; t < m_hp->m_num_trees; t++) { m_trees[t] = new RandomTree<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>(m_hp, m_appcontext); m_trees[t]->Init(inbag_dataset[t]); } for (unsigned int d = 0; d < m_hp->m_max_tree_depth; d++) { int num_nodes_left = 0; for (int t = 0; t < m_hp->m_num_trees; t++) num_nodes_left += m_trees[t]->GetTrainingQueueSize(); if (!m_hp->m_quiet) std::cout << "RF: training depth " << d << " of the forest -> " << num_nodes_left << " nodes left for splitting" << std::endl; // train the trees #pragma omp parallel for for (int t = 0; t < m_hp->m_num_trees; t++) m_trees[t]->Train(d); } if (m_hp->m_do_tree_refinement) { #pragma omp parallel for for (int t = 0; t < m_hp->m_num_trees; t++) m_trees[t]->UpdateLeafStatistics(outbag_dataset[t]); } } template<typename Sample, typename Label, typename SplitFunction, typename SplitEvaluator, typename LeafNodeStatistics, typename AppContext> vector<vector<Node<Sample, Label, SplitFunction, LeafNodeStatistics, AppContext>*> > RandomForest<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>::Test(DataSet<Sample, Label>& dataset) { return this->Test(dataset, (int)this->m_trees.size()); } template<typename Sample, typename Label, typename SplitFunction, typename SplitEvaluator, typename LeafNodeStatistics, typename AppContext> vector<vector<Node<Sample, Label, SplitFunction, LeafNodeStatistics, AppContext>* > > RandomForest<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>::Test(DataSet<Sample, Label>& dataset, int num_trees_to_test) { if (num_trees_to_test < 1 || num_trees_to_test > (int)m_trees.size()) num_trees_to_test = (int)m_trees.size(); vector<Node<Sample, Label, SplitFunction, LeafNodeStatistics, AppContext>* > tmp(num_trees_to_test); vector<vector<Node<Sample, Label, SplitFunction, LeafNodeStatistics, AppContext>* > > resulting_leafnodes((int)dataset.size(), tmp); #pragma omp parallel for for (int t = 0; t < num_trees_to_test; t++) { for (int s = 0; s < (int)dataset.size(); s++) { resulting_leafnodes[s][t] = m_trees[t]->Test(dataset[s]); } } return resulting_leafnodes; } template<typename Sample, typename Label, typename SplitFunction, typename SplitEvaluator, typename LeafNodeStatistics, typename AppContext> void RandomForest<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>::Test(LabelledSample<Sample, Label>* sample, std::vector<Node<Sample, Label, SplitFunction, LeafNodeStatistics, AppContext>* >& resulting_leafnodes) { resulting_leafnodes.resize(m_trees.size()); for (size_t t = 0; t < m_trees.size(); t++) resulting_leafnodes[t] = m_trees[t]->Test(sample); } template<typename Sample, typename Label, typename SplitFunction, typename SplitEvaluator, typename LeafNodeStatistics, typename AppContext> void RandomForest<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>::TestTree(LabelledSample<Sample, Label>* sample, std::vector<Node<Sample, Label, SplitFunction, LeafNodeStatistics, AppContext>* >& resulting_leafnodes, int tree_id) { resulting_leafnodes.resize(1); resulting_leafnodes[0] = m_trees[tree_id]->Test(sample); } template<typename Sample, typename Label, typename SplitFunction, typename SplitEvaluator, typename LeafNodeStatistics, typename AppContext> std::vector<LeafNodeStatistics> RandomForest<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>::TestAndAverage(DataSet<Sample, Label>& dataset) { vector<vector<Node<Sample, Label, SplitFunction, LeafNodeStatistics, AppContext>* > > leafnodes = this->Test(dataset); vector<LeafNodeStatistics> ret_stats(dataset.size(), this->m_appcontext); #pragma omp parallel for for (size_t s = 0; s < dataset.size(); s++) { vector<LeafNodeStatistics*> tmp_stats(leafnodes[s].size()); for (size_t t = 0; t < leafnodes[s].size(); t++) { tmp_stats[t] = leafnodes[s][t]->m_leafstats; } ret_stats[s] = LeafNodeStatistics::Average(tmp_stats, this->m_appcontext); } return ret_stats; } template<typename Sample, typename Label, typename SplitFunction, typename SplitEvaluator, typename LeafNodeStatistics, typename AppContext> LeafNodeStatistics RandomForest<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>::TestAndAverage(LabelledSample<Sample, Label>* sample) { vector<Node<Sample, Label, SplitFunction, LeafNodeStatistics, AppContext>* > leafnodes; this->Test(sample, leafnodes); std::vector<LeafNodeStatistics*> tmp_stats(leafnodes.size()); for (size_t t = 0; t < leafnodes.size(); t++) tmp_stats[t] = leafnodes[t]->m_leafstats; return LeafNodeStatistics::Average(tmp_stats, this->m_appcontext); } template<typename Sample, typename Label, typename SplitFunction, typename SplitEvaluator, typename LeafNodeStatistics, typename AppContext> void RandomForest<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>::DenormalizeTargetVariables(Eigen::VectorXd mean, Eigen::VectorXd std) { // get all leaf nodes vector<vector<Node<Sample, Label, SplitFunction, LeafNodeStatistics, AppContext>* > > leafs; leafs = this->GetAllLeafNodes(); // call DenormalizeTargetVariables method in each of the leafnodes-statistics for (size_t t = 0; t < leafs.size(); t++) { for (size_t i = 0; i < leafs[t].size(); i++) { leafs[t][i]->m_leafstats->DenormalizeTargetVariables(mean, std); } } } template<typename Sample, typename Label, typename SplitFunction, typename SplitEvaluator, typename LeafNodeStatistics, typename AppContext> void RandomForest<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>::DenormalizeTargetVariables(std::vector<Eigen::VectorXd> mean, std::vector<Eigen::VectorXd> std) { // get all leaf nodes vector<vector<Node<Sample, Label, SplitFunction, LeafNodeStatistics, AppContext>* > > leafs; leafs = this->GetAllLeafNodes(); // call DenormalizeTargetVariables method in each of the leafnodes-statistics for (size_t t = 0; t < leafs.size(); t++) { for (size_t i = 0; i < leafs[t].size(); i++) { leafs[t][i]->m_leafstats->DenormalizeTargetVariables(mean, std); } } } template<typename Sample, typename Label, typename SplitFunction, typename SplitEvaluator, typename LeafNodeStatistics, typename AppContext> vector<vector<Node<Sample, Label, SplitFunction, LeafNodeStatistics, AppContext>* > > RandomForest<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>::GetAllInternalNodes() { std::vector<std::vector<Node<Sample, Label, SplitFunction, LeafNodeStatistics, AppContext>* > > ret(this->m_trees.size()); for (size_t t = 0; t < this->m_trees.size(); t++) { ret[t] = this->m_trees[t]->GetAllInternalNodes(); } return ret; } template<typename Sample, typename Label, typename SplitFunction, typename SplitEvaluator, typename LeafNodeStatistics, typename AppContext> vector<vector<Node<Sample, Label, SplitFunction, LeafNodeStatistics, AppContext>* > > RandomForest<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>::GetAllLeafNodes() { std::vector<std::vector<Node<Sample, Label, SplitFunction, LeafNodeStatistics, AppContext>* > > ret(this->m_trees.size()); for (size_t t = 0; t < this->m_trees.size(); t++) { ret[t] = this->m_trees[t]->GetAllLeafNodes(); } return ret; } template<typename Sample, typename Label, typename SplitFunction, typename SplitEvaluator, typename LeafNodeStatistics, typename AppContext> void RandomForest<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>::Save(std::string savepath, int t_offset) { // This function should be rather called "SaveTrees", as no information on the complete forest is stored // this has the benefits that one can train 100 trees, but then use only a subset for testing, if desired // e.g., for analysis of the parameter #trees // check if storage folder exists. If not, try to create the folder. struct stat info; if (stat(savepath.c_str(), &info) != 0) { int status = mkdir(savepath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (status == -1) { std::cout << "Could not create the folder to store trees" << std::endl; throw std::runtime_error("Could not create savepath"); } } else if (info.st_mode & S_IFDIR) { // everything is ok } else { std::cout << savepath << " is not a folder" << std::endl; throw std::runtime_error("not a folder"); } // iterate over all trees for (int t = 0; t < m_trees.size(); t++) { std::stringstream tree_savefile_stream; tree_savefile_stream << savepath << "tree_" << t + t_offset << ".txt"; std::string tree_savefile = tree_savefile_stream.str(); std::ofstream out(tree_savefile.c_str(), ios::binary); // TODO: we could try to write a real binary file with out.write(...,...). Maybe the files become smaller m_trees[t]->Save(out); out.flush(); out.close(); } } /** * Loading a random forest from a set of .txt files stored in a folder. The number of trees loaded depends * on the number of trees defined in the config file. Each tree has to be stored in a separate .txt file * named "tree_X.txt", where X goes from to 0 to #trees-1. One can also use an offset value to start from * any tree > 0. * * @params[in] loadpath path to the folder the trees are stored * @params[in] t_offset the offset of the trees to start loading */ template<typename Sample, typename Label, typename SplitFunction, typename SplitEvaluator, typename LeafNodeStatistics, typename AppContext> void RandomForest<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>::Load(std::string loadpath, int t_offset) { m_trees.resize(m_hp->m_num_trees); for (int t = 0; t < m_hp->m_num_trees; t++) { // create a new tree m_trees[t] = new RandomTree<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>(m_hp, m_appcontext); // load the tree std::stringstream tree_loadfile_stream; tree_loadfile_stream << loadpath << "tree_" << t + t_offset << ".txt"; std::string tree_loadfile = tree_loadfile_stream.str(); std::ifstream in(tree_loadfile.c_str(), ios::in); m_trees[t]->Load(in); in.close(); } } // ############### PRIVATE METHODS ####################### template<typename Sample, typename Label, typename SplitFunction, typename SplitEvaluator, typename LeafNodeStatistics, typename AppContext> void RandomForest<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>::BaggingForTrees(DataSet<Sample, Label>& dataset_full, vector<DataSet<Sample, Label> >& dataset_inbag, vector<DataSet<Sample, Label> >& dataset_outbag) { if ((int)dataset_inbag.size() != m_hp->m_num_trees) dataset_inbag.resize(m_hp->m_num_trees); if ((int)dataset_outbag.size() != m_hp->m_num_trees) dataset_outbag.resize(m_hp->m_num_trees); size_t fixed_n; vector<int> rand_inds; for (unsigned int t = 0; t < m_hp->m_num_trees; t++) { DataSet<Sample, Label> temp1, temp2; switch (m_hp->m_bagging_method) { case TREE_BAGGING_TYPE::NONE: dataset_inbag[t] = dataset_full; // no out-of-bag samples break; case TREE_BAGGING_TYPE::SUBSAMPLE_WITH_REPLACEMENT: this->SubsampleWithReplacement(dataset_full, temp1, temp2); dataset_inbag[t] = temp1; dataset_outbag[t] = temp2; break; case TREE_BAGGING_TYPE::FIXED_RANDOM_SUBSET: fixed_n = min((size_t)3000, dataset_full.size()); rand_inds = randPermSTL((int)dataset_full.size()); dataset_inbag[t].Resize(fixed_n); for (size_t i = 0; i < fixed_n; i++) dataset_inbag[t].SetLabelledSample(i, dataset_full[rand_inds[i]]); // no out-of-bag samples break; default: throw std::runtime_error("RandomForest: wrong sampling method defined!"); break; } } } template<typename Sample, typename Label, typename SplitFunction, typename SplitEvaluator, typename LeafNodeStatistics, typename AppContext> void RandomForest<Sample, Label, SplitFunction, SplitEvaluator, LeafNodeStatistics, AppContext>::SubsampleWithReplacement(DataSet<Sample, Label>& dataset_full, DataSet<Sample, Label>& dataset_inbag, DataSet<Sample, Label>& dataset_outbag) { int num_total_samples = (int)dataset_full.size(); vector<int> inIndex(num_total_samples, 0); vector<int> usedSamples(num_total_samples, 0); for (int n = 0; n < num_total_samples; n++) { // get a random index inIndex[n] = (int)floor(num_total_samples * randDouble()); if (usedSamples[inIndex[n]] == 0) { dataset_inbag.AddLabelledSample(dataset_full[(unsigned int)inIndex[n]]); usedSamples[inIndex[n]] = 1; } } // set the outbag samples for (int n = 0; n < num_total_samples; n++) { if (usedSamples[n] == 0) { dataset_outbag.AddLabelledSample(dataset_full[(unsigned int)n]); } } } #endif /* RANDOMFOREST_CPP_ */
40.617729
256
0.730683
pkainz
4da0f656b1d03fffcd2893f6b950eb3d484b90e2
20,059
cpp
C++
src/libcore/src/ccm/util/LinkedList.cpp
sparkoss/ccm
9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d
[ "Apache-2.0" ]
6
2018-05-08T10:08:21.000Z
2021-11-13T13:22:58.000Z
src/libcore/src/ccm/util/LinkedList.cpp
sparkoss/ccm
9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d
[ "Apache-2.0" ]
1
2018-05-08T10:20:17.000Z
2018-07-23T05:19:19.000Z
src/libcore/src/ccm/util/LinkedList.cpp
sparkoss/ccm
9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d
[ "Apache-2.0" ]
4
2018-03-13T06:21:11.000Z
2021-06-19T02:48:07.000Z
//========================================================================= // Copyright (C) 2018 The C++ Component Model(CCM) Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "ccm/util/LinkedList.h" #include <ccmlogger.h> using ccm::core::E_INDEX_OUT_OF_BOUNDS_EXCEPTION; using ccm::core::E_ILLEGAL_STATE_EXCEPTION; using ccm::core::ICloneable; using ccm::core::IID_ICloneable; using ccm::io::IID_ISerializable; namespace ccm { namespace util { CCM_INTERFACE_IMPL_5(LinkedList, AbstractSequentialList, ILinkedList, IDeque, IQueue, ICloneable, ISerializable); ECode LinkedList::Constructor() { return AbstractSequentialList::Constructor(); } ECode LinkedList::Constructor( /* [in] */ ICollection* c) { Constructor(); return AddAll(c); } void LinkedList::LinkFirst( /* [in] */ IInterface* e) { AutoPtr<Node> f = mFirst; AutoPtr<Node> newNode = new Node(nullptr, e, f); mFirst = std::move(newNode); if (f == nullptr) { mLast = mFirst; } else { f->mPrev = mFirst; } mSize++; mModCount++; } void LinkedList::LinkLast( /* [in] */ IInterface* e) { AutoPtr<Node> l = mLast; AutoPtr<Node> newNode = new Node(l, e, nullptr); mLast = std::move(newNode); if (l == nullptr) { mFirst = mLast; } else { l->mNext = mLast; } mSize++; mModCount++; } void LinkedList::LinkBefore( /* [in] */ IInterface* e, /* [in] */ Node* succ) { AutoPtr<Node> pred = succ->mPrev; AutoPtr<Node> newNode = new Node(pred, e, succ); succ->mPrev = newNode; if (pred = nullptr) { mFirst = std::move(newNode); } else { pred->mNext = std::move(newNode); } mSize++; mModCount++; } AutoPtr<IInterface> LinkedList::UnlinkFirst( /* [in] */ Node* f) { AutoPtr<IInterface> element = std::move(f->mItem); AutoPtr<Node> next = std::move(f->mNext); f->mItem = nullptr; f->mNext = nullptr; mFirst = std::move(next); if (mFirst == nullptr) { mLast = nullptr; } else { mFirst->mPrev = nullptr; } mSize--; mModCount++; return element; } AutoPtr<IInterface> LinkedList::UnlinkLast( /* [in] */ Node* l) { AutoPtr<IInterface> element = std::move(l->mItem); AutoPtr<Node> prev = l->mPrev; l->mItem = nullptr; l->mPrev = nullptr; mLast = std::move(prev); if (mLast == nullptr) { mFirst = nullptr; } else { mLast->mNext = nullptr; } mSize--; mModCount++; return element; } AutoPtr<IInterface> LinkedList::Unlink( /* [in] */ Node* x) { AutoPtr<IInterface> element = std::move(x->mItem); AutoPtr<Node> next = std::move(x->mNext); Node* prev = x->mPrev; if (prev == nullptr) { mFirst = next; } else { prev->mNext = next; x->mPrev = nullptr; } if (next == nullptr) { mLast = prev; } else { next->mPrev = prev; x->mNext = nullptr; } x->mItem = nullptr; mSize--; mModCount++; return element; } ECode LinkedList::GetFirst( /* [out] */ IInterface** e) { VALIDATE_NOT_NULL(e); if (mFirst == nullptr) { return E_NO_SUCH_ELEMENT_EXCEPTION; } *e = mFirst->mItem; REFCOUNT_ADD(*e); return NOERROR; } ECode LinkedList::GetLast( /* [out] */ IInterface** e) { VALIDATE_NOT_NULL(e); if (mLast == nullptr) { return E_NO_SUCH_ELEMENT_EXCEPTION; } *e = mLast->mItem; REFCOUNT_ADD(*e); return NOERROR; } ECode LinkedList::RemoveFirst( /* [out] */ IInterface** e) { if (mFirst == nullptr) { return E_NO_SUCH_ELEMENT_EXCEPTION; } AutoPtr<IInterface> element = UnlinkFirst(mFirst); if (e != nullptr) { element.MoveTo(e); } return NOERROR; } ECode LinkedList::RemoveLast( /* [out] */ IInterface** e) { if (mLast == nullptr) { return E_NO_SUCH_ELEMENT_EXCEPTION; } AutoPtr<IInterface> element = UnlinkLast(mLast); if (e != nullptr) { element.MoveTo(e); } return NOERROR; } ECode LinkedList::AddFirst( /* [in] */ IInterface* e) { LinkFirst(e); return NOERROR; } ECode LinkedList::AddLast( /* [in] */ IInterface* e) { LinkLast(e); return NOERROR; } ECode LinkedList::Contains( /* [in] */ IInterface* obj, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); Integer idx; IndexOf(obj, &idx); *result = idx != -1; return NOERROR; } ECode LinkedList::GetSize( /* [out] */ Integer* size) { VALIDATE_NOT_NULL(size); *size = mSize; return NOERROR; } ECode LinkedList::Add( /* [in] */ IInterface* e, /* [out] */ Boolean* changed) { LinkLast(e); if (changed != nullptr) { *changed = true; } return NOERROR; } ECode LinkedList::Remove( /* [in] */ IInterface* obj, /* [out] */ Boolean* result) { if (obj == nullptr) { for (AutoPtr<Node> x = mFirst; x != nullptr; x = x->mNext) { if (x->mItem == nullptr) { Unlink(x); if (result != nullptr) { *result = true; } return NOERROR; } } } else { for (AutoPtr<Node> x = mFirst; x != nullptr; x = x->mNext) { if (Object::Equals(obj, x->mItem)) { Unlink(x); if (result != nullptr) { *result = true; } return NOERROR; } } } if (result != nullptr) { *result = false; } return NOERROR; } ECode LinkedList::AddAll( /* [in] */ ICollection* c, /* [out] */ Boolean* changed) { return AddAll(mSize, c, changed); } ECode LinkedList::AddAll( /* [in] */ Integer index, /* [in] */ ICollection* c, /* [out] */ Boolean* result) { FAIL_RETURN(CheckPositionIndex(index)); Array<IInterface*> a; c->ToArray(&a); Integer numNew = a.GetLength(); if (numNew == 0) { if (result != nullptr) { *result = false; } return NOERROR; } AutoPtr<Node> pred, succ; if (index == mSize) { pred = mLast; } else { succ = GetNode(index); pred = succ->mPrev; } for (IInterface* o : a) { AutoPtr<Node> newNode = new Node(pred, o, nullptr); if (pred == nullptr) { mFirst = newNode; } else { pred->mNext = newNode; } pred = std::move(newNode); } if (succ == nullptr) { mLast = pred; } else { pred->mNext = succ; succ->mPrev = pred; } mSize += numNew; mModCount++; if (result != nullptr) { *result = true; } return NOERROR; } ECode LinkedList::Clear() { for (AutoPtr<Node> x = mFirst; x != nullptr; ) { AutoPtr<Node> next = std::move(x->mNext); x->mItem = nullptr; x->mNext = nullptr; x->mPrev = nullptr; x = std::move(next); } mFirst = nullptr; mLast = nullptr; mSize = 0; mModCount++; return NOERROR; } ECode LinkedList::Get( /* [in] */ Integer index, /* [out] */ IInterface** obj) { VALIDATE_NOT_NULL(obj); FAIL_RETURN(CheckElementIndex(index)); *obj = GetNode(index)->mItem; REFCOUNT_ADD(*obj); return NOERROR; } ECode LinkedList::Set( /* [in] */ Integer index, /* [in] */ IInterface* obj, /* [out] */ IInterface** prevObj) { FAIL_RETURN(CheckElementIndex(index)); AutoPtr<Node> x = GetNode(index); if (prevObj != nullptr) { x->mItem.MoveTo(prevObj); } x->mItem = obj; return NOERROR; } ECode LinkedList::Add( /* [in] */ Integer index, /* [in] */ IInterface* obj) { FAIL_RETURN(CheckPositionIndex(index)); if (index == mSize) { LinkLast(obj); } else { LinkBefore(obj, GetNode(index)); } return NOERROR; } ECode LinkedList::Remove( /* [in] */ Integer index, /* [out] */ IInterface** obj) { FAIL_RETURN(CheckElementIndex(index)); AutoPtr<IInterface> element = Unlink(GetNode(index)); if (obj != nullptr) { element.MoveTo(obj); } return NOERROR; } Boolean LinkedList::IsElementIndex( /* [in] */ Integer index) { return index >= 0 && index < mSize; } Boolean LinkedList::IsPositionIndex( /* [in] */ Integer index) { return index >= 0 && index <= mSize; } String LinkedList::OutOfBoundsMsg( /* [in] */ Integer index) { return String::Format("Index: %d, Size: %d\n", index, mSize); } ECode LinkedList::CheckElementIndex( /* [in] */ Integer index) { if (!IsElementIndex(index)) { Logger::E("LinkedList", OutOfBoundsMsg(index).string()); return E_INDEX_OUT_OF_BOUNDS_EXCEPTION; } return NOERROR; } ECode LinkedList::CheckPositionIndex( /* [in] */ Integer index) { if (!IsPositionIndex(index)) { Logger::E("LinkedList", OutOfBoundsMsg(index).string()); return E_INDEX_OUT_OF_BOUNDS_EXCEPTION; } return NOERROR; } AutoPtr<LinkedList::Node> LinkedList::GetNode( /* [in] */ Integer index) { if (index < (mSize >> 1)) { AutoPtr<Node> x = mFirst; for (Integer i = 0; i < index; i++) { x = x->mNext; } return x; } else { AutoPtr<Node> x = mLast; for (Integer i = mSize - 1; i > index; i--) { x = x->mPrev; } return x; } } ECode LinkedList::IndexOf( /* [in] */ IInterface* obj, /* [out] */ Integer* index) { VALIDATE_NOT_NULL(index); Integer idx = 0; if (obj == nullptr) { for (AutoPtr<Node> x = mFirst; x != nullptr; x = x->mNext) { if (x->mItem == nullptr) { *index = idx; return NOERROR; } idx++; } } else { for (AutoPtr<Node> x = mFirst; x != nullptr; x = x->mNext) { if (Object::Equals(obj, x->mItem)) { *index = idx; return NOERROR; } idx++; } } *index = -1; return NOERROR; } ECode LinkedList::LastIndexOf( /* [in] */ IInterface* obj, /* [out] */ Integer* index) { VALIDATE_NOT_NULL(index); Integer idx = mSize; if (obj == nullptr) { for (AutoPtr<Node> x = mLast; x != nullptr; x = x->mPrev) { idx--; if (x->mItem == nullptr) { *index = idx; return NOERROR; } } } else { for (AutoPtr<Node> x = mLast; x != nullptr; x = x->mPrev) { idx--; if (Object::Equals(obj, x->mItem)) { *index = idx; return NOERROR; } } } *index = -1; return NOERROR; } ECode LinkedList::Peek( /* [out] */ IInterface** e) { VALIDATE_NOT_NULL(e); *e = (mFirst == nullptr) ? nullptr : mFirst->mItem; REFCOUNT_ADD(*e); return NOERROR; } ECode LinkedList::Element( /* [out] */ IInterface** e) { VALIDATE_NOT_NULL(e); return GetFirst(e); } ECode LinkedList::Poll( /* [out] */ IInterface** e) { VALIDATE_NOT_NULL(e); if (mFirst == nullptr) { *e = nullptr; } else { UnlinkFirst(mFirst).MoveTo(e); } return NOERROR; } ECode LinkedList::Remove( /* [out] */ IInterface** e) { return RemoveFirst(e); } ECode LinkedList::Offer( /* [in] */ IInterface* e, /* [out] */ Boolean* changed) { return Add(e, changed); } ECode LinkedList::OfferFirst( /* [in] */ IInterface* e, /* [out] */ Boolean* changed) { AddFirst(e); if (changed != nullptr) { *changed = true; } return NOERROR; } ECode LinkedList::OfferLast( /* [in] */ IInterface* e, /* [out] */ Boolean* changed) { AddLast(e); if (changed != nullptr) { *changed = true; } return NOERROR; } ECode LinkedList::PeekFirst( /* [out] */ IInterface** e) { VALIDATE_NOT_NULL(e); *e = (mFirst == nullptr) ? nullptr : mFirst->mItem; REFCOUNT_ADD(*e); return NOERROR; } ECode LinkedList::PeekLast( /* [out] */ IInterface** e) { VALIDATE_NOT_NULL(e); *e = (mLast == nullptr) ? nullptr : mLast->mItem; REFCOUNT_ADD(*e); return NOERROR; } ECode LinkedList::PollFirst( /* [out] */ IInterface** e) { VALIDATE_NOT_NULL(e); if (mFirst == nullptr) { *e = nullptr; } else { UnlinkFirst(mFirst).MoveTo(e); } return NOERROR; } ECode LinkedList::PollLast( /* [out] */ IInterface** e) { VALIDATE_NOT_NULL(e); if (mLast == nullptr) { *e = nullptr; } else { UnlinkLast(mLast).MoveTo(e); } return NOERROR; } ECode LinkedList::Push( /* [in] */ IInterface* e) { return AddFirst(e); } ECode LinkedList::Pop( /* [out] */ IInterface** e) { return RemoveFirst(e); } ECode LinkedList::RemoveFirstOccurrence( /* [in] */ IInterface* e, /* [out] */ Boolean* changed) { return Remove(e, changed); } ECode LinkedList::RemoveLastOccurrence( /* [in] */ IInterface* e, /* [out] */ Boolean* changed) { if (e == nullptr) { for (AutoPtr<Node> x = mLast; x != nullptr; x = x->mPrev) { if (x->mItem == nullptr) { Unlink(x); if (changed != nullptr) { *changed = true; } return NOERROR; } } } else { for (AutoPtr<Node> x = mLast; x != nullptr; x = x->mPrev) { if (Object::Equals(e, x->mItem)) { Unlink(x); if (changed != nullptr) { *changed = true; } return NOERROR; } } } if (changed != nullptr) { *changed = false; } return NOERROR; } ECode LinkedList::GetListIterator( /* [in] */ Integer index, /* [out] */ IListIterator** it) { VALIDATE_NOT_NULL(it); FAIL_RETURN(CheckPositionIndex(index)); *it = new ListItr(this, index); REFCOUNT_ADD(*it); return NOERROR; } ECode LinkedList::GetDescendingIterator( /* [out] */ IIterator** it) { VALIDATE_NOT_NULL(it); *it = new DescendingIterator(this); REFCOUNT_ADD(*it); return NOERROR; } ECode LinkedList::CloneImpl( /* [in] */ ILinkedList* newObj) { LinkedList* clone = (LinkedList*)newObj; clone->mFirst = nullptr; clone->mLast = nullptr; clone->mSize = 0; clone->mModCount = 0; for (AutoPtr<Node> x = mFirst; x != nullptr; x = x->mNext) { clone->Add(x->mItem); } return NOERROR; } ECode LinkedList::ToArray( /* [out, callee] */ Array<IInterface*>* objs) { VALIDATE_NOT_NULL(objs); Array<IInterface*> result(mSize); Integer i = 0; for (AutoPtr<Node> x = mFirst; x != nullptr; x = x->mNext) { result.Set(i++, x->mItem); } *objs = result; return NOERROR; } ECode LinkedList::ToArray( /* [in] */ const InterfaceID& iid, /* [out, callee] */ Array<IInterface*>* objs) { VALIDATE_NOT_NULL(objs); Array<IInterface*> result(mSize); Integer i = 0; for (AutoPtr<Node> x = mFirst; x != nullptr; x = x->mNext) { result.Set(i++, x->mItem->Probe(iid)); } *objs = result; return NOERROR; } ECode LinkedList::GetIterator( /* [out] */ IIterator** it) { return AbstractSequentialList::GetIterator(it); } //------------------------------------------------------------------------------------- CCM_INTERFACE_IMPL_2(LinkedList::ListItr, SyncObject, IListIterator, IIterator); LinkedList::ListItr::ListItr( /* [in] */ LinkedList* owner, /* [in] */ Integer index) : mNextIndex(index) , mExpectedModCount(owner->mModCount) , mOwner(owner) { if (index != mOwner->mSize) { mNext = mOwner->GetNode(index); } } ECode LinkedList::ListItr::HasNext( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = mNextIndex < mOwner->mSize; return NOERROR; } ECode LinkedList::ListItr::Next( /* [out] */ IInterface** object) { FAIL_RETURN(CheckForComodification()); Boolean hasNext; if (HasNext(&hasNext), !hasNext) { return E_NO_SUCH_ELEMENT_EXCEPTION; } mLastReturned = mNext; mNext = mNext->mNext; mNextIndex++; if (object != nullptr) { *object = mLastReturned->mItem; REFCOUNT_ADD(*object); } return NOERROR; } ECode LinkedList::ListItr::HasPrevious( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = mNextIndex > 0; return NOERROR; } ECode LinkedList::ListItr::Previous( /* [out] */ IInterface** object) { FAIL_RETURN(CheckForComodification()); Boolean hasPrevious; if (HasPrevious(&hasPrevious), !hasPrevious) { return E_NO_SUCH_ELEMENT_EXCEPTION; } mNext = (mNext == nullptr) ? mOwner->mLast.Get() : mNext->mPrev; mLastReturned = mNext; mNextIndex--; if (object != nullptr) { *object = mLastReturned->mItem; REFCOUNT_ADD(*object); } return NOERROR; } ECode LinkedList::ListItr::GetNextIndex( /* [out] */ Integer* index) { VALIDATE_NOT_NULL(index); *index = mNextIndex; return NOERROR; } ECode LinkedList::ListItr::GetPreviousIndex( /* [out] */ Integer* index) { VALIDATE_NOT_NULL(index); *index = mNextIndex - 1; return NOERROR; } ECode LinkedList::ListItr::Remove() { FAIL_RETURN(CheckForComodification()); if (mLastReturned == nullptr) { return E_ILLEGAL_STATE_EXCEPTION; } AutoPtr<Node> lastNext = mLastReturned->mNext; mOwner->Unlink(mLastReturned); if (mNext == mLastReturned) { mNext = lastNext; } else { mNextIndex--; } mLastReturned = nullptr; mExpectedModCount++; return NOERROR; } ECode LinkedList::ListItr::Set( /* [in] */ IInterface* object) { if (mLastReturned == nullptr) { return E_ILLEGAL_STATE_EXCEPTION; } FAIL_RETURN(CheckForComodification()); mLastReturned->mItem = object; return NOERROR; } ECode LinkedList::ListItr::Add( /* [in] */ IInterface* object) { FAIL_RETURN(CheckForComodification()); mLastReturned = nullptr; if (mNext == nullptr) { mOwner->LinkLast(object); } else { mOwner->LinkBefore(object, mNext); } mNextIndex++; mExpectedModCount++; return NOERROR; } ECode LinkedList::ListItr::CheckForComodification() { if (mOwner->mModCount != mExpectedModCount) { return E_CONCURRENT_MODIFICATION_EXCEPTION; } return NOERROR; } //------------------------------------------------------------------------------------- CCM_INTERFACE_IMPL_1(LinkedList::DescendingIterator, SyncObject, IIterator); LinkedList::DescendingIterator::DescendingIterator( /* [in] */ LinkedList* owner) { Integer index; owner->GetSize(&index); mItr = new ListItr(owner, index); } ECode LinkedList::DescendingIterator::HasNext( /* [out] */ Boolean* result) { return mItr->HasPrevious(result); } ECode LinkedList::DescendingIterator::Next( /* [out] */ IInterface** object) { return mItr->Previous(object); } ECode LinkedList::DescendingIterator::Remove() { return mItr->Remove(); } } }
21.136986
113
0.551024
sparkoss
4da1836999299dc5caf69c07d6dfa5d5f1db371c
54,881
cpp
C++
tests/unit/modules/solver/agent.cpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
43
2018-07-26T07:20:42.000Z
2022-03-02T10:23:12.000Z
tests/unit/modules/solver/agent.cpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
212
2018-09-21T10:44:07.000Z
2022-03-22T14:33:05.000Z
tests/unit/modules/solver/agent.cpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
16
2018-07-25T15:00:36.000Z
2022-03-22T14:19:46.000Z
#include "gtest/gtest.h" #include "korali.hpp" #include "modules/problem/reinforcementLearning/reinforcementLearning.hpp" #include "modules/problem/reinforcementLearning/continuous/continuous.hpp" #include "modules/problem/reinforcementLearning/discrete/discrete.hpp" #include "modules/solver/agent/continuous/VRACER/VRACER.hpp" #include "modules/solver/agent/discrete/dVRACER/dVRACER.hpp" #include "modules/conduit/sequential/sequential.hpp" namespace korali { namespace problem { extern Sample *__currentSample; extern size_t __envFunctionId; extern solver::Agent *_agent; extern Conduit* _conduit; extern cothread_t _envThread; extern size_t _launchId; extern void __environmentWrapper(); } } namespace { using namespace korali; using namespace korali::solver; using namespace korali::solver::agent; using namespace korali::solver::agent::continuous; using namespace korali::solver::agent::discrete; using namespace korali::problem; using namespace korali::problem::reinforcementLearning; using namespace korali::conduit; //////////////// Base Agent CLASS //////////////////////// TEST(a, baseAgent) { // Creating base experiment Experiment e; e._logger = new Logger("Detailed", stdout); auto& experimentJs = e._js.getJson(); experimentJs["Variables"][0]["Name"] = "X"; Variable v; e._variables.push_back(&v); // Creating optimizer configuration Json knlohmann::json agentJs; // Configuring Problem e["Problem"]["Type"] = "Reinforcement Learning / Continuous"; reinforcementLearning::Continuous* pC; knlohmann::json problemRefJs; problemRefJs["Type"] = "Reinforcement Learning / Continuous"; problemRefJs["Environment Function"] = [](Sample &s){}; e["Variables"][0]["Name"] = "State0"; e["Variables"][1]["Name"] = "Action0"; e["Variables"][1]["Type"] = "Action"; e["Variables"][1]["Initial Exploration Noise"] = 0.45; e["Variables"][1]["Lower Bound"] = 0.00; e["Variables"][1]["Upper Bound"] = 1.00; e["Solver"]["Type"] = "Agent / Continuous / VRACER"; Variable vState; vState._name = "State0"; vState._type = "State"; Variable vAction; vAction._name = "Action0"; vAction._type = "Action"; vAction._initialExplorationNoise = 0.45; vAction._lowerBound = 0.00; vAction._upperBound = 1.00; e._variables.push_back(&vState); e._variables.push_back(&vAction); ASSERT_NO_THROW(pC = dynamic_cast<reinforcementLearning::Continuous *>(Module::getModule(problemRefJs, &e))); // Defaults should be applied without a problem ASSERT_NO_THROW(pC->applyModuleDefaults(problemRefJs)); // Covering variable functions (no effect) ASSERT_NO_THROW(pC->applyVariableDefaults()); // Setting up problem correctly ASSERT_NO_THROW(pC->setConfiguration(problemRefJs)); // Intitialize problem e._problem = pC; ASSERT_NO_THROW(pC->initialize()); // Using a agent solver agentJs["Type"] = "Agent / Continuous / VRACER"; agentJs["Mode"] = "Training"; agentJs["Episodes Per Generation"] = 10; agentJs["Experiences Between Policy Updates"] = 1; agentJs["Discount Factor"] = 0.99; agentJs["Learning Rate"] = 0.0001; agentJs["Mini Batch"]["Size"] = 32; agentJs["Experience Replay"]["Start Size"] = 1000; agentJs["Experience Replay"]["Maximum Size"] = 10000; /// Configuring the neural network and its hidden layers agentJs["Neural Network"]["Engine"] = "OneDNN"; agentJs["Neural Network"]["Optimizer"] = "Adam"; agentJs["Neural Network"]["Hidden Layers"][0]["Type"] = "Layer/Linear"; agentJs["Neural Network"]["Hidden Layers"][0]["Output Channels"] = 16; // Creating module VRACER* a; ASSERT_NO_THROW(a = dynamic_cast<VRACER *>(Module::getModule(agentJs, &e))); // Defaults should be applied without a problem ASSERT_NO_THROW(a->applyModuleDefaults(agentJs)); // Covering variable functions (no effect) ASSERT_NO_THROW(a->applyVariableDefaults()); // Backup the correct base configuration auto baseOptJs = agentJs; auto baseExpJs = experimentJs; // Setting up optimizer correctly agentJs = baseOptJs; experimentJs = baseExpJs; ASSERT_NO_THROW(a->setConfiguration(agentJs)); // Running initial configuration correctly ASSERT_NO_THROW(a->initialize()); // Case with no ER size maximum a->_experienceReplayMaximumSize = 0; ASSERT_NO_THROW(a->initialize()); ASSERT_NE(a->_experienceReplayMaximumSize, 0); // Case with no ER size maximum a->_experienceReplayStartSize = 0; ASSERT_NO_THROW(a->initialize()); ASSERT_NE(a->_experienceReplayStartSize, 0); // Case Cutoff scale a->_experienceReplayOffPolicyCutoffScale = -1.0f; ASSERT_ANY_THROW(a->initialize()); a->_experienceReplayOffPolicyCutoffScale = 1.0f; // Case testing with testing best curPolicy empty a->_mode = "Testing"; a->_testingSampleIds = std::vector<size_t>(); ASSERT_ANY_THROW(a->initialize()); // No sample ids defined a->_testingSampleIds = std::vector<size_t>({1}); a->_trainingCurrentPolicy = std::vector<float>({1.0}); ASSERT_NO_THROW(a->initialize()); // Testing Process Episode corner cases knlohmann::json episode; episode["Environment Id"] = 0; episode["Experiences"][0]["State"] = std::vector<float>({0.0f}); episode["Experiences"][0]["Action"] = std::vector<float>({0.0f}); episode["Experiences"][0]["Reward"] = 1.0f; episode["Experiences"][0]["Termination"] = "Terminal"; episode["Experiences"][0]["Policy"]["State Value"] = 1.0; a->processEpisode(episode); // ASSERT_NO_THROW(a->processEpisode(episode)); // No state value provided error episode["Experiences"][0]["Policy"].erase("State Value"); ASSERT_ANY_THROW(a->processEpisode(episode)); episode["Experiences"][0]["Policy"]["State Value"] = 1.0; // Reward adjusted due to out of bounds action a->_rewardOutboundPenalizationEnabled = true; a->_rewardOutboundPenalizationFactor = 0.5f; episode["Experiences"][0]["Reward"] = 1.0f; episode["Experiences"][0]["Action"] = std::vector<float>({-1.0f}); a->_rewardVector.clear(); ASSERT_NO_THROW(a->processEpisode(episode)); ASSERT_EQ(a->_rewardVector[0], 0.5f); // Correct handling of truncated state episode["Experiences"][0]["Termination"] = "Truncated"; episode["Experiences"][0]["Truncated State"] = std::vector<float>({0.0f}); ASSERT_NO_THROW(a->processEpisode(episode)); // Correct handling of truncated state episode["Experiences"][0]["Termination"] = "Truncated"; episode["Experiences"][0]["Truncated State"] = std::vector<float>({std::numeric_limits<float>::infinity()}); ASSERT_ANY_THROW(a->processEpisode(episode)); episode["Experiences"][0]["Truncated State"] = std::vector<float>({0.0f}); // Check truncated state sequence for sequences > 1 episode["Experiences"][0]["Environment Id"] = 0; episode["Experiences"][0]["State"] = std::vector<float>({0.0f}); episode["Experiences"][0]["Action"] = std::vector<float>({0.0f}); episode["Experiences"][0]["Reward"] = 1.0f; episode["Experiences"][0]["Termination"] = "Non Terminal"; episode["Experiences"][0]["Policy"]["State Value"] = 1.0; episode["Experiences"][1]["Environment Id"] = 0; episode["Experiences"][1]["State"] = std::vector<float>({0.0f}); episode["Experiences"][1]["Action"] = std::vector<float>({0.0f}); episode["Experiences"][1]["Reward"] = 1.0f; episode["Experiences"][1]["Termination"] = "Non Terminal"; episode["Experiences"][1]["Policy"]["State Value"] = 1.0; episode["Experiences"][2]["Environment Id"] = 0; episode["Experiences"][2]["State"] = std::vector<float>({0.0f}); episode["Experiences"][2]["Action"] = std::vector<float>({0.0f}); episode["Experiences"][2]["Reward"] = 1.0f; episode["Experiences"][2]["Termination"] = "Truncated"; episode["Experiences"][2]["Policy"]["State Value"] = 1.0; episode["Experiences"][2]["Truncated State"] = std::vector<float>({0.0f}); ASSERT_NO_THROW(a->processEpisode(episode)); a->_timeSequenceLength = 2; ASSERT_NO_THROW(a->getTruncatedStateSequence(a->_terminationVector.size()-1)); // Triggering bad path in serialization routine e._fileOutputPath = "/dev/null/\%*Incorrect Path*"; ASSERT_ANY_THROW(a->serializeExperienceReplay()); ASSERT_ANY_THROW(a->deserializeExperienceReplay()); // Some specific printing cases a->_mode = "Training"; a->_maxEpisodes = 0; ASSERT_NO_THROW(a->printGenerationAfter()); a->_maxEpisodes = 1; ASSERT_NO_THROW(a->printGenerationAfter()); a->_maxExperiences = 0; ASSERT_NO_THROW(a->printGenerationAfter()); a->_maxExperiences = 1; ASSERT_NO_THROW(a->printGenerationAfter()); a->_maxPolicyUpdates = 0; ASSERT_NO_THROW(a->printGenerationAfter()); a->_maxPolicyUpdates = 1; ASSERT_NO_THROW(a->printGenerationAfter()); // Testing optional parameters agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Action Lower Bounds"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Action Lower Bounds"] = std::vector<float>({0.0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Action Upper Bounds"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Action Upper Bounds"] = std::vector<float>({0.0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Current Episode"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Current Episode"] = 1; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Reward History"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Reward History"] = std::vector<float>({1.0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Experience History"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Experience History"] = std::vector<float>({1}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Average Reward"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Average Reward"] = 1.0; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Last Reward"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Last Reward"] = 1.0; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Best Reward"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Best Reward"] = 1.0; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Best Episode Id"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Best Episode Id"] = 1; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Testing"]["Reward"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Testing"]["Reward"] = std::vector<float>({1.0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"]["Count"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"]["Count"] = 1; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"]["Ratio"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"]["Ratio"] = 1.0; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"]["Current Cutoff"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"]["Current Cutoff"] = 1.0; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Current Learning Rate"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Current Learning Rate"] = 1.0; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Policy Update Count"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Policy Update Count"] = 1; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Current Sample ID"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Current Sample ID"] = 1; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Count Per Environment"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Count Per Environment"] = std::vector<size_t>({1}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Count"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Count"] = 1; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Reward"]["Outbound Penalization"]["Count"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Reward"]["Outbound Penalization"]["Count"] = 1; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Reward"]["Rescaling"]["Sum Squared Rewards"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Reward"]["Rescaling"]["Sum Squared Rewards"] = std::vector<float>({1.0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Reward"]["Rescaling"]["Sigma"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Reward"]["Rescaling"]["Sigma"] = std::vector<float>({1.0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["State Rescaling"]["Means"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["State Rescaling"]["Means"] = std::vector<float>({1.0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["State Rescaling"]["Sigmas"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["State Rescaling"]["Sigmas"] = std::vector<float>({1.0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); // Testing mandatory parameters agentJs = baseOptJs; experimentJs = baseExpJs; agentJs.erase("Mode"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Mode"] = 1.0; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Mode"] = "Training"; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs.erase("Concurrent Environments"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Concurrent Environments"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Concurrent Environments"] = 1; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs.erase("Episodes Per Generation"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Episodes Per Generation"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Episodes Per Generation"] = 1; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Mini Batch"].erase("Size"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Mini Batch"]["Size"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Mini Batch"]["Size"] = 1; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Mini Batch"].erase("Strategy"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Mini Batch"]["Strategy"] = 1; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Mini Batch"]["Strategy"] = "Unknown"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Mini Batch"]["Strategy"] = "Uniform"; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs.erase("Time Sequence Length"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Time Sequence Length"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Time Sequence Length"] = 1; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs.erase("Learning Rate"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Learning Rate"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Learning Rate"] = 1.0; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs.erase("Importance Weight Truncation Level"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Importance Weight Truncation Level"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Importance Weight Truncation Level"] = 1.0; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["L2 Regularization"].erase("Enabled"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["L2 Regularization"]["Enabled"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["L2 Regularization"]["Enabled"] = true; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["L2 Regularization"].erase("Importance"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["L2 Regularization"]["Importance"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["L2 Regularization"]["Importance"] = 1.0; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Neural Network"].erase("Hidden Layers"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Neural Network"]["Hidden Layers"] = knlohmann::json(); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Neural Network"].erase("Optimizer"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Neural Network"]["Optimizer"] = 1.0; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Neural Network"]["Optimizer"] = "Adam"; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Neural Network"].erase("Engine"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Neural Network"]["Engine"] = 1.0; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Neural Network"]["Engine"] = "Adam"; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs.erase("Discount Factor"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Discount Factor"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Discount Factor"] = 0.99; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"].erase("Serialize"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Serialize"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Serialize"] = true; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"].erase("Start Size"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Start Size"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Start Size"] = 1; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"].erase("Maximum Size"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Maximum Size"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Maximum Size"] = 1; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"].erase("Cutoff Scale"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"]["Cutoff Scale"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"]["Cutoff Scale"] = 1.0; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"].erase("Target"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"]["Target"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"]["Target"] = 1.0; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"].erase("Annealing Rate"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"]["Annealing Rate"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"]["Annealing Rate"] = 1.0; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"].erase("REFER Beta"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"]["REFER Beta"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experience Replay"]["Off Policy"]["REFER Beta"] = 1.0; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs.erase("Experiences Between Policy Updates"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experiences Between Policy Updates"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Experiences Between Policy Updates"] = 1; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["State Rescaling"].erase("Enabled"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["State Rescaling"]["Enabled"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["State Rescaling"]["Enabled"] = true; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Reward"]["Outbound Penalization"].erase("Enabled"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Reward"]["Outbound Penalization"]["Enabled"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Reward"]["Outbound Penalization"]["Enabled"] = true; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Reward"]["Outbound Penalization"].erase("Factor"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Reward"]["Outbound Penalization"]["Factor"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Reward"]["Outbound Penalization"]["Factor"] = 2.0; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Reward"]["Rescaling"].erase("Enabled"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Reward"]["Rescaling"]["Enabled"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Reward"]["Rescaling"]["Enabled"] = false; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Testing"].erase("Sample Ids"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Testing"]["Sample Ids"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Testing"]["Sample Ids"] = std::vector<size_t>({0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Testing"].erase("Current Policy"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Testing"]["Current Policy"] = std::vector<size_t>({0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Environment Id History"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Environment Id History"] = std::vector<size_t>({1}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"].erase("Average Depth"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Average Depth"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Average Depth"] = 2; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"].erase("Current Policy"); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Current Policy"] = std::vector<size_t>({0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"].erase("Best Policy"); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Training"]["Best Policy"] = std::vector<size_t>({0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Termination Criteria"].erase("Max Experiences"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Termination Criteria"]["Max Experiences"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Termination Criteria"]["Max Experiences"] = 200; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Termination Criteria"].erase("Max Episodes"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Termination Criteria"]["Max Episodes"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Termination Criteria"]["Max Episodes"] = 200; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Termination Criteria"].erase("Max Policy Updates"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Termination Criteria"]["Max Policy Updates"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Termination Criteria"]["Max Policy Updates"] = 200.0; ASSERT_NO_THROW(a->setConfiguration(agentJs)); // Testing termination criteria e._currentGeneration = 2; // Control check ASSERT_FALSE(a->checkTermination()); // Checking max episodes termination a->_mode = "Training"; a->_maxEpisodes = 10; a->_currentEpisode = 20; ASSERT_TRUE(a->checkTermination()); a->_currentEpisode = 5; ASSERT_FALSE(a->checkTermination()); // Checking max experiences termination a->_mode = "Training"; a->_maxExperiences = 10; a->_experienceCount = 20; ASSERT_TRUE(a->checkTermination()); a->_experienceCount = 5; ASSERT_FALSE(a->checkTermination()); // Checking curPolicy update termination a->_mode = "Training"; a->_maxPolicyUpdates = 10; a->_policyUpdateCount = 20; ASSERT_TRUE(a->checkTermination()); a->_policyUpdateCount = 5; ASSERT_FALSE(a->checkTermination()); } //// Continous Agent TEST(a, continuousAgent) { // Creating base experiment Experiment e; e._logger = new Logger("Detailed", stdout); auto& experimentJs = e._js.getJson(); experimentJs["Variables"][0]["Name"] = "X"; Variable v; e._variables.push_back(&v); // Creating optimizer configuration Json knlohmann::json agentJs; // Configuring Problem e["Problem"]["Type"] = "Reinforcement Learning / Continuous"; reinforcementLearning::Continuous* pC; knlohmann::json problemRefJs; problemRefJs["Type"] = "Reinforcement Learning / Continuous"; problemRefJs["Environment Function"] = [](Sample &s){}; e["Variables"][0]["Name"] = "State0"; e["Variables"][1]["Name"] = "Action0"; e["Variables"][1]["Type"] = "Action"; e["Variables"][1]["Initial Exploration Noise"] = 0.45; e["Variables"][1]["Lower Bound"] = 0.00; e["Variables"][1]["Upper Bound"] = 1.00; Variable vState; vState._name = "State0"; vState._type = "State"; Variable vAction; vAction._name = "Action0"; vAction._type = "Action"; vAction._initialExplorationNoise = 0.45; vAction._lowerBound = 0.00; vAction._upperBound = 1.00; e._variables.push_back(&vState); e._variables.push_back(&vAction); ASSERT_NO_THROW(pC = dynamic_cast<reinforcementLearning::Continuous *>(Module::getModule(problemRefJs, &e))); e._problem = pC; ASSERT_NO_THROW(pC->initialize()); // Using a neural network solver (deep learning) for inference agentJs["Type"] = "Agent / Continuous / VRACER"; agentJs["Mode"] = "Training"; agentJs["Episodes Per Generation"] = 10; agentJs["Experiences Between Policy Updates"] = 1; agentJs["Discount Factor"] = 0.99; agentJs["Learning Rate"] = 0.0001; agentJs["Mini Batch"]["Size"] = 32; agentJs["Experience Replay"]["Start Size"] = 1000; agentJs["Experience Replay"]["Maximum Size"] = 10000; /// Configuring the neural network and its hidden layers agentJs["Neural Network"]["Engine"] = "OneDNN"; agentJs["Neural Network"]["Optimizer"] = "Adam"; agentJs["Neural Network"]["Hidden Layers"][0]["Type"] = "Layer/Linear"; agentJs["Neural Network"]["Hidden Layers"][0]["Output Channels"] = 16; // Creating module VRACER* a; ASSERT_NO_THROW(a = dynamic_cast<VRACER *>(Module::getModule(agentJs, &e))); // Defaults should be applied without a problem ASSERT_NO_THROW(a->applyModuleDefaults(agentJs)); // Covering variable functions (no effect) ASSERT_NO_THROW(a->applyVariableDefaults()); // Creating normal generator knlohmann::json normalDistroJs; normalDistroJs["Type"] = "Univariate/Normal"; normalDistroJs["Mean"] = 0.0; normalDistroJs["Standard Deviation"] = 1.0; a->_normalGenerator = dynamic_cast<korali::distribution::univariate::Normal*>(korali::Module::getModule(normalDistroJs, &e)); a->_normalGenerator->applyVariableDefaults(); a->_normalGenerator->applyModuleDefaults(normalDistroJs); a->_normalGenerator->setConfiguration(normalDistroJs); // Creating uniform generator knlohmann::json uniformDistroJs; uniformDistroJs["Type"] = "Univariate/Uniform"; uniformDistroJs["Minimum"] = -1.0; uniformDistroJs["Maximum"] = +1.0; a->_uniformGenerator = dynamic_cast<korali::distribution::univariate::Uniform*>(korali::Module::getModule(uniformDistroJs, &e)); a->_uniformGenerator->applyVariableDefaults(); a->_uniformGenerator->applyModuleDefaults(uniformDistroJs); a->_uniformGenerator->setConfiguration(uniformDistroJs); // Backup the correct base configuration auto baseOptJs = agentJs; auto baseExpJs = experimentJs; // Testing distribution corner cases policy_t curPolicy; policy_t prevPolicy; curPolicy.distributionParameters = std::vector<float>({0.0, 1.0}); prevPolicy.distributionParameters = std::vector<float>({0.0, 0.5}); curPolicy.unboundedAction = std::vector<float>({0.1f}); prevPolicy.unboundedAction = std::vector<float>({0.1f}); auto testAction = std::vector<float>({0.1f}); a->_policyDistribution = "Normal"; ASSERT_NO_THROW(a->agent::Continuous::initializeAgent()); ASSERT_NO_THROW(a->generateTrainingAction(curPolicy)); ASSERT_NO_THROW(a->generateTestingAction(curPolicy)); ASSERT_NO_THROW(a->calculateImportanceWeight(testAction, curPolicy, prevPolicy)); ASSERT_NO_THROW(a->calculateImportanceWeightGradient(testAction, curPolicy, prevPolicy)); ASSERT_NO_THROW(a->calculateKLDivergenceGradient(curPolicy, prevPolicy)); a->_policyDistribution = "Clipped Normal"; a->_actionLowerBounds = std::vector<float>({0.0}); a->_actionUpperBounds = std::vector<float>({1.0}); ASSERT_NO_THROW(a->agent::Continuous::initializeAgent()); ASSERT_NO_THROW(a->generateTrainingAction(curPolicy)); ASSERT_NO_THROW(a->generateTestingAction(curPolicy)); a->_policyDistribution = "Truncated Normal"; ASSERT_NO_THROW(a->agent::Continuous::initializeAgent()); ASSERT_NO_THROW(a->generateTrainingAction(curPolicy)); ASSERT_NO_THROW(a->generateTestingAction(curPolicy)); a->_policyDistribution = "Beta"; a->_actionLowerBounds = std::vector<float>({-std::numeric_limits<float>::infinity()}); a->_actionUpperBounds = std::vector<float>({1.0f}); ASSERT_ANY_THROW(a->agent::Continuous::initializeAgent()); a->_actionLowerBounds = std::vector<float>({0.0f}); a->_actionUpperBounds = std::vector<float>({+std::numeric_limits<float>::infinity()}); ASSERT_ANY_THROW(a->agent::Continuous::initializeAgent()); a->_actionLowerBounds = std::vector<float>({-1.0f}); a->_actionUpperBounds = std::vector<float>({1.0f}); ASSERT_NO_THROW(a->agent::Continuous::initializeAgent()); ASSERT_NO_THROW(a->generateTrainingAction(curPolicy)); curPolicy.distributionParameters = std::vector<float>({0.5, 0.2236}); ASSERT_NO_THROW(a->generateTestingAction(curPolicy)); ASSERT_NO_THROW(a->generateTestingAction(curPolicy)); ASSERT_NO_THROW(a->calculateImportanceWeight(testAction, curPolicy, prevPolicy)); ASSERT_NO_THROW(a->calculateImportanceWeightGradient(testAction, curPolicy, prevPolicy)); ASSERT_NO_THROW(a->calculateKLDivergenceGradient(curPolicy, prevPolicy)); pC->_actionVectorIndexes[0] = 1; e._variables[1]->_initialExplorationNoise = -1.0f; ASSERT_ANY_THROW(a->agent::Continuous::initializeAgent()); e._variables[1]->_initialExplorationNoise = 0.45f; a->_policyDistribution = "Squashed Normal"; ASSERT_NO_THROW(a->agent::Continuous::initializeAgent()); a->_actionLowerBounds = std::vector<float>({-std::numeric_limits<float>::infinity()}); a->_actionUpperBounds = std::vector<float>({1.0f}); ASSERT_ANY_THROW(a->agent::Continuous::initializeAgent()); a->_actionLowerBounds = std::vector<float>({0.0f}); a->_actionUpperBounds = std::vector<float>({+std::numeric_limits<float>::infinity()}); ASSERT_ANY_THROW(a->agent::Continuous::initializeAgent()); a->_actionLowerBounds = std::vector<float>({0.0f}); a->_actionUpperBounds = std::vector<float>({1.0f}); ASSERT_NO_THROW(a->agent::Continuous::initializeAgent()); ASSERT_NO_THROW(a->generateTrainingAction(curPolicy)); ASSERT_NO_THROW(a->generateTestingAction(curPolicy)); ASSERT_NO_THROW(a->calculateImportanceWeight(testAction, curPolicy, prevPolicy)); ASSERT_NO_THROW(a->calculateImportanceWeightGradient(testAction, curPolicy, prevPolicy)); ASSERT_NO_THROW(a->calculateKLDivergenceGradient(curPolicy, prevPolicy)); pC->_actionVectorIndexes[0] = 1; e._variables[1]->_initialExplorationNoise = -1.0f; ASSERT_ANY_THROW(a->agent::Continuous::initializeAgent()); e._variables[1]->_initialExplorationNoise = 0.45f; // Testing optional parameters agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Action Shifts"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Action Shifts"] = std::vector<float>({0.0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Action Scales"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Action Scales"] = std::vector<float>({0.0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Policy"]["Parameter Count"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Policy"]["Parameter Count"] = 1; ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Policy"]["Parameter Transformation Masks"] = 1.0; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Policy"]["Parameter Transformation Masks"] = std::vector<std::string>({""}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Policy"]["Parameter Scaling"] = 1.0; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Policy"]["Parameter Scaling"] = std::vector<float>({0.0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Policy"]["Parameter Shifting"] = 1.0; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Policy"]["Parameter Shifting"] = std::vector<float>({0.0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); // Testing mandatory parameters agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Policy"].erase("Distribution"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Policy"]["Distribution"] = 1.0; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Policy"]["Distribution"] = "Unknown"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Policy"]["Distribution"] = "Normal"; ASSERT_NO_THROW(a->setConfiguration(agentJs)); } //// Continous Agent TEST(a, VRACER) { // Creating base experiment Experiment e; e._logger = new Logger("Detailed", stdout); auto& experimentJs = e._js.getJson(); experimentJs["Variables"][0]["Name"] = "X"; Variable v; e._variables.push_back(&v); // Creating optimizer configuration Json knlohmann::json agentJs; // Configuring Problem e["Problem"]["Type"] = "Reinforcement Learning / Continuous"; reinforcementLearning::Continuous* pC; knlohmann::json problemRefJs; problemRefJs["Type"] = "Reinforcement Learning / Continuous"; problemRefJs["Environment Function"] = 0; e["Variables"][0]["Name"] = "State0"; e["Variables"][1]["Name"] = "Action0"; e["Variables"][1]["Type"] = "Action"; e["Variables"][1]["Initial Exploration Noise"] = 0.45; e["Variables"][1]["Lower Bound"] = 0.00; e["Variables"][1]["Upper Bound"] = 1.00; Variable vState; vState._name = "State0"; vState._type = "State"; Variable vAction; vAction._name = "Action0"; vAction._type = "Action"; vAction._initialExplorationNoise = 0.45; vAction._lowerBound = 0.00; vAction._upperBound = 1.00; e._variables.push_back(&vState); e._variables.push_back(&vAction); ASSERT_NO_THROW(pC = dynamic_cast<reinforcementLearning::Continuous *>(Module::getModule(problemRefJs, &e))); e._problem = pC; ASSERT_NO_THROW(pC->initialize()); // Using a neural network solver (deep learning) for inference agentJs["Type"] = "Agent / Continuous / VRACER"; agentJs["Mode"] = "Training"; agentJs["Episodes Per Generation"] = 10; agentJs["Experiences Between Policy Updates"] = 1; agentJs["Discount Factor"] = 0.99; agentJs["Learning Rate"] = 0.0001; agentJs["Mini Batch"]["Size"] = 32; agentJs["Experience Replay"]["Start Size"] = 1000; agentJs["Experience Replay"]["Maximum Size"] = 10000; /// Configuring the neural network and its hidden layers agentJs["Neural Network"]["Engine"] = "OneDNN"; agentJs["Neural Network"]["Optimizer"] = "Adam"; agentJs["Neural Network"]["Hidden Layers"][0]["Type"] = "Layer/Linear"; agentJs["Neural Network"]["Hidden Layers"][0]["Output Channels"] = 16; // Creating module VRACER* a; ASSERT_NO_THROW(a = dynamic_cast<VRACER *>(Module::getModule(agentJs, &e))); // Defaults should be applied without a problem ASSERT_NO_THROW(a->applyModuleDefaults(agentJs)); // Covering variable functions (no effect) ASSERT_NO_THROW(a->applyVariableDefaults()); // Backup the correct base configuration auto baseOptJs = agentJs; auto baseExpJs = experimentJs; // Testing optional parameters agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Statistics"]["Average Action Sigmas"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Statistics"]["Average Action Sigmas"] = std::vector<float>({0.0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; e["Variables"][0].erase("Initial Exploration Noise"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; e["Variables"][0]["Initial Exploration Noise"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; e["Variables"][0]["Initial Exploration Noise"] = 0.0f; ASSERT_NO_THROW(a->setConfiguration(agentJs)); ASSERT_NO_THROW(a->initializeAgent()); e._solver = a; Sample s; auto curPolicy = a->getAgentPolicy(); s["Policy Hyperparameters"] = a->getAgentPolicy(); s["Sample Id"] = 0; s["State Rescaling"]["Means"] = std::vector<float>({0.0}); s["State Rescaling"]["Standard Deviations"] = std::vector<float>({1.0}); // Evaluation function _functionVector.resize(1); std::function<void(korali::Sample&)> modelFc = [](Sample& s) { s["Termination"] = "Unknown"; }; _functionVector[0] = &modelFc; // Creating conduit knlohmann::json conduitJs; conduitJs["Type"] = "Sequential"; ASSERT_NO_THROW(_conduit = dynamic_cast<Sequential *>(Module::getModule(conduitJs, NULL))); _launchId = 0; __envFunctionId = 0; __currentSample = &s; ASSERT_ANY_THROW(__environmentWrapper()); modelFc = [](Sample& s) { s["Termination"] = "Non Terminal"; }; ASSERT_ANY_THROW(__environmentWrapper()); modelFc = [](Sample& s) { s["Termination"] = "Terminal"; }; s._workerThread = co_active(); ASSERT_ANY_THROW(__environmentWrapper()); _envThread = co_active(); s["State"] = std::vector<float>({std::numeric_limits<float>::infinity()}); ASSERT_ANY_THROW(pC->runEnvironment(s)); } //// Discrete Agent TEST(a, discreteAgent) { // Creating base experiment Experiment e; e._logger = new Logger("Detailed", stdout); auto& experimentJs = e._js.getJson(); experimentJs["Variables"][0]["Name"] = "X"; Variable v; e._variables.push_back(&v); // Creating optimizer configuration Json knlohmann::json agentJs; // Configuring Problem e["Problem"]["Type"] = "Reinforcement Learning / Discrete"; reinforcementLearning::Discrete* pD; knlohmann::json problemRefJs; problemRefJs["Type"] = "Reinforcement Learning / Discrete"; problemRefJs["Environment Function"] = [](Sample &s){}; problemRefJs["Possible Actions"] = std::vector<std::vector<float>>({ { -10.0 }, { 10.0 } }); e["Variables"][0]["Name"] = "State0"; e["Variables"][1]["Name"] = "Action0"; e["Variables"][1]["Type"] = "Action"; Variable vState; vState._name = "State0"; vState._type = "State"; Variable vAction; vAction._name = "Action0"; vAction._type = "Action"; e._variables.push_back(&vState); e._variables.push_back(&vAction); ASSERT_NO_THROW(pD = dynamic_cast<reinforcementLearning::Discrete *>(Module::getModule(problemRefJs, &e))); e._problem = pD; pD->_possibleActions = std::vector<std::vector<float>>({ { -10.0 }, { 10.0 } }); pD->initialize(); ASSERT_NO_THROW(pD->initialize()); // Using a neural network solver (deep learning) for inference agentJs["Type"] = "Agent / Discrete / dVRACER"; agentJs["Mode"] = "Training"; agentJs["Episodes Per Generation"] = 10; agentJs["Experiences Between Policy Updates"] = 1; agentJs["Discount Factor"] = 0.99; agentJs["Learning Rate"] = 0.0001; agentJs["Importance Weight Truncation Level"] = 0.0001; agentJs["Mini Batch"]["Size"] = 32; agentJs["Experience Replay"]["Start Size"] = 1000; agentJs["Experience Replay"]["Maximum Size"] = 10000; /// Configuring the neural network and its hidden layers agentJs["Neural Network"]["Engine"] = "OneDNN"; agentJs["Neural Network"]["Optimizer"] = "Adam"; agentJs["Neural Network"]["Hidden Layers"][0]["Type"] = "Layer/Linear"; agentJs["Neural Network"]["Hidden Layers"][0]["Output Channels"] = 16; // Creating module dVRACER* a; ASSERT_NO_THROW(a = dynamic_cast<dVRACER *>(Module::getModule(agentJs, &e))); // Defaults should be applied without a problem ASSERT_NO_THROW(a->applyModuleDefaults(agentJs)); // Covering variable functions (no effect) ASSERT_NO_THROW(a->applyVariableDefaults()); // Backup the correct base configuration auto baseOptJs = agentJs; auto baseExpJs = experimentJs; // Testing distribution corner cases policy_t curPolicy; policy_t prevPolicy; curPolicy.distributionParameters = std::vector<float>({0.2, 0.8, 1.0}); // Q values andbeta curPolicy.actionProbabilities = std::vector<float>({0.2, 0.8}); // Probability distribution of possible actions curPolicy.actionIndex = 0; prevPolicy.distributionParameters = std::vector<float>({0.5, 0.5, 1.0}); // Q values andbeta prevPolicy.actionProbabilities = std::vector<float>({0.5, 0.5}); // Probability distribution of possible actions prevPolicy.actionIndex = 0; auto testAction = std::vector<float>({-10.0f}); ASSERT_NO_THROW(a->agent::Discrete::initializeAgent()); ASSERT_NO_THROW(a->calculateImportanceWeight(testAction, curPolicy, prevPolicy)); ASSERT_NO_THROW(a->calculateImportanceWeightGradient(curPolicy, prevPolicy)); ASSERT_NO_THROW(a->calculateKLDivergenceGradient(curPolicy, prevPolicy)); } TEST(a, dVRACER) { // Creating base experiment Experiment e; e._logger = new Logger("Detailed", stdout); auto& experimentJs = e._js.getJson(); experimentJs["Variables"][0]["Name"] = "X"; Variable v; e._variables.push_back(&v); // Creating optimizer configuration Json knlohmann::json agentJs; // Configuring Problem e["Problem"]["Type"] = "Reinforcement Learning / Discrete"; reinforcementLearning::Discrete* pD; knlohmann::json problemRefJs; problemRefJs["Type"] = "Reinforcement Learning / Discrete"; problemRefJs["Environment Function"] = [](Sample &s){}; problemRefJs["Possible Actions"] = std::vector<std::vector<float>>({ { -10.0 }, { 10.0 } }); e["Variables"][0]["Name"] = "State0"; e["Variables"][1]["Name"] = "Action0"; e["Variables"][1]["Type"] = "Action"; Variable vState; vState._name = "State0"; vState._type = "State"; Variable vAction; vAction._name = "Action0"; vAction._type = "Action"; e._variables.push_back(&vState); e._variables.push_back(&vAction); ASSERT_NO_THROW(pD = dynamic_cast<reinforcementLearning::Discrete *>(Module::getModule(problemRefJs, &e))); e._problem = pD; pD->_possibleActions = std::vector<std::vector<float>>({ { -10.0 }, { 10.0 } }); ASSERT_NO_THROW(pD->initialize()); // Using a neural network solver (deep learning) for inference agentJs["Type"] = "Agent / Discrete / dVRACER"; agentJs["Mode"] = "Training"; agentJs["Episodes Per Generation"] = 10; agentJs["Experiences Between Policy Updates"] = 1; agentJs["Discount Factor"] = 0.99; agentJs["Learning Rate"] = 0.0001; agentJs["Mini Batch"]["Size"] = 32; agentJs["Experience Replay"]["Start Size"] = 1000; agentJs["Experience Replay"]["Maximum Size"] = 10000; /// Configuring the neural network and its hidden layers agentJs["Neural Network"]["Engine"] = "OneDNN"; agentJs["Neural Network"]["Optimizer"] = "Adam"; agentJs["Neural Network"]["Hidden Layers"][0]["Type"] = "Layer/Linear"; agentJs["Neural Network"]["Hidden Layers"][0]["Output Channels"] = 16; // Creating module dVRACER* a; ASSERT_NO_THROW(a = dynamic_cast<dVRACER *>(Module::getModule(agentJs, &e))); // Defaults should be applied without a problem ASSERT_NO_THROW(a->applyModuleDefaults(agentJs)); // Covering variable functions (no effect) ASSERT_NO_THROW(a->applyVariableDefaults()); // Backup the correct base configuration auto baseOptJs = agentJs; auto baseExpJs = experimentJs; // Testing optional parameters agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Statistics"]["Average Action Sigmas"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; agentJs["Statistics"]["Average Action Sigmas"] = std::vector<float>({0.0}); ASSERT_NO_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; e["Variables"][0].erase("Initial Exploration Noise"); ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; e["Variables"][0]["Initial Exploration Noise"] = "Not a Number"; ASSERT_ANY_THROW(a->setConfiguration(agentJs)); agentJs = baseOptJs; experimentJs = baseExpJs; e["Variables"][0]["Initial Exploration Noise"] = 0.0f; ASSERT_NO_THROW(a->setConfiguration(agentJs)); } } // namespace
33.648682
131
0.707094
JonathanLehner
4da5ceda0fc25b8942706fe37117477910515dc6
808
cpp
C++
src/AdventOfCode2019/Day16-FlawedFrequencyTransmission/Day16-Main.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
src/AdventOfCode2019/Day16-FlawedFrequencyTransmission/Day16-Main.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
src/AdventOfCode2019/Day16-FlawedFrequencyTransmission/Day16-Main.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
#include "Day16-FlawedFrequencyTransmission.h" #include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h> __BEGIN_LIBRARIES_DISABLE_WARNINGS #include <algorithm> #include <fstream> #include <iostream> __END_LIBRARIES_DISABLE_WARNINGS int main() { namespace CurrentDay = AdventOfCode::Year2019::Day16; std::fstream fileIn("input.txt"); std::string signalString { (std::istreambuf_iterator<char>(fileIn)), (std::istreambuf_iterator<char>()) }; signalString.erase(std::remove(signalString.begin(), signalString.end(), '\n'), signalString.end()); std::cout << "First part: " << CurrentDay::firstEightDigitsOfFinalOutput(signalString) << std::endl; std::cout << "Second part: " << CurrentDay::messageInFinalOutputForRealSignal(signalString) << std::endl; }
29.925926
109
0.725248
dbartok
4daccc511eb5dd4afc3eaaf3eab70165f52d57be
677
hpp
C++
include/JVM/structures/Types.hpp
vieiramanoel/SB_JVM_2019_1
779d080eeab258dad61bcee27dae92aa46ff0dec
[ "MIT" ]
null
null
null
include/JVM/structures/Types.hpp
vieiramanoel/SB_JVM_2019_1
779d080eeab258dad61bcee27dae92aa46ff0dec
[ "MIT" ]
5
2019-05-13T00:33:51.000Z
2019-07-09T12:10:12.000Z
include/JVM/structures/Types.hpp
vieiramanoel/SB_JVM_2019_1
779d080eeab258dad61bcee27dae92aa46ff0dec
[ "MIT" ]
null
null
null
#ifndef _Types_H_ #define _Types_H_ #include <map> #include <memory> #include <string> enum Type { B, C, D, F, I, J, S, Z, L, R }; static const std::map<std::string, Type> TypeMap = std::map<std::string, Type>{ {"B", B}, {"C", C}, {"D", D}, {"F", F}, {"I", I}, {"J", J}, {"S", S}, {"Z", Z}, {"L", L}}; int static category(Type t) { if (t == D || t == J) { return 2; } return 1; } static const std::map<int, Type> ATypeMap = std::map<int, Type>{ {4, B}, {5, C}, {6, F}, {7, D}, {8, B}, {9, S}, {10, I}, {11, J}, }; /*B = byte C = char D = double F = float I = int J = long S = short Z = bool L = class R = string */ #endif
18.805556
79
0.478582
vieiramanoel
4dade8f223eeb8d226c4660d8086a8b8c5100052
2,324
hpp
C++
src/utils/utils_internal_gpu/cuSetArange_gpu.hpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
11
2020-04-14T15:45:42.000Z
2022-03-31T14:37:03.000Z
src/utils/utils_internal_gpu/cuSetArange_gpu.hpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
38
2019-08-02T15:15:51.000Z
2022-03-04T19:07:02.000Z
src/utils/utils_internal_gpu/cuSetArange_gpu.hpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
7
2019-07-17T07:50:55.000Z
2021-07-03T06:44:52.000Z
#ifndef _H_cuSetArange_gpu_ #define _H_cuSetArange_gpu_ #include <cstdio> #include <cstdlib> #include <stdint.h> #include <climits> #include "Type.hpp" #include "cytnx_error.hpp" #include "Storage.hpp" namespace cytnx{ namespace utils_internal{ // type = 0, start < end , incremental // type = 1, start > end , decremental void cuSetArange_gpu_cd(boost::intrusive_ptr<Storage_base> &in, const cytnx_double &start, const cytnx_double &end, const cytnx_double &step, const cytnx_uint64 &Nelem); void cuSetArange_gpu_cf(boost::intrusive_ptr<Storage_base> &in, const cytnx_double &start, const cytnx_double &end, const cytnx_double &step, const cytnx_uint64 &Nelem); void cuSetArange_gpu_d(boost::intrusive_ptr<Storage_base> &in, const cytnx_double &start, const cytnx_double &end, const cytnx_double &step, const cytnx_uint64 &Nelem); void cuSetArange_gpu_f(boost::intrusive_ptr<Storage_base> &in, const cytnx_double &start, const cytnx_double &end, const cytnx_double &step, const cytnx_uint64 &Nelem); void cuSetArange_gpu_i64(boost::intrusive_ptr<Storage_base> &in, const cytnx_double &start, const cytnx_double &end, const cytnx_double &step, const cytnx_uint64 &Nelem); void cuSetArange_gpu_u64(boost::intrusive_ptr<Storage_base> &in, const cytnx_double &start, const cytnx_double &end, const cytnx_double &step, const cytnx_uint64 &Nelem); void cuSetArange_gpu_i32(boost::intrusive_ptr<Storage_base> &in, const cytnx_double &start, const cytnx_double &end, const cytnx_double &step, const cytnx_uint64 &Nelem); void cuSetArange_gpu_u32(boost::intrusive_ptr<Storage_base> &in, const cytnx_double &start, const cytnx_double &end, const cytnx_double &step, const cytnx_uint64 &Nelem); void cuSetArange_gpu_i16(boost::intrusive_ptr<Storage_base> &in, const cytnx_double &start, const cytnx_double &end, const cytnx_double &step, const cytnx_uint64 &Nelem); void cuSetArange_gpu_u16(boost::intrusive_ptr<Storage_base> &in, const cytnx_double &start, const cytnx_double &end, const cytnx_double &step, const cytnx_uint64 &Nelem); void cuSetArange_gpu_b(boost::intrusive_ptr<Storage_base> &in, const cytnx_double &start, const cytnx_double &end, const cytnx_double &step, const cytnx_uint64 &Nelem); } } #endif
72.625
178
0.765491
j9263178
4daf866ed2db218071af1c668ba6ad659aa5ac97
3,469
cpp
C++
src/lexa2.cpp
AlexeyZhuravlev/hashcode-2020-prequal
dbd7ce52d08ec3d07ecd0c9de035cec4f429330f
[ "MIT" ]
null
null
null
src/lexa2.cpp
AlexeyZhuravlev/hashcode-2020-prequal
dbd7ce52d08ec3d07ecd0c9de035cec4f429330f
[ "MIT" ]
null
null
null
src/lexa2.cpp
AlexeyZhuravlev/hashcode-2020-prequal
dbd7ce52d08ec3d07ecd0c9de035cec4f429330f
[ "MIT" ]
null
null
null
#include <common.h> #include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <iostream> #include <cassert> #include <cmath> #include <string> #include <queue> #include <set> #include <map> #include <cstdlib> #include <chrono> using namespace std; struct MySolver : public Context { std::vector<std::set<int>> serverToTasks; std::vector<int> timeOnServer; std::vector<char> usedTargets; int GetCost(int file, std::vector<int>& required, int server) { int result = timeOnServer[server]; std::queue<int> elements; elements.push(file); while (!elements.empty()) { int file = elements.front(); elements.pop(); if (serverToTasks[server].count(file) == 0) { result += CT[file]; required.push_back(file); } for (int dep : Deps[file]) { elements.push(dep); } } std::reverse(required.begin(), required.end()); return result; } void Solve() { serverToTasks.resize(S); timeOnServer.assign(S, 0); usedTargets.assign(T, 0); while (true) { int server = 0; for (int i = 0; i < S; ++i) { if (timeOnServer[i] < timeOnServer[server]) { server = i; } } int bestReward = -10000000; int correspondingTime = 0; int bestTarget = 0; std::vector<int> bestElements; for (int i = 0; i < T; ++i) { int target = Target[i]; if (usedTargets[i]) { continue; } std::vector<int> targetElements; int time = GetCost(target, targetElements, server); int deadline = Deadline[i]; int points = Points[i]; int reward = points + deadline - time; if (reward > bestReward) { bestReward = reward; bestElements = targetElements; correspondingTime = time; bestTarget = i; } } //std::cerr << bestReward << std::endl; //std::cerr << bestElements.size() << std::endl; if (bestElements.empty()) { break; } for (int task: bestElements) { if (serverToTasks[server].count(task) == 0) { serverToTasks[server].insert(task); Solution.push_back(std::make_pair(task, server)); } //std::cerr << task << " " << server << std::endl; } timeOnServer[server] = correspondingTime; usedTargets[bestTarget] = 1; } } }; int main() { MySolver solver; solver.Input(); auto start = std::chrono::system_clock::now(); cerr << "Started solving..." << endl; solver.Solve(); cerr << "Done!" << endl; auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; cerr << "Test time: " << elapsed_seconds.count() << endl; cerr << "Outputting" << endl; solver.Output(); cerr << solver.GetScore() << endl; return 0; }
30.429825
70
0.477083
AlexeyZhuravlev
4db2ac13e906cbc3bc2b17d6b58cb0af0282c540
305
cpp
C++
baekjoon/15596.cpp
GihwanKim/Baekjoon
52eb2bf80bb1243697858445e5b5e2d50d78be4e
[ "MIT" ]
null
null
null
baekjoon/15596.cpp
GihwanKim/Baekjoon
52eb2bf80bb1243697858445e5b5e2d50d78be4e
[ "MIT" ]
null
null
null
baekjoon/15596.cpp
GihwanKim/Baekjoon
52eb2bf80bb1243697858445e5b5e2d50d78be4e
[ "MIT" ]
null
null
null
/* 15596 : 정수 N개의 합 URL : https://www.acmicpc.net/problem/15596 Input : Output : */ #include <vector> long long sum(std::vector<int> &a) { long long ans = 0; for (std::vector<int>::iterator it = a.begin(); it != a.end(); ++it) { ans += (*it); } return ans; }
16.052632
72
0.514754
GihwanKim
4dbb57700ff317f48dd3721ae11602b7b6a7bbe3
9,002
cpp
C++
src/xalanc/XalanSourceTree/XalanSourceTreeText.cpp
rherardi/xml-xalan-c-src_1_10_0
24e6653a617a244e4def60d67b57e70a192a5d4d
[ "Apache-2.0" ]
null
null
null
src/xalanc/XalanSourceTree/XalanSourceTreeText.cpp
rherardi/xml-xalan-c-src_1_10_0
24e6653a617a244e4def60d67b57e70a192a5d4d
[ "Apache-2.0" ]
null
null
null
src/xalanc/XalanSourceTree/XalanSourceTreeText.cpp
rherardi/xml-xalan-c-src_1_10_0
24e6653a617a244e4def60d67b57e70a192a5d4d
[ "Apache-2.0" ]
null
null
null
/* * Copyright 1999-2004 The Apache Software 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. */ #include "XalanSourceTreeText.hpp" #include <xalanc/XalanDOM/XalanDOMException.hpp> #include <xalanc/PlatformSupport/DOMStringHelper.hpp> #include "XalanSourceTreeComment.hpp" #include "XalanSourceTreeDocumentFragment.hpp" #include "XalanSourceTreeElement.hpp" #include "XalanSourceTreeProcessingInstruction.hpp" #include "XalanSourceTreeHelper.hpp" XALAN_CPP_NAMESPACE_BEGIN static const XalanDOMString s_emptyString(XalanMemMgrs::getDummyMemMgr()); XalanSourceTreeText::XalanSourceTreeText( const XalanDOMString& theData, XalanNode* theParentNode, XalanNode* thePreviousSibling, XalanNode* theNextSibling, IndexType theIndex) : XalanText(), m_data(theData), m_parentNode(theParentNode), m_previousSibling(thePreviousSibling), m_nextSibling(theNextSibling), m_index(theIndex) { } XalanSourceTreeText::~XalanSourceTreeText() { } XalanSourceTreeText::XalanSourceTreeText( const XalanSourceTreeText& theSource, bool /* deep */) : XalanText(theSource), m_data(theSource.m_data), m_parentNode(0), m_previousSibling(0), m_nextSibling(0), m_index(0) { } const XalanDOMString& XalanSourceTreeText::getNodeName() const { return s_nameString; } const XalanDOMString& XalanSourceTreeText::getNodeValue() const { return m_data; } XalanSourceTreeText::NodeType XalanSourceTreeText::getNodeType() const { return TEXT_NODE; } XalanNode* XalanSourceTreeText::getParentNode() const { return m_parentNode; } const XalanNodeList* XalanSourceTreeText::getChildNodes() const { throw XalanDOMException(XalanDOMException::NOT_SUPPORTED_ERR); // Dummy return value... return 0; } XalanNode* XalanSourceTreeText::getFirstChild() const { return 0; } XalanNode* XalanSourceTreeText::getLastChild() const { return 0; } XalanNode* XalanSourceTreeText::getPreviousSibling() const { return m_previousSibling; } XalanNode* XalanSourceTreeText::getNextSibling() const { return m_nextSibling; } const XalanNamedNodeMap* XalanSourceTreeText::getAttributes() const { return 0; } XalanDocument* XalanSourceTreeText::getOwnerDocument() const { assert(m_parentNode != 0); return m_parentNode->getOwnerDocument(); } #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) XalanNode* #else XalanSourceTreeText* #endif XalanSourceTreeText::cloneNode(bool /* deep */) const { throw XalanDOMException(XalanDOMException::NOT_SUPPORTED_ERR); // Dummy return value... return 0; } XalanNode* XalanSourceTreeText::insertBefore( XalanNode* /* newChild */, XalanNode* /* refChild */) { throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR); // Dummy return value... return 0; } XalanNode* XalanSourceTreeText::replaceChild( XalanNode* /* newChild */, XalanNode* /* oldChild */) { throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR); // Dummy return value... return 0; } XalanNode* XalanSourceTreeText::removeChild(XalanNode* /* oldChild */) { throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR); // Dummy return value... return 0; } XalanNode* XalanSourceTreeText::appendChild(XalanNode* /* newChild */) { throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR); // Dummy return value... return 0; } bool XalanSourceTreeText::hasChildNodes() const { return false; } void XalanSourceTreeText::setNodeValue(const XalanDOMString& /* nodeValue */) { throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR); } void XalanSourceTreeText::normalize() { throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR); } bool XalanSourceTreeText::isSupported( const XalanDOMString& /* feature */, const XalanDOMString& /* version */) const { return false; } const XalanDOMString& XalanSourceTreeText::getNamespaceURI() const { return s_emptyString; } const XalanDOMString& XalanSourceTreeText::getPrefix() const { return s_emptyString; } const XalanDOMString& XalanSourceTreeText::getLocalName() const { return s_emptyString; } void XalanSourceTreeText::setPrefix(const XalanDOMString& /* prefix */) { throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR); } bool XalanSourceTreeText::isIndexed() const { return true; } XalanSourceTreeText::IndexType XalanSourceTreeText::getIndex() const { return m_index; } const XalanDOMString& XalanSourceTreeText::getData() const { return m_data; } unsigned int XalanSourceTreeText::getLength() const { assert(unsigned(length(m_data)) == length(m_data)); return unsigned(length(m_data)); } XalanDOMString& XalanSourceTreeText::substringData( unsigned int offset, unsigned int count, XalanDOMString& theResult) const { return m_data.substr(theResult, offset, count); } void XalanSourceTreeText::appendData(const XalanDOMString& /* arg */) { throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR); } void XalanSourceTreeText::insertData( unsigned int /* offset */, const XalanDOMString& /* arg */) { throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR); } void XalanSourceTreeText::deleteData( unsigned int /* offset */, unsigned int /* count */) { throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR); } void XalanSourceTreeText::replaceData( unsigned int /* offset */, unsigned int /* count */, const XalanDOMString& /* arg */) { throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR); } XalanText* XalanSourceTreeText::splitText(unsigned int /* offset */) { throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR); return 0; } bool XalanSourceTreeText::isIgnorableWhitespace() const { return false; } void XalanSourceTreeText::setParent(XalanSourceTreeElement* theParent) { m_parentNode = theParent; } void XalanSourceTreeText::setParent(XalanSourceTreeDocumentFragment* theParent) { m_parentNode = theParent; } void XalanSourceTreeText::setPreviousSibling(XalanSourceTreeComment* thePreviousSibling) { m_previousSibling = thePreviousSibling; } void XalanSourceTreeText::setPreviousSibling(XalanSourceTreeElement* thePreviousSibling) { m_previousSibling = thePreviousSibling; } void XalanSourceTreeText::setPreviousSibling(XalanSourceTreeProcessingInstruction* thePreviousSibling) { m_previousSibling = thePreviousSibling; } void XalanSourceTreeText::setPreviousSibling(XalanSourceTreeText* thePreviousSibling) { m_previousSibling = thePreviousSibling; } void XalanSourceTreeText::appendSiblingNode(XalanSourceTreeComment* theSibling) { XalanSourceTreeHelper::appendSibling(this, m_nextSibling, theSibling); } void XalanSourceTreeText::appendSiblingNode(XalanSourceTreeElement* theSibling) { XalanSourceTreeHelper::appendSibling(this, m_nextSibling, theSibling); } void XalanSourceTreeText::appendSiblingNode(XalanSourceTreeProcessingInstruction* theSibling) { XalanSourceTreeHelper::appendSibling(this, m_nextSibling, theSibling); } void XalanSourceTreeText::appendSiblingNode(XalanSourceTreeText* theSibling) { XalanSourceTreeHelper::appendSibling(this, m_nextSibling, theSibling); } static XalanDOMString s_staticNameString(XalanMemMgrs::getDummyMemMgr()); const XalanDOMString& XalanSourceTreeText::s_nameString = s_staticNameString; const XalanDOMChar s_text[] = { XalanUnicode::charNumberSign, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, XalanUnicode::charLetter_x, XalanUnicode::charLetter_t, 0 }; void XalanSourceTreeText::initialize(MemoryManagerType& theManager) { XalanDOMString theBuffer(s_text, theManager); s_staticNameString.swap(theBuffer); } void XalanSourceTreeText::terminate() { releaseMemory(s_staticNameString, XalanMemMgrs::getDummyMemMgr()); } XALAN_CPP_NAMESPACE_END
17.212237
98
0.731504
rherardi
4dbc6b934e18c1fb4486c8d4dcd577d452397a37
1,336
hh
C++
src/lib/MeshFEM/Parallelism.hh
MeshFEM/MeshFEM
9b3619fa450d83722879bfd0f5a3fe69d927bd63
[ "MIT" ]
19
2020-10-21T10:05:17.000Z
2022-03-20T13:41:50.000Z
src/lib/MeshFEM/Parallelism.hh
MeshFEM/MeshFEM
9b3619fa450d83722879bfd0f5a3fe69d927bd63
[ "MIT" ]
4
2021-01-01T15:58:15.000Z
2021-09-19T03:31:09.000Z
src/lib/MeshFEM/Parallelism.hh
MeshFEM/MeshFEM
9b3619fa450d83722879bfd0f5a3fe69d927bd63
[ "MIT" ]
4
2020-10-05T09:01:50.000Z
2022-01-11T03:02:39.000Z
#ifndef PARALLELISM_HH #define PARALLELISM_HH #include <stddef.h> #ifdef MESHFEM_WITH_TBB #define TBB_PREVIEW_GLOBAL_CONTROL 1 #include <tbb/global_control.h> #include <tbb/parallel_for.h> #include <tbb/enumerable_thread_specific.h> #include <tbb/combinable.h> #include <memory> #include <MeshFEM_export.h> MESHFEM_EXPORT void set_max_num_tbb_threads(int num_threads); MESHFEM_EXPORT void unset_max_num_tbb_threads(); // We may want to use different numbers of threads to assemble the Hessian/gradient because of the // overhead of the reduction operation used to combine the results. MESHFEM_EXPORT void set_hessian_assembly_num_threads(int num_threads); MESHFEM_EXPORT void set_gradient_assembly_num_threads(int num_threads); MESHFEM_EXPORT tbb::task_arena &get_hessian_assembly_arena(); MESHFEM_EXPORT tbb::task_arena &get_gradient_assembly_arena(); template<typename F> void parallel_for_range(size_t n, F &&f) { tbb::parallel_for(tbb::blocked_range<size_t>(0, n), [&f](const tbb::blocked_range<size_t> &r) { for (size_t i = r.begin(); i < r.end(); ++i) f(i); }); } #else // Dummy implementation template<typename F> void parallel_for_range(size_t n, F &&f) { for (size_t i = 0; i < n; ++i) f(i); } #endif #endif /* end of include guard: PARALLELISM_HH */
27.265306
98
0.736527
MeshFEM
4dc42611d1bd6b8ffa52cb120249b0ee7cfeca41
790
cpp
C++
string_demo.cpp
carryxyh/practice
a8ec7d647a5bc6a9217dae15ae7d1a8c3ff84fc3
[ "Apache-2.0" ]
null
null
null
string_demo.cpp
carryxyh/practice
a8ec7d647a5bc6a9217dae15ae7d1a8c3ff84fc3
[ "Apache-2.0" ]
null
null
null
string_demo.cpp
carryxyh/practice
a8ec7d647a5bc6a9217dae15ae7d1a8c3ff84fc3
[ "Apache-2.0" ]
null
null
null
// // Created by 修宇航 on 2017/11/1. // #include <string> #include <iostream> using std::string; int main() { string s1; //默认初始化 string s2 = s1; //s2是s1的副本 string s3 = "hiya"; //s3是该字符串字面值的副本 拷贝初始化 string s4(10, 'c'); //cccccccccc 直接初始化 string s5 = string(10, 'c'); //拷贝 这个string是临时对象用于拷贝 //------------------------------------ // os << s s写到输出流os当中,返回os // is >> s 从is中读取字符串赋给s,字符串以空白分割,返回is // getline(is,s) 从is读取一行赋给s,返回is //其他操作与 java 类似 s.empty();空返回true s.size s[n] s1+s2 s1=s2 s1==s2大小写敏感 //c++不支持如下写法: // string sss = "hello" + " world"; //引用处理字符串 string string1("hello world"); for (auto &c : string1) { c = toupper(c); //c是一个引用,赋值语句改变string1中的字符的值 } std::cout << string1 << std::endl; return 0; }
22.571429
74
0.560759
carryxyh
4dc8191fc834f4e097b677905986f5c741d83f83
13,612
cpp
C++
src/bindings/Scriptdev2/scripts/northrend/violet_hold/boss_ichoron.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
1
2017-11-16T19:04:07.000Z
2017-11-16T19:04:07.000Z
src/bindings/Scriptdev2/scripts/northrend/violet_hold/boss_ichoron.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
null
null
null
src/bindings/Scriptdev2/scripts/northrend/violet_hold/boss_ichoron.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
null
null
null
/* Copyright (C) 2006 - 2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: boss_ichoron SDAuthor: ckegg SD%Complete: 0 SDComment: SDCategory: The Violet Hold EndScriptData */ #include "precompiled.h" #include "def_violet_hold.h" enum { SAY_AGGRO = -1608018, SAY_SLAY_1 = -1608019, SAY_SLAY_2 = -1608020, SAY_SLAY_3 = -1608021, SAY_DEATH = -1608022, SAY_SPAWN = -1608023, SAY_ENRAGE = -1608024, SAY_SHATTER = -1608025, SAY_BUBBLE = -1608026, EMOTE_ICHORON_PROTECTIVE_BUBBLE = -1608008, SPELL_DRAINED = 59820, SPELL_FRENZY = 54312, SPELL_FRENZY_H = 59522, SPELL_PROTECTIVE_BUBBLE = 54306, SPELL_WATER_BLAST = 54237, SPELL_WATER_BLAST_H = 59520, SPELL_WATER_BOLT_VOLLEY = 54241, SPELL_WATER_BOLT_VOLLEY_H = 59521, NPC_ICHOR_GLOBULE = 29321, SPELL_SPLASH = 59516, SPELL_WATER_GLOBULE = 54268, SPELL_WATER_GLOBULE_2 = 54260, GLOBULE_HEAL_H = 9000, GLOBULE_HEAL = 5000 }; struct MANGOS_DLL_DECL boss_ichoronAI : public ScriptedAI { boss_ichoronAI(Creature *pCreature) : ScriptedAI(pCreature) { m_pInstance = ((ScriptedInstance*)pCreature->GetInstanceData()); m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty(); Reset(); } ScriptedInstance *m_pInstance; std::list<uint64> m_lWaterElementsGUIDList; bool m_bIsRegularMode; bool m_bIsExploded; bool m_bIsFrenzy; bool MovementStarted; uint32 m_uiBuubleChecker_Timer; uint32 m_uiWaterBoltVolley_Timer; uint32 m_uiShowup_Counter; uint32 m_uiVisible_Timer; uint32 m_uiHealth; void Reset() { if (!m_pInstance) return; DoCastSpellIfCan(m_creature, SPELL_PROTECTIVE_BUBBLE); m_bIsExploded = false; m_bIsFrenzy = false; MovementStarted = false; m_uiBuubleChecker_Timer = 1000; // m_uiDrained_Timer = 1000; m_uiVisible_Timer = 0; m_uiWaterBoltVolley_Timer = urand(5000, 10000); // m_uiShowup_Counter = 0; m_creature->SetVisibility(VISIBILITY_ON); m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); DespawnWaterElements(); } void JustReachedHome() { if (m_pInstance) { m_pInstance->SetData(TYPE_ICHORON, FAIL); m_pInstance->SetData(TYPE_EVENT, FAIL); m_pInstance->SetData(TYPE_RIFT, FAIL); if(m_pInstance->GetData(TYPE_PORTAL6) == IN_PROGRESS) {m_pInstance->SetData(TYPE_PORTAL6, NOT_STARTED);} else {m_pInstance->SetData(TYPE_PORTAL12, NOT_STARTED);} } } void Aggro(Unit* pWho) { if (!m_pInstance) return; DoScriptText(SAY_AGGRO, m_creature); m_pInstance->SetData(TYPE_ICHORON, IN_PROGRESS); SetCombatMovement(true); } void AttackStart(Unit* pWho) { if (!m_pInstance) return; if (m_pInstance->GetData(TYPE_ICHORON) != SPECIAL && m_pInstance->GetData(TYPE_ICHORON) != IN_PROGRESS) return; if (!pWho || pWho == m_creature) return; if (m_creature->Attack(pWho, true)) { m_creature->AddThreat(pWho); m_creature->SetInCombatWith(pWho); pWho->SetInCombatWith(m_creature); DoStartMovement(pWho); } } void WaterElementHit() { if (Creature* pIchoron = m_creature->GetMap()->GetCreature( m_pInstance->GetData64(DATA_ICHORON))) { if(pIchoron->isAlive()) { pIchoron->ModifyHealth( m_bIsRegularMode ? GLOBULE_HEAL : GLOBULE_HEAL_H); if (m_bIsExploded) { if(m_creature->HasAura(SPELL_DRAINED)) { m_creature->RemoveAurasByCasterSpell(SPELL_DRAINED,m_creature->GetGUID()); } m_creature->SetVisibility(VISIBILITY_ON); m_creature->GetMotionMaster()->MoveChase(m_creature->getVictim()); } } } } void JustSummoned(Creature* pSummoned) { pSummoned->SetSpeedRate(MOVE_RUN, 0.2f); pSummoned->GetMotionMaster()->MoveFollow(m_creature, 0, 0); pSummoned->CastSpell(pSummoned, SPELL_WATER_GLOBULE, false); m_lWaterElementsGUIDList.push_back(pSummoned->GetGUID()); } void DespawnWaterElements() { if (m_lWaterElementsGUIDList.empty()) return; for(std::list<uint64>::iterator itr = m_lWaterElementsGUIDList.begin(); itr != m_lWaterElementsGUIDList.end(); ++itr) { if (Creature* pTemp = m_creature->GetMap()->GetCreature(*itr)) { if (pTemp->isAlive()) //pTemp->ForcedDespawn(); pTemp->DealDamage(pTemp, pTemp->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); } } m_lWaterElementsGUIDList.clear(); } void StartMovement(uint32 id) { m_creature->GetMotionMaster()->MovePoint(id, PortalLoc[id].x, PortalLoc[id].y, PortalLoc[id].z); m_creature->AddSplineFlag(SPLINEFLAG_WALKMODE); m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); MovementStarted = true; m_creature->SetInCombatWithZone(); } void MovementInform(uint32 type, uint32 id) { if (type != POINT_MOTION_TYPE || !MovementStarted || m_creature->GetVisibility() == VISIBILITY_OFF ) return; if (id == 0) { MovementStarted = false; m_creature->GetMotionMaster()->MovementExpired(); SetCombatMovement(true); m_creature->SetInCombatWithZone(); } } void UpdateAI(const uint32 uiDiff) { if (m_pInstance->GetData(TYPE_ICHORON) == SPECIAL && !MovementStarted) StartMovement(0); //Return since we have no target if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (!m_bIsFrenzy) { if (m_uiBuubleChecker_Timer < uiDiff) { if(!m_creature->HasAura(SPELL_PROTECTIVE_BUBBLE) && m_creature->GetVisibility() == VISIBILITY_ON && m_bIsExploded) { DoCastSpellIfCan(m_creature, SPELL_PROTECTIVE_BUBBLE); DoScriptText(SAY_BUBBLE, m_creature); m_bIsExploded = false; m_uiBuubleChecker_Timer = 3000; } if(!m_creature->HasAura(SPELL_PROTECTIVE_BUBBLE) && m_creature->GetVisibility() == VISIBILITY_ON && !m_bIsExploded) { DoCastSpellIfCan(m_creature->getVictim(), m_bIsRegularMode ? SPELL_WATER_BLAST : SPELL_WATER_BLAST_H); for(uint8 i = 0; i < 10; i++) { int tmp = urand(0, 5); m_creature->SummonCreature(NPC_ICHOR_GLOBULE, PortalLoc[tmp].x, PortalLoc[tmp].y, PortalLoc[tmp].z, 0, TEMPSUMMON_CORPSE_DESPAWN, 0); } DoScriptText(EMOTE_ICHORON_PROTECTIVE_BUBBLE, m_creature); //DoScriptText(SAY_SHATTER, m_creature); m_creature->DealDamage(m_creature, m_creature->GetMaxHealth()*0.25, NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); m_creature->SetVisibility(VISIBILITY_OFF); m_bIsExploded = true; m_uiVisible_Timer = 15000; } } else m_uiBuubleChecker_Timer -= uiDiff; if(m_creature->GetVisibility() == VISIBILITY_OFF && m_uiVisible_Timer < uiDiff) { m_creature->SetVisibility(VISIBILITY_ON); m_uiVisible_Timer = 3000; } else m_uiVisible_Timer -= uiDiff; } if (m_creature->GetVisibility() == VISIBILITY_OFF && !m_creature->HasAura(SPELL_DRAINED) ) { DoCastSpellIfCan(m_creature, SPELL_DRAINED); } if (m_creature->GetVisibility() == VISIBILITY_ON ) { if (m_uiWaterBoltVolley_Timer < uiDiff) { DoCastSpellIfCan(m_creature, m_bIsRegularMode ? SPELL_WATER_BOLT_VOLLEY : SPELL_WATER_BOLT_VOLLEY_H); m_uiWaterBoltVolley_Timer = urand(15000, 20000); } else m_uiWaterBoltVolley_Timer -= uiDiff; } if (!m_bIsFrenzy && (m_creature->GetHealth()*100 / m_creature->GetMaxHealth()) < 25) { DoCastSpellIfCan(m_creature, m_bIsRegularMode ? SPELL_FRENZY : SPELL_FRENZY_H); DoScriptText(SAY_ENRAGE, m_creature); if(m_creature->HasAura(SPELL_DRAINED)) { m_creature->RemoveAurasByCasterSpell(SPELL_DRAINED,m_creature->GetGUID()); } if(m_creature->GetVisibility() == VISIBILITY_OFF){m_creature->SetVisibility(VISIBILITY_ON);} m_bIsFrenzy = true; } DoMeleeAttackIfReady(); } void JustDied(Unit* pKiller) { DoScriptText(SAY_DEATH, m_creature); DespawnWaterElements(); if (m_pInstance){ m_pInstance->SetData(TYPE_ICHORON, DONE); if(m_pInstance->GetData(TYPE_PORTAL6) == IN_PROGRESS) {m_pInstance->SetData(TYPE_PORTAL6, DONE);} else {m_pInstance->SetData(TYPE_PORTAL12, DONE);} } if(m_creature->GetVisibility() == VISIBILITY_OFF) m_creature->SetVisibility(VISIBILITY_ON); } void KilledUnit(Unit* pVictim) { switch(urand(0, 2)) { case 0: DoScriptText(SAY_SLAY_1, m_creature);break; case 1: DoScriptText(SAY_SLAY_2, m_creature);break; case 2: DoScriptText(SAY_SLAY_3, m_creature);break; } } }; struct MANGOS_DLL_DECL mob_ichor_globuleAI : public ScriptedAI { mob_ichor_globuleAI(Creature *pCreature) : ScriptedAI(pCreature) { m_pInstance = ((ScriptedInstance*)pCreature->GetInstanceData()); Reset(); } ScriptedInstance *m_pInstance; uint32 m_uiRangeCheck_Timer; void Reset() { m_uiRangeCheck_Timer = 1000; } void AttackStart(Unit* pWho) { return; } void UpdateAI(const uint32 uiDiff) { if (m_uiRangeCheck_Timer < uiDiff) { if (m_pInstance) { if (Creature* pIchoron = m_creature->GetMap()->GetCreature( m_pInstance->GetData64(DATA_ICHORON))) { float fDistance = m_creature->GetDistance2d(pIchoron); if (fDistance <= 2) { ((boss_ichoronAI*)pIchoron->AI())->WaterElementHit(); m_creature->DealDamage(m_creature, m_creature->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); } } } m_uiRangeCheck_Timer = 1000; } else m_uiRangeCheck_Timer -= uiDiff; } void JustDied(Unit* pKiller) { DoCast(m_creature, SPELL_SPLASH); DoCast(m_creature, SPELL_WATER_GLOBULE_2); } }; CreatureAI* GetAI_boss_ichoron(Creature* pCreature) { return new boss_ichoronAI (pCreature); } CreatureAI* GetAI_mob_ichor_globule(Creature* pCreature) { return new mob_ichor_globuleAI (pCreature); } void AddSC_boss_ichoron() { Script *newscript; newscript = new Script; newscript->Name = "boss_ichoron"; newscript->GetAI = &GetAI_boss_ichoron; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "mob_ichor_globule"; newscript->GetAI = &GetAI_mob_ichor_globule; newscript->RegisterSelf(); }
33.444717
161
0.573979
mfooo
4dcd6ec36514d7849c44593803667225d30d0fb1
15,991
cpp
C++
CrowLeer/main.cpp
ERap320/CrowLeer
fa27beec0dba2c9ab28143067aaf02ba0dd25571
[ "0BSD" ]
20
2018-02-20T17:38:09.000Z
2020-12-05T11:52:22.000Z
CrowLeer/main.cpp
ERap320/CrowLeer
fa27beec0dba2c9ab28143067aaf02ba0dd25571
[ "0BSD" ]
null
null
null
CrowLeer/main.cpp
ERap320/CrowLeer
fa27beec0dba2c9ab28143067aaf02ba0dd25571
[ "0BSD" ]
2
2018-07-16T16:02:43.000Z
2019-07-26T18:55:21.000Z
#include <iostream> #include <thread> #include <fstream> //Other project headers #include "uri.hpp" #include "utils.hpp" #include "getopt.h" #define HELP_MSG "\ Fast and reliable CLI web crawler with focus on pages download\n\ For more information visit https://github.com/ERap320/CrowLeer\n\n\ >>USAGE: crowleer [options]\n\ \n\ >>OPTIONS:\n\ \t-h --help\t\tView this help page\n\ \t-u --url\t\tURL used to start crawling\n\ \t-t --thread\t\tNumber of threads used\n\ \t-d --depth\t\tMaximum crawling depth (the starting URL spcified in -u is at depth 0)\n\ \t-x --same-domain\tQuick flag to only follow URLs with the same domain as the starting URL,\n\t\t\t\toverrides the --f-domain option\n\ \t-S --save\t\tActivates the download functionality of CrowLeer. If not used nothing\n\t\t\t\twill be saved on the disk\n\ \t-o --output\t\tChoose a directory where the selected files will be saved. The default\n\t\t\t\tvalue is the current directory\n\ \t-l --log\t\tOutputs progress details to the specified log file. Works best if it's\n\t\t\t\tthe first specified option, as it makes possible to log further settings\n\t\t\t\tof the current job\n\ \t-e --exclude\t\tRule tested on the whole parsed URL, excludes the URL from the crawling\n\t\t\t\tand saving steps if matched\n\ \t-c --curl-opt\t\tName of the custom CURL option to use when downloading pages. Only to\n\t\t\t\tuse before the -p flag that specifies the parameter for the option.\n\t\t\t\tCan be used multiple times to set more than one option\n\ \t-p --curl-param\t\tValue of the custom CURL option specified before it with the -c flag\n\ \t-r --relative\t\tMake every URL in downloaded pages relative, so that you can seamlessly\n\t\t\t\tbrowse from the downloaded copy (Only works with -S)\n\ \t\n\ \t--f-global\t\tFollow rule to be tested on the whole parsed URL\t\t\n\ \t--f-protocol\t\tFollow rules on single parts of parsed URLs\n\ \t--f-domain\n\ \t--f-path\n\ \t--f-filename\n\ \t--f-extension\n\ \t--f-querystring\t\n\ \t--f-anchor\n\ \t\n\ \t--s-global\t\tSave rule to be tested on the whole parsed URL\t\t\n\ \t--s-protocol\t\tSave rules on single parts of parsed URLs\n\ \t--s-domain\n\ \t--s-path\n\ \t--s-filename\n\ \t--s-extension\n\ \t--s-querystring\n\ \t--s-anchor\n\ \n\ >>RULES:\n\ CrowLeer uses Regular Expressions (https://en.wikipedia.org/wiki/Regular_expression) to apply\nconditions to URLs or parts of URLs.\n\ Both rules have a global component, that matches the Completed URL (see the URL section) and one\nfor every URL part.\n\ There are two rules: Follow Rule and Save Rule.\n\ - Follow Rule: describes pages to follow while crawling\n\ - Save Rule: describes pages to download and save locally\n\ \n\ If not specified every rule is set to match everything. You can set every possible composition\nof rules to describe the exact scenario you need, including global rule and parts rules together.\n\ \n\ >>URLs:\n\ CrowLeer completes the URLs found in the crawled pages to make its and your work easier.\n\ Every URL is split in parts and completed with parts from the URL of the page it was found in\nif necessary.\n\ The parts in which a URL is split are: protocol, domain, path, filename, extension, querystring\nand anchor.\n\ \n\ Example: the URL \"/example/one/file.txt\" was found while running on \"https://erap.space\"\n\ \tThe Completed URL will be \"https://erap.space/example/one/file.txt\", and its parts will be:\n\ \t- protocol: \"https\"\n\ \t- domain: \"erap.space\"\n\ \t- path: \"example/one\"\n\ \t- filename: \"file\"\n\ \t- extension: \"txt\"\n\ \t- querystring: \"\"\n\ \t- anchor: \"\"\n\ \n\ Example: the URL \"https://en.wikipedia.org/wiki/Dog?s=canis#Origin\" will be split in parts this way:\n\ \t- protocol: \"https\"\n\ \t- domain: \"en.wikipedia.org\"\n\ \t- path: \"wiki/Dog\"\n\ \t- filename: \"\"\n\ \t- extension: \"\"\n\ \t- querystring: \"s=canis\"\n\ \t- anchor: \"Origin\"" using std::cin; using std::thread; using std::mutex; //Number of threads used for crawling, will be initialized with -t flag or after reading the flags unsigned int thrNum = 0; //Variables to initialize string url; unsigned int maxdepth = -1; //Set to the biggest int possible because of two's complement representation rule followCondition; //conditions to choose what to crawl rule saveCondition; //condition to choose what to download regex excludeCondition; //condition to exclude certain URLs, like a negative global follow condition bool save = false; //flag to activate the saving of files, changed with the -S option bool relativize = false; //flag to activate url relativization //String of the path where to save files string pathString; //Path of the log file set with -l string logPath; //Option struct used to store curl options until pushed curl_option temp_option; //Lock to access the threads' activity flags mutex flagsMutex; void doWork(unordered_set<string>& urls, queue<uri>& todo, uri base, bool* isActive, unsigned int thrId) { string url; string response; uri current; bool oktoread = true; bool workEnded = false; bool follow; bool download; fs::path directory; while (!workEnded) { follow = false; download = false; queueMutex.lock(); oktoread = !todo.empty(); if (oktoread) { current = todo.front(); if (current.check(followCondition)) //Other rules are checked before inserting in the todo queue { follow = true; url = current.toString(); download = save && current.check(saveCondition); consoleMutex.lock(); out << todo.size() << " >> "; special_out(url, download); out << " : " << current.depth << "\n"; consoleMutex.unlock(); } todo.pop(); flagsMutex.lock(); isActive[thrId] = true; flagsMutex.unlock(); } queueMutex.unlock(); //Save the file in the correct directory if (oktoread && (follow || download) ) { response = HTTPrequest(url); if (follow && (maxdepth == -1 || current.depth < maxdepth)) { crawl(response, urls, todo, save, excludeCondition, maxdepth, &current); } if (download) { directory = computePath(current, pathString); if (relativize) relativizeUrls(&response, current, followCondition, saveCondition, maxdepth); writeToDisk(response, directory); } } //We can close the thread only if work is completely done (no other thread is processing in addition to an empty queue) flagsMutex.lock(); { isActive[thrId] = false; if (oktoread) { workEnded = false; } else { workEnded = true; for (unsigned int i = 0; i < thrNum && workEnded; i++) workEnded = !isActive[i]; } } flagsMutex.unlock(); } } int main(int argc, char *argv[]) { out << "CrowLeer 2.0 by ERap320 [battistonelia@erap.space]\n\n"; //Used to initialize custom curl options map curl_options_init(); //Condition to use the -s flag bool sameDomain = false; //Variable for the command line options management char opt=0; //Default value of the saved files path fs::path directory; pathString = fs::current_path().string(); //Default value for the excludeCondition, not to match anything excludeCondition = "(?!)"; /* getopt_long stores the option index here. */ static struct option long_options[] = { { "help", no_argument, 0, 'h' }, { "url", required_argument, 0, 'u' }, { "threads", required_argument, 0, 't' }, { "depth", required_argument, 0, 'd' }, { "same-domain", required_argument, 0, 'x' }, { "save", required_argument, 0, 'S' }, { "output", required_argument, 0, 'o' }, { "log", required_argument, 0, 'l' }, { "exclude", required_argument, 0, 'e' }, { "replace", required_argument, 0, 'r' }, { "f-global", required_argument, 0, 'f' }, { "f-protocol", required_argument, 0, 'f' }, { "f-domain", required_argument, 0, 'f' }, { "f-path", required_argument, 0, 'f' }, { "f-filename", required_argument, 0, 'f' }, { "f-extension", required_argument, 0, 'f' }, { "f-querystring", required_argument, 0, 'f' }, { "f-anchor", required_argument, 0, 'f' }, { "s-global", required_argument, 0, 's' }, { "s-protocol", required_argument, 0, 's' }, { "s-domain", required_argument, 0, 's' }, { "s-path", required_argument, 0, 's' }, { "s-filename", required_argument, 0, 's' }, { "s-extension", required_argument, 0, 's' }, { "s-querystring", required_argument, 0, 's' }, { "s-anchor", required_argument, 0, 's' }, { "curl-opt", required_argument, 0, 'c' }, { "curl-param", required_argument, 0, 'p' }, { 0, 0, 0, 0 } }; while (opt != -1) { int option_index = 0; opt = getopt_long(argc, argv, "hu:xSo:l:e:rt:d:f:s:c:p:", long_options, &option_index); /* Detect the end of the options. */ if (opt == -1) break; switch (opt) { case 'h': { out << HELP_MSG << "\n"; return 0; break; } case 'u': { out << "Selected URL: " << optarg << "\n"; url.append(optarg); break; } case 't': { out << "Threads number: " << optarg << "\n"; thrNum = atoi(optarg); break; } case 'd': { out << "Maximum depth: " << optarg << "\n"; maxdepth = atoi(optarg); break; } case 'x': { sameDomain = true; out << "Same domain rule applied\n"; break; } case 'S': { save = true; out << "Activate Save rule applied\n"; break; } case 'o': { pathString.clear(); pathString.append(optarg); pathString = std::regex_replace(pathString, regex("\\*|\\?|\"|<|>|\\|"), ""); out << "Output directory for saved files changed to " << std::regex_replace(optarg, regex("\\*|\\?|\"|<|>|\\|"), "") << "\n"; break; } case 'l': { logPath = optarg; logPath = std::regex_replace(logPath, regex("\\*|\\?|\"|<|>|\\|"), ""); out.useLog(logPath); out << "Log file set to " << std::regex_replace(optarg, regex("\\*|\\?|\"|<|>|\\|"), "") << "\n"; break; } case 'e': { excludeCondition = optarg; out << "Exclude rule: " << optarg << "\n"; break; } case 'r': { relativize = true; out << "Relative URLs rule applied\n"; break; } case 'f': { if (long_options[option_index].name == "f-global") { followCondition.global = optarg; out << "Global Follow rule: " << optarg << "\n"; } else if (long_options[option_index].name == "f-protocol") { followCondition.protocol = optarg; out << "Protocol Follow rule: " << optarg << "\n"; } else if (long_options[option_index].name == "f-domain") { followCondition.domain = optarg; out << "Domain Follow rule: " << optarg << "\n"; } else if (long_options[option_index].name == "f-path") { followCondition.path = optarg; out << "Path Follow rule: " << optarg << "\n"; } else if (long_options[option_index].name == "f-filename") { followCondition.filename = optarg; out << "Filename Follow rule: " << optarg << "\n"; } else if (long_options[option_index].name == "f-extension") { followCondition.extension = optarg; out << "Extension Follow rule: " << optarg << "\n"; } else if (long_options[option_index].name == "f-querystring") { followCondition.querystring = optarg; out << "Querystring Follow rule: " << optarg << "\n"; } else if (long_options[option_index].name == "f-anchor") { followCondition.anchor = optarg; out << "Anchor Follow rule: " << optarg << "\n"; } break; } case 's': { if (long_options[option_index].name == "s-global") { saveCondition.global = optarg; out << "Global Save rule: " << optarg << "\n"; } else if (long_options[option_index].name == "s-protocol") { saveCondition.protocol = optarg; out << "Protocol save rule: " << optarg << "\n"; } else if (long_options[option_index].name == "s-domain") { saveCondition.domain = optarg; out << "Domain Save rule: " << optarg << "\n"; } else if (long_options[option_index].name == "s-path") { saveCondition.path = optarg; out << "Path Save rule: " << optarg << "\n"; } else if (long_options[option_index].name == "s-filename") { saveCondition.filename = optarg; out << "Filename Save rule: " << optarg << "\n"; } else if (long_options[option_index].name == "s-extension") { saveCondition.extension = optarg; out << "Extension Save rule: " << optarg << "\n"; } else if (long_options[option_index].name == "s-querystring") { saveCondition.querystring = optarg; out << "Querystring Save rule: " << optarg << "\n"; } else if (long_options[option_index].name == "s-anchor") { saveCondition.anchor = optarg; out << "Anchor Save rule: " << optarg << "\n"; } break; } case 'c': { if (!temp_option.name.empty()) { out << "Trying to set the " << optarg << "option without giving a parameter for " << temp_option.name << "\n"; return 0; } if (optcode.find(string(optarg)) == optcode.end()) { out << optarg << " is not a CURL option\n"; return 0; } if(curl_option_value(string(optarg))/10000 > 1 ) //See HTTPrequest definition in utils.cpp { out << "Unsupported custom CURL option " << optarg << ", please contact the developer at battistonelia@erap.space about this issue\n"; return 0; } temp_option.name = optarg; break; } case 'p': { if (temp_option.name.empty()) { out << "No option name specified before '" << optarg << "'\n"; return 0; } temp_option.parameter = optarg; options.push_back(temp_option); out << "CURL option: " << temp_option.name << "='" << temp_option.parameter << "'\n"; temp_option.name.clear(); temp_option.parameter.clear(); break; } case ':': { out << "Missing value for option -" << (char)optopt << "\n"; return 0; break; } case '?': default: return 0; } } if (optind < argc) { out << "Illegal non-option arguments: "; while (optind < argc) out << argv[optind++] << " "; out << "\n\n" << HELP_MSG << "\n"; return 0; } if (url.empty()) { out << "\n\n" << HELP_MSG << "\n"; return 0; } if (thrNum == 0) { thrNum = std::thread::hardware_concurrency(); out << "Threads number: " << thrNum << "\n"; } out << "\n"; url = validate(url); string response; //Contains HTTP response response = HTTPrequest(url); uri base(url); if (sameDomain) { followCondition.domain = std::regex_replace(base.domain, regex("\\."), "\\."); saveCondition.domain = followCondition.domain; } unordered_set<string> urls; //Hash table which contains the URLs found in the response queue<uri> todo; //Queue containing the urls left to crawl out << todo.size() << " >> "; special_out(url, save && base.check(saveCondition)); out << " : " << base.depth << "\n"; crawl(response, urls, todo, save, excludeCondition, maxdepth, &base); //Check if the starting url has to be saved if (save && base.check(saveCondition)) { directory = pathString; directory /= base.domain; directory /= base.path; if (!fs::exists(directory)) { try { fs::create_directories(directory); } catch(fs::filesystem_error e){ error_out( (string)e.what() + " : An error occurred while creating the output directory. Make sure the path is valid and check the folders' permissions"); return 1; } } if (base.filename.empty()) directory /= "index.html"; else directory /= base.filename + "." + base.extension; if (relativize) relativizeUrls(&response, base, followCondition, saveCondition, maxdepth); writeToDisk(response, directory); } thread* threads = new thread[thrNum]; bool* isActive = new bool[thrNum](); //Initialized to zero (false) for (unsigned int i = 0; i < thrNum; i++) { threads[i] = std::thread(doWork, std::ref(urls), std::ref(todo), base, isActive, i); } for (unsigned int i = 0; i < thrNum; i++) { threads[i].join(); } delete isActive; out << "\nCrawling completed\n"; return 0; }
29.234004
232
0.63517
ERap320
4dce47cfbd9557349dbc676c06b6a2480e3fec9b
9,022
inl
C++
thirdparty/antlr/cpp/antlr3commontreenodestream.inl
RuslanKorshunov/sc-machine
8cb79a818d4e4144843b26722ac67bd71515ddaf
[ "MIT" ]
2
2015-02-20T16:48:59.000Z
2015-03-14T11:37:40.000Z
thirdparty/antlr/cpp/antlr3commontreenodestream.inl
RuslanKorshunov/sc-machine
8cb79a818d4e4144843b26722ac67bd71515ddaf
[ "MIT" ]
19
2015-02-01T19:42:52.000Z
2016-10-27T15:59:55.000Z
thirdparty/antlr/cpp/antlr3commontreenodestream.inl
RuslanKorshunov/sc-machine
8cb79a818d4e4144843b26722ac67bd71515ddaf
[ "MIT" ]
23
2015-04-18T15:11:56.000Z
2021-12-21T14:43:22.000Z
ANTLR_BEGIN_NAMESPACE() template<class ImplTraits> CommonTreeNodeStream<ImplTraits>::CommonTreeNodeStream(ANTLR_UINT32 hint) { this->init(hint); } template<class ImplTraits> void CommonTreeNodeStream<ImplTraits>::init( ANTLR_UINT32 hint ) { m_root = NULL; m_adaptor = new TreeAdaptorType; // Create the node list map // if (hint == 0) hint = DEFAULT_INITIAL_BUFFER_SIZE; m_nodes.reserve( DEFAULT_INITIAL_BUFFER_SIZE ); m_p = -1; m_currentNode = NULL; m_previousNode = NULL; m_currentChildIndex = 0; m_absoluteNodeIndex = 0; m_lookAhead = NULL; m_lookAheadLength = 0; m_head = 0; m_tail = 0; m_uniqueNavigationNodes = false; m_isRewriter = false; CommonTokenType* token = new CommonTokenType(CommonTokenType::TOKEN_UP); token->set_tokText( "UP" ); m_UP.set_token( token ); token = new CommonTokenType(CommonTokenType::TOKEN_DOWN); token->set_tokText( "DOWN" ); m_DOWN.set_token( token ); token = new CommonTokenType(CommonTokenType::TOKEN_EOF); token->set_tokText( "EOF" ); m_EOF_NODE.set_token( token ); token = new CommonTokenType(CommonTokenType::TOKEN_INVALID); token->set_tokText( "INVALID" ); m_EOF_NODE.set_token( token ); } template<class ImplTraits> CommonTreeNodeStream<ImplTraits>::CommonTreeNodeStream( const CommonTreeNodeStream& ctn ) { m_root = ctn.m_root; m_adaptor = ctn.m_adaptor; m_nodes.reserve( DEFAULT_INITIAL_BUFFER_SIZE ); m_nodeStack = ctn.m_nodeStack; m_p = -1; m_currentNode = NULL; m_previousNode = NULL; m_currentChildIndex = 0; m_absoluteNodeIndex = 0; m_lookAhead = NULL; m_lookAheadLength = 0; m_head = 0; m_tail = 0; m_uniqueNavigationNodes = false; m_isRewriter = true; m_UP.set_token( ctn.m_UP.get_token() ); m_DOWN.set_token( ctn.m_DOWN.get_token() ); m_EOF_NODE.set_token( ctn.m_EOF_NODE.get_token() ); m_INVALID_NODE.set_token( ctn.m_INVALID_NODE.get_token() ); } template<class ImplTraits> CommonTreeNodeStream<ImplTraits>::CommonTreeNodeStream( TreeType* tree, ANTLR_UINT32 hint ) { this->init(hint); m_root = tree; } template<class ImplTraits> CommonTreeNodeStream<ImplTraits>::~CommonTreeNodeStream() { // If this is a rewrting stream, then certain resources // belong to the originating node stream and we do not // free them here. // if ( m_isRewriter != true) { delete m_adaptor; m_nodeStack.clear(); delete m_INVALID_NODE.get_token(); delete m_EOF_NODE.get_token(); delete m_DOWN.get_token(); delete m_UP.get_token(); } m_nodes.clear(); } template<class ImplTraits> typename CommonTreeNodeStream<ImplTraits>::TreeType* CommonTreeNodeStream<ImplTraits>::_LT(ANTLR_INT32 k) { if ( m_p == -1) { this->fillBufferRoot(); } if (k < 0) { return this->LB(-k); } else if (k == 0) { return &(m_INVALID_NODE); } // k was a legitimate request, // if (( m_p + k - 1) >= (ANTLR_INT32)(m_nodes.size())) { return &(m_EOF_NODE); } return m_nodes[ m_p + k - 1 ]; } template<class ImplTraits> typename CommonTreeNodeStream<ImplTraits>::TreeType* CommonTreeNodeStream<ImplTraits>::getTreeSource() { return m_root; } template<class ImplTraits> typename CommonTreeNodeStream<ImplTraits>::TreeAdaptorType* CommonTreeNodeStream<ImplTraits>::getTreeAdaptor() { return m_adaptor; } template<class ImplTraits> void CommonTreeNodeStream<ImplTraits>::set_uniqueNavigationNodes(bool uniqueNavigationNodes) { m_uniqueNavigationNodes = uniqueNavigationNodes; } template<class ImplTraits> typename CommonTreeNodeStream<ImplTraits>::StringType CommonTreeNodeStream<ImplTraits>::toString() { return this->toStringSS(m_root, NULL); } template<class ImplTraits> typename CommonTreeNodeStream<ImplTraits>::StringType CommonTreeNodeStream<ImplTraits>::toStringSS(TreeType* start, TreeType* stop) { StringType buf; this->toStringWork(start, stop, buf); return buf; } template<class ImplTraits> void CommonTreeNodeStream<ImplTraits>::toStringWork(TreeType* start, TreeType* stop, StringType& str) { ANTLR_UINT32 n; ANTLR_UINT32 c; StringStreamType buf; if (!start->isNilNode() ) { StringType text; text = start->toString(); if (text.empty()) { buf << ' '; buf << start->getType(); } else buf << text; } if (start == stop) { return; /* Finished */ } n = start->getChildCount(); if (n > 0 && ! start->isNilNode() ) { buf << ' '; buf << CommonTokenType::TOKEN_DOWN; } for (c = 0; c<n ; c++) { TreeType* child; child = start->getChild(c); this->toStringWork(child, stop, buf); } if (n > 0 && ! start->isNilNode() ) { buf << ' '; buf << CommonTokenType::TOKEN_UP; } str = buf.str(); } template<class ImplTraits> typename CommonTreeNodeStream<ImplTraits>::TreeType* CommonTreeNodeStream<ImplTraits>::get(ANTLR_INT32 k) { if( m_p == -1 ) { this->fillBufferRoot(); } return m_nodes[k]; } template<class ImplTraits> void CommonTreeNodeStream<ImplTraits>::replaceChildren(TreeType* parent, ANTLR_INT32 startChildIndex, ANTLR_INT32 stopChildIndex, TreeType* t) { if (parent != NULL) { TreeAdaptorType* adaptor; adaptor = this->getTreeAdaptor(); adaptor->replaceChildren(parent, startChildIndex, stopChildIndex, t); } } template<class ImplTraits> typename CommonTreeNodeStream<ImplTraits>::TreeType* CommonTreeNodeStream<ImplTraits>::LB(ANTLR_INT32 k) { if ( k==0) { return &(m_INVALID_NODE); } if ( (m_p - k) < 0) { return &(m_INVALID_NODE); } return m_nodes[ m_p - k ]; } template<class ImplTraits> void CommonTreeNodeStream<ImplTraits>::addNavigationNode(ANTLR_UINT32 ttype) { TreeType* node; node = NULL; if (ttype == CommonTokenType::TOKEN_DOWN) { if (this->hasUniqueNavigationNodes() == true) { node = this->newDownNode(); } else { node = &m_DOWN; } } else { if (this->hasUniqueNavigationNodes() == true) { node = this->newUpNode(); } else { node = &m_UP; } } // Now add the node we decided upon. // m_nodes.push_back(node); } template<class ImplTraits> typename CommonTreeNodeStream<ImplTraits>::TreeType* CommonTreeNodeStream<ImplTraits>::newDownNode() { TreeType* dNode; CommonTokenType* token; token = new CommonTokenType(CommonTokenType::TOKEN_DOWN); token->set_tokText("DOWN"); dNode = new TreeType(token); return &dNode; } template<class ImplTraits> typename CommonTreeNodeStream<ImplTraits>::TreeType* CommonTreeNodeStream<ImplTraits>::newUpNode() { TreeType* uNode; CommonTokenType* token; token = new CommonTokenType(CommonTokenType::TOKEN_UP); token->set_tokText("UP"); uNode = new TreeType(token); return &uNode; } template<class ImplTraits> bool CommonTreeNodeStream<ImplTraits>::hasUniqueNavigationNodes() const { return m_uniqueNavigationNodes; } template<class ImplTraits> ANTLR_UINT32 CommonTreeNodeStream<ImplTraits>::getLookaheadSize() { return m_tail < m_head ? (m_lookAheadLength - m_head + m_tail) : (m_tail - m_head); } template<class ImplTraits> void CommonTreeNodeStream<ImplTraits>::push(ANTLR_INT32 index) { m_nodeStack.push(m_p); // Save current index this->seek(index); } template<class ImplTraits> ANTLR_INT32 CommonTreeNodeStream<ImplTraits>::pop() { ANTLR_INT32 retVal; retVal = m_nodeStack.top(); m_nodeStack.pop(); this->seek(retVal); return retVal; } template<class ImplTraits> void CommonTreeNodeStream<ImplTraits>::reset() { if ( m_p != -1) { m_p = 0; } BaseType::m_lastMarker = 0; // Free and reset the node stack only if this is not // a rewriter, which is going to reuse the originating // node streams node stack // if (m_isRewriter != true) m_nodeStack.clear(); } template<class ImplTraits> void CommonTreeNodeStream<ImplTraits>::fillBufferRoot() { // Call the generic buffer routine with the root as the // argument // this->fillBuffer(m_root); m_p = 0; // Indicate we are at buffer start } template<class ImplTraits> void CommonTreeNodeStream<ImplTraits>::fillBuffer(TreeType* t) { bool nilNode; ANTLR_UINT32 nCount; ANTLR_UINT32 c; nilNode = m_adaptor->isNilNode(t); // If the supplied node is not a nil (list) node then we // add in the node itself to the vector // if (nilNode == false) { m_nodes.push_back(t); } // Only add a DOWN node if the tree is not a nil tree and // the tree does have children. // nCount = t->getChildCount(); if (nilNode == false && nCount>0) { this->addNavigationNode( CommonTokenType::TOKEN_DOWN); } // We always add any children the tree contains, which is // a recursive call to this function, which will cause similar // recursion and implement a depth first addition // for (c = 0; c < nCount; c++) { this->fillBuffer( m_adaptor->getChild(t, c)); } // If the tree had children and was not a nil (list) node, then we // we need to add an UP node here to match the DOWN node // if (nilNode == false && nCount > 0) { this->addNavigationNode(CommonTokenType::TOKEN_UP); } } ANTLR_END_NAMESPACE()
21.328605
132
0.707049
RuslanKorshunov
4dd2d2dc0abe25b085b6abc7f06f94be02a9a203
4,189
cpp
C++
osquery/config/parsers/tests/decorators_tests.cpp
msekletar/osquery
beca5e68e97c5ff411b082fe871c69edcba1e641
[ "BSD-3-Clause" ]
7
2018-03-12T10:52:37.000Z
2020-09-11T14:09:23.000Z
osquery/config/parsers/tests/decorators_tests.cpp
msekletar/osquery
beca5e68e97c5ff411b082fe871c69edcba1e641
[ "BSD-3-Clause" ]
1
2021-03-20T05:24:15.000Z
2021-03-20T05:24:15.000Z
osquery/config/parsers/tests/decorators_tests.cpp
Acidburn0zzz/osquery
1cedf8d57310b4ac3ae0a39fe33dce00699f4a3b
[ "BSD-3-Clause" ]
4
2018-03-12T10:52:40.000Z
2020-08-18T09:03:17.000Z
/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <gtest/gtest.h> #include <osquery/config.h> #include <osquery/flags.h> #include <osquery/registry.h> #include "osquery/config/parsers/decorators.h" #include "osquery/tests/test_util.h" namespace osquery { DECLARE_bool(disable_decorators); DECLARE_bool(decorations_top_level); class DecoratorsConfigParserPluginTests : public testing::Test { public: void SetUp() override { // Read config content manually. readFile(kTestDataPath + "test_parse_items.conf", content_); // Construct a config map, the typical output from `Config::genConfig`. config_data_["awesome"] = content_; Config::get().reset(); clearDecorations("awesome"); // Backup the current decorator status. decorator_status_ = FLAGS_disable_decorators; FLAGS_disable_decorators = true; } void TearDown() override { Config::get().reset(); FLAGS_disable_decorators = decorator_status_; } protected: std::string content_; std::map<std::string, std::string> config_data_; bool decorator_status_{false}; }; TEST_F(DecoratorsConfigParserPluginTests, test_decorators_list) { // Assume the decorators are disabled. Config::get().update(config_data_); auto parser = Config::getParser("decorators"); EXPECT_NE(parser, nullptr); // Expect the decorators to be disabled by default. QueryLogItem item; getDecorations(item.decorations); EXPECT_EQ(item.decorations.size(), 0U); } TEST_F(DecoratorsConfigParserPluginTests, test_decorators_run_load) { // Re-enable the decorators, then update the config. // The 'load' decorator set should run every time the config is updated. FLAGS_disable_decorators = false; Config::get().update(config_data_); QueryLogItem item; getDecorations(item.decorations); ASSERT_EQ(item.decorations.size(), 3U); EXPECT_EQ(item.decorations["load_test"], "test"); } TEST_F(DecoratorsConfigParserPluginTests, test_decorators_run_interval) { // Prevent loads from executing. FLAGS_disable_decorators = true; Config::get().update(config_data_); // Mimic the schedule's execution. FLAGS_disable_decorators = false; runDecorators(DECORATE_INTERVAL, 60); QueryLogItem item; item.epoch = 0L; item.counter = 0L; getDecorations(item.decorations); ASSERT_EQ(item.decorations.size(), 2U); EXPECT_EQ(item.decorations.at("internal_60_test"), "test"); std::string log_line; serializeQueryLogItemJSON(item, log_line); std::string expected = "{\"snapshot\":\"\",\"action\":\"snapshot\",\"name\":\"\"," "\"hostIdentifier\":\"\",\"calendarTime\":\"\",\"unixTime\":\"0\"," "\"epoch\":\"0\",\"counter\":\"0\"," "\"decorations\":{\"internal_60_test\":\"test\",\"one\":\"1\"}}\n"; EXPECT_EQ(log_line, expected); // Now clear and run again. clearDecorations("awesome"); runDecorators(DECORATE_INTERVAL, 60 * 60); QueryLogItem second_item; getDecorations(second_item.decorations); ASSERT_EQ(second_item.decorations.size(), 2U); } TEST_F(DecoratorsConfigParserPluginTests, test_decorators_run_load_top_level) { // Re-enable the decorators, then update the config. // The 'load' decorator set should run every time the config is updated. FLAGS_disable_decorators = false; // enable top level decorations for the test FLAGS_decorations_top_level = true; Config::get().update(config_data_); // make sure decorations object still exists QueryLogItem item; getDecorations(item.decorations); ASSERT_EQ(item.decorations.size(), 3U); EXPECT_EQ(item.decorations["load_test"], "test"); // searialize the QueryLogItem and make sure decorations go top level pt::ptree tree; auto status = serializeQueryLogItem(item, tree); std::string expected = "test"; std::string result = tree.get("load_test", "none"); EXPECT_EQ(result, expected); // disable top level decorations FLAGS_decorations_top_level = false; } }
31.02963
79
0.725949
msekletar
4dd3951c4f177ed1ac2a66ee8aa19eae333b3447
10,691
cpp
C++
utests/kwriter_tests.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
null
null
null
utests/kwriter_tests.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
null
null
null
utests/kwriter_tests.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
1
2021-08-20T16:15:01.000Z
2021-08-20T16:15:01.000Z
#include "catch.hpp" #include <dekaf2/kstream.h> #include <dekaf2/ktcpclient.h> #include <dekaf2/kunixstream.h> #include <dekaf2/ksslclient.h> #include <dekaf2/kfilesystem.h> #include <dekaf2/ktcpserver.h> #include <dekaf2/ksystem.h> using namespace dekaf2; namespace { KTempDir TempDir; } class KMyServer : public KTCPServer { public: using KTCPServer::KTCPServer; protected: // a simple echo KString Request(KString& sLine, Parameters& parameters) override { sLine += "\n"; return sLine; } }; #if defined(DEKAF2_HAS_CPP_14) && (defined(DEKAF2_NO_GCC) || (DEKAF2_GCC_VERSION >= 80000)) constexpr #endif KStringView sCert = R"(-----BEGIN CERTIFICATE----- MIIEpDCCAowCCQCjjdpjiU244jANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAls b2NhbGhvc3QwHhcNMTgxMDMwMTMwNjA4WhcNMTkxMDMwMTMwNjA4WjAUMRIwEAYD VQQDDAlsb2NhbGhvc3QwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCl Sy5eUHyAF14TbT713mYYozxG7Nj6twX2CbmrLkdpBPRgW/G35HPjiKlwr4D49I6t EjZyMF7hdH5GdXofGAlpT89emiMm5epZAoWEsqTpFpfJjbEf9a+SGzTrhRxlMtbJ FQyBIcN86bLmowAMIMfA1onCG/mQ5L5iO5s1KbNezH+vwhOlAn12/1ZkNQZwY8jO 3BWC5k2A0TSt0lPr+ZFzFcwJYKziOLKMVbiS4nB/37hI9AruczKppd1OWLqTTM+9 Eb13GzhCY1NDF/v80SVIZQt+P0KurZA/QMuTula/O4nYxZsjlRexuiDEJ1BHMr/t aV6Sf9kzeh35ntNSf2xf5geITYqwjHRgwXaINYSbYTBg65nWpXybW33meecVeQvD 0HtXsdnV2N+asx4W3Onu6swI4OTmTDQ8hSxqOXrf8ba8vIXlDLoqjbzNIKcALXRM cvw2T56s9G6xXKuRQAKou8edARLMDq2qjOTxo7Uy83EqkE2ZMWKx/PpbCG+gu9Gd YKlvr+Wb1T4vK6AvmCXiqgNxwpav2tf9Cji76QlHjx0RJQYvvBNsOlgO8cjtG+6u vRcI/obs3zjxIy7ZBHqTP86aDnUgbT90pAn8JVSP3Sd67ZVoJEsU0+eQYUoV7dGI J5uRMnHj4VNJvjq/5S4/YeX6sTGbXWIR11GX63VKhQIDAQABMA0GCSqGSIb3DQEB CwUAA4ICAQAFcxiEg7IK5s8Kvcwn6lFoOK0vu4AQ7J42LQz+ncgP+iNMXmZoJ6GX 08ZlG5TxWa7RhpfzOBzwn9XVJL3D/mu4in2Nipu7gdl1PNgZ01hFg+T+TnlrqU9P Qz0u/PBy4pQgkAZyr5NA7nY8QYD6SQRgFZb8orN3gGjhWEfKQnyWDrfey3bixTPA klF6PD6dHVaU3xa+NBZUC1kpob/lPdEI6AU/aNw4zguPve5czpmwWxRZdPD9lsSU bDpq3XIPbnWOod3lq3akr6qr8gsfQaPs50QqpGmsrIf4XlSpG9KwBD+3VjlMaINS vEav+f1pqfUls+MwQqRv6ThM8cevNUsqIUqmFxRfZ+SHNbyIebRvlhPDNuTWj3ZZ Xd3x0udeekxz2R9+suvFRknHzlTMZ+TidFoTrcC+C50QWfDSwmCYDxT5WLyJXG9D pEF3pzDMLgbIh+ChTKYZXXU1QYlNW2zzLe6vV7y6K7x9+GzdQsgQZv+I3QMd6hIH hn7dm5rlcyD0iB4Xv7lHqwh62+b3sA6c38JgtHQduNJmU8p/dMAsYz99F9yw3v6H QHvjFPcNWBZ32BrEzUeYmLaEGRNj22IWDYm1nu2x0pgkjtou9+HZgZTXPb078+8t CBw53UppWW98e2rXKWXTtU6rEL1ctGz135WgBrqmkJ58n2pjd4jLDQ== -----END CERTIFICATE----- )"; #if defined(DEKAF2_HAS_CPP_14) && (defined(DEKAF2_NO_GCC) || (DEKAF2_GCC_VERSION >= 80000)) constexpr #endif KStringView sKey = R"(-----BEGIN PRIVATE KEY----- MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQClSy5eUHyAF14T bT713mYYozxG7Nj6twX2CbmrLkdpBPRgW/G35HPjiKlwr4D49I6tEjZyMF7hdH5G dXofGAlpT89emiMm5epZAoWEsqTpFpfJjbEf9a+SGzTrhRxlMtbJFQyBIcN86bLm owAMIMfA1onCG/mQ5L5iO5s1KbNezH+vwhOlAn12/1ZkNQZwY8jO3BWC5k2A0TSt 0lPr+ZFzFcwJYKziOLKMVbiS4nB/37hI9AruczKppd1OWLqTTM+9Eb13GzhCY1ND F/v80SVIZQt+P0KurZA/QMuTula/O4nYxZsjlRexuiDEJ1BHMr/taV6Sf9kzeh35 ntNSf2xf5geITYqwjHRgwXaINYSbYTBg65nWpXybW33meecVeQvD0HtXsdnV2N+a sx4W3Onu6swI4OTmTDQ8hSxqOXrf8ba8vIXlDLoqjbzNIKcALXRMcvw2T56s9G6x XKuRQAKou8edARLMDq2qjOTxo7Uy83EqkE2ZMWKx/PpbCG+gu9GdYKlvr+Wb1T4v K6AvmCXiqgNxwpav2tf9Cji76QlHjx0RJQYvvBNsOlgO8cjtG+6uvRcI/obs3zjx Iy7ZBHqTP86aDnUgbT90pAn8JVSP3Sd67ZVoJEsU0+eQYUoV7dGIJ5uRMnHj4VNJ vjq/5S4/YeX6sTGbXWIR11GX63VKhQIDAQABAoICAE0C2BmtGjR7rqMSdREMizjT ZNQOqZE2EJrvMQgmSbMOUeVLMTViRPQvyfHscwSKvKa6I4/UJYCZS/P76+fsxQXB 33XODq6i1CqgWCDZMqg+lH2dfHbNev1xm5hXrkEgDJ4nJmpLls7t+yIls3HzG94m loxPiFkPmfwelVORmDaExMDYhVqN7HKyyEdrxRI8C2UFeShBsL5huk95/QumfTPH ZgbAegv0KovjrFkTEyMg0rV6rlUmauZLlu5XvKXAVdFbIJELp4yWxkYuOIMz1lEC cvZg9up3hwtRXwf2+0+hp7nNZ1iOsDln5Lg/MNHbPTyZqSxMUKABN1IDw6VeJNlR M/YF55Y/aNUBWYyiU677Y7pebGhTh1dAoGPXXP2iouh+NK5icF6DJrb5xI270mwT p0tl3UmfKaWo/7i44NM94Wtkme2emlQXBJBFW4AUsgCdLPUE5Wvgy84Ns3tQ9Mut NtLriBeoX4eszNwziDLj+ldnuoUX3H9PKV54T9xy+MXwMWAZbHYlCda5mgSJ80cb aA6T/k3q315b0tZwOgv5vrX/v4a61I8oqzBYHbbGwlLHpR8JQzXjsJ7Fd2x/3Opw fMbtlfidLOs7WyR72UgGwKlL36h4N9GLWWrZnRil7uDuJ91uPeIHyyL2ygocLWEM JMoYDW2M/zdA1bwxosWJAoIBAQDbtgOzTm6Is5a7V5iygrgK8gAUsDLm33IQdMde CwcgG6sJeH9ruoTZviP6eV9r6dLzDUX/Ou/JJ4Ijq7IE72XpBLe/O3xtP2r0/OGy EhZJbfOtXbQyd14rP/uIPBXOgsIcFV1YbJqj4RIEK9TDUFZMpf7wlDQIhumwYVsb V6f/1PzpmVudhVpycbee0GL5H7omREOXKukjY7UhZSh9bfejQPqIKIIZGQnY9fZx dJ5EwBYa2M5iQ2GgGw62nJQa7vyomyYHxSwHUOWPzkSavzMNWwzo0oPy9OnuYTHx MwgeCM7QBxO/wpnfdAmw9nYk3MsOg/15Z6RZ6IkT3IM83DSHAoIBAQDAmECxQunf aEh8887U4kCTaHftk6VjbmewFXE1PVp+sf6kqPZdCcLj4431OxkQC6E9n50o/XTB gCdEohcxKVTaW/zselSQUkw4YJ1+etgDodPGBnPhAJmruTEQPBiOwlkRD9SxBllB J2Dgrz6k9tNTsmixbpok1mxt3C0aMoJgn5skN4gRQ7yAj/gmZvJVR3HaXIzKx0w7 W9soYnjiVpPicm8g0Z4wrN1y2kxjTZfcsIUh81HZEDCoP8CaGGo+iAfl978guIWE a5zX6jmSA4OLw6SPoKGOlQRJUjONjV49c7gCPXMmw5wftaztpnmfY8WSVPmbD4XO 1TzFBngbHReTAoIBAErGBzxe1P9xHzti9HTMSBZxhdWEoc4w/YDcPX2kAyjKQctX VwYy1EPGkjgMVo1DZqeRPOFADZtH9uJs7IkBcI19LYvHkvEbRCtcZPNVdIBJC0VV Pp5uQX42qEQVLta5aZZlLv+I9pgPYTJKOH7AOJ6dX8ZAqfS89YsxlvAXRPWsZuaZ arSRTdblHLjP8t8WDSQ410f7Mpz4sgxLgRwu8Lh+xMTSBHTGMLPGAblbFwIO3XcF kjee9vqmOrurTjxcWWCIbMj4MaPLxFTMvkxsBdPlyN7zxjRJZdPbAEQ2Oez+0mO6 BN6eO//wXdv8BPlGq1SlVv6aZzSyDvTTd1afGsECggEBAItQFsuiaWYPGxA3lA9t seRvFwElYecwv5QhjohCXylyO46EIeFe5DjQK6mOHCz9HJ9ky9wQqtolh0IgNcJ7 8UMaczPjsTPMNBI74PDSj1rhPjzqAfxp4L7U8OabcfAiKScsWl/LBdkZUPx2B0xw tqC+Vvix1pJ7AGffckiW7LRT/3cNLEHAy6P7gDbXFMgXLAYWGEm+LChr43Ws9WBT 3BlbSYNl3ZW8FVu1CLh0MjuS/Fp4lWX8ThYGN52/t2qQH5Z7xSc4EmydIxET/pze KdN5q5mxSevHYxhee6gS8G5nPF1ycc9Cg7Z0RiiJ2UQweYPGL9+4NMROfuzOJycF vj0CggEAF0edFyA/WFg4Vxs5RBtOjIzHZ5Z2ry1LHViu5zMxQcvrAwtdTrgt0LmM qA4avnzHg7S3gLCSfivpX47np0xFlKt4Q6jyUliNZHAXg/Ocv8RRQp14h5YhG6Lp RVXAP0buVX8MjxTDITtJcPr/wTepltxRvE7YX9jX79CETHf6Ov6yJda4ZqFuZVLT 1bhLNx7JuWskIIB05MJwxfFjhgRO1smcMEjYXYfn5IpNlwmYd2fwPgixsdZs/+G9 +yQWd5RaFFIU4uwjA1hyVtP9577hTU/iDeuoZbKN5xdxCgOh+t39mlzZz2ZF5CIY ifGH2FR4yO/361j9D9X2h9uBgconDA== -----END PRIVATE KEY----- )"; TEST_CASE("KWriter") { kSetCWD("/tmp"); SECTION("Short write to file") { KString sLarge; sLarge += "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; KString sFile(kFormat("{}/short.txt", TempDir.Name())); KOutFile stream(sFile); stream.Write(sLarge); CHECK( stream.Good() == true ); stream.close(); CHECK ( kFileSize(sFile) == sLarge.size() ); } SECTION("Large write to file") { KString sLarge; sLarge.reserve(1*1024*1024); for (size_t ct = 0; ct < 1*1024*1024 / 80; ++ct) { sLarge += "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; } KString sFile(kFormat("{}large.txt", TempDir.Name())); KOutFile stream(sFile); stream.Write(sLarge); CHECK( stream.Good() == true ); stream.close(); CHECK ( kFileSize(sFile) == sLarge.size() ); } #ifndef DEKAF2_IS_WINDOWS SECTION("Short write to TCP socket") { KString sLarge; sLarge = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; KMyServer Server(43234, false, 5); Server.Start(5000, false); KTCPClient stream("localhost:43234", 5000); stream.Write(sLarge); stream.Write('\n'); stream.Flush(); CHECK( stream.KOutStream::Good() == true ); if (stream.KOutStream::Good()) { KString sRx; CHECK ( stream.ReadLine(sRx) == true ); CHECK ( sRx == sLarge ); } } SECTION("Large write to TCP socket") { KString sLarge; sLarge.reserve(1*1024*1024); for (size_t ct = 0; ct < 1*1024*1024 / 80; ++ct) { sLarge += "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; } KMyServer Server(43235, false, 5); Server.Start(5, false); KTCPClient stream("localhost:43235", 5); stream.Write(sLarge); stream.Write('\n'); stream.Flush(); CHECK( stream.KOutStream::Good() == true ); if (stream.KOutStream::Good()) { KString sRx; CHECK ( stream.ReadLine(sRx) == true ); CHECK ( sRx == sLarge ); } } #endif #ifndef DEKAF2_IS_WINDOWS SECTION("Short write to Unix socket") { KString sLarge; sLarge = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; KString sSocket; #ifdef DEKAF2_IS_OSX // OSX has a very narrow limit on unix socket file name length, // and a very long temp folder name, so we use just /tmp .. kSystem("rm -f /tmp/short.socket"); sSocket = "/tmp/short.socket"; #else sSocket = kFormat("{}/short.socket", TempDir.Name()); #endif KMyServer Server(sSocket, 5); Server.Start(5, false); KUnixStream stream(sSocket, 5); stream.Write(sLarge); stream.Write('\n'); stream.Flush(); CHECK( stream.KOutStream::Good() == true ); if (stream.KOutStream::Good()) { KString sRx; CHECK ( stream.ReadLine(sRx) == true ); CHECK ( sRx == sLarge ); } } SECTION("Large write to Unix socket") { KString sLarge; sLarge.reserve(1*1024*1024); for (size_t ct = 0; ct < 1*1024*1024 / 80; ++ct) { sLarge += "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; } KString sSocket; #ifdef DEKAF2_IS_OSX // OSX has a very narrow limit on unix socket file name length, // and a very long temp folder name, so we use just /tmp .. kSystem("rm -f /tmp/large.socket"); sSocket = "/tmp/large.socket"; #else sSocket = kFormat("{}/large.socket", TempDir.Name()); #endif KMyServer Server(sSocket, 5); Server.Start(5, false); KUnixStream stream(sSocket, 5); stream.Write(sLarge); stream.Write('\n'); stream.Flush(); CHECK( stream.KOutStream::Good() == true ); if (stream.KOutStream::Good()) { KString sRx; CHECK ( stream.ReadLine(sRx) == true ); CHECK ( sRx == sLarge ); } } #endif #ifndef DEKAF2_IS_WINDOWS SECTION("short write to TLS socket") { KString sLarge; sLarge = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; KMyServer Server(43236, true, 5); Server.SetSSLCertificates(sCert, sKey); Server.Start(5, false); KSSLClient stream("localhost:43236", 5, false); stream.Write(sLarge); stream.Write('\n'); stream.Flush(); CHECK( stream.KOutStream::Good() == true ); if (stream.KOutStream::Good()) { KString sRx; CHECK ( stream.ReadLine(sRx) == true ); CHECK ( sRx == sLarge ); } } SECTION("Large write to TLS socket") { KString sLarge; sLarge.reserve(1*1024*1024); for (size_t ct = 0; ct < 1*1024*1024 / 80; ++ct) { sLarge += "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; } KMyServer Server(43237, true, 5); Server.SetSSLCertificates(sCert, sKey); Server.Start(5, false); KSSLClient stream("localhost:43237", 5, false); stream.Write(sLarge); stream.Write('\n'); stream.Flush(); CHECK( stream.KOutStream::Good() == true ); if (stream.KOutStream::Good()) { KString sRx; CHECK ( stream.ReadLine(sRx) == true ); CHECK ( sRx == sLarge ); } } #endif }
31.913433
96
0.806005
ridgeware
4dddb10066c76f079a845fd30c0c32252d65e02a
6,296
cpp
C++
src/ActiveBSP/src/Actor.cpp
fbaude/activebsp
d867d74e58bde38cc0f816bcb23c6c41a5bb4f81
[ "BSD-3-Clause" ]
null
null
null
src/ActiveBSP/src/Actor.cpp
fbaude/activebsp
d867d74e58bde38cc0f816bcb23c6c41a5bb4f81
[ "BSD-3-Clause" ]
null
null
null
src/ActiveBSP/src/Actor.cpp
fbaude/activebsp
d867d74e58bde38cc0f816bcb23c6c41a5bb4f81
[ "BSD-3-Clause" ]
null
null
null
#include "Actor.h" #include <iostream> #include <algorithm> #include <utility> #include <string.h> #include "SyntaxHelper.h" #include "actormsg/GetResultPartsMessage.h" #include "actormsg/StoreResultMessage.h" #include "log.h" #include "future/FutureKeyManager.h" #define BROADCASTDV_OPT 0 namespace activebsp { ActorBase::ActorBase() { _bsplib = SyntaxHelper::getInstance()->getActorBSPlib(); _actorComm = SyntaxHelper::getInstance()->getComm(); _intraActorComm = SyntaxHelper::getInstance()->getIntraActorComm(); register_spmd(&ActorBase::bsp_sync); _next_spmd_function_id = -1; bsp_push_reg(&_next_spmd_function_id, sizeof(int)); _dv_buf_nelems = 0; bsp_push_reg(&_dv_buf_nelems, sizeof(int)); bsp_sync(); } void ActorBase::setMasterProxy(const std::shared_ptr<MasterProxy> & masterProxy) { _masterProxy = masterProxy; } void ActorBase::call_spmd(int function_id) { if (_spmd_functions.size()) { _spmd_functions[function_id](); } else { std::cerr << "Received unknown slave message : " << function_id << std::endl; } } void ActorBase::kill_slaves() { int destroy_id = 0; _intraActorComm->sendSPMDFunctionID(destroy_id); } bool ActorBase::is_master() { return bsp_pid() == 0; } void ActorBase::setRequestId(int reqId) { _reqId = reqId; } int ActorBase::getRequestId() const { return _reqId; } int ActorBase::getNPendingRequests() { return _masterProxy->getNPendingRequests(); } void ActorBase::run_function_id(int id) { int send_id = id + 1; _intraActorComm->sendSPMDFunctionID(send_id); _spmd_functions[id](); } vector_distribution_base * ActorBase::prepare_distr_result(int nparts) { _cur_vector_distribution = vector_distribution_base(nparts); _cur_vector_distribution_part_size = 0; bsp_push_reg(_cur_vector_distribution.getBuf(), _cur_vector_distribution.getBufSize()); bsp_sync(); return &_cur_vector_distribution; } void ActorBase::register_result_part(int ipart, int resid, size_t size, size_t offset) { _cur_vector_distribution.register_part(ipart, _actorComm->pid(), resid, size, offset); } void ActorBase::store_vector_distribution(vector_distribution_base && dv) { _RequestDistrVectors.emplace(std::make_pair(_reqId, dv)); } void ActorBase::free_vector_distribution(int reqId) { _RequestDistrVectors.erase(reqId); } int ActorBase::store_result(const char * buf, size_t size) { LOG_TRACE("Storing result of size %zu", size); int key = FutureKeyManager::getInstance()->takeKey(); START_MEASURE(1); _actorComm->store_result(key, buf, size); END_MEASURE(1); LOG_MEASURE(1, "Storing result"); return key; } void ActorBase::register_single_part_result(const char * data, size_t size, size_t offset) { int resid = store_result(data, size); prepare_distr_result(1); register_result_part(0, resid, size, offset); } std::vector<char> ActorBase::get_part(const vector_distribution_base & dv, size_t offset, size_t size) { std::vector<char> vec(size); get_part(dv, offset, &vec[0], size); return vec; } void ActorBase::broadcast_dv(vector_distribution_base & dv) { int dv_buf_nelems_old = _dv_buf_nelems; int dv_buf_new = dv.nparts(); if (bsp_pid() == 0) { if (BROADCASTDV_OPT && dv_buf_nelems_old == dv_buf_new && dv_buf_nelems_old != 0) { for (int i = 0; i < bsp_nprocs(); ++i) { bsp_put(i, dv.getBuf(), &_dv_buf[0], 0, dv.getBufSize()); } } else { for (int i = 0; i < bsp_nprocs(); ++i) { bsp_put(i, &dv_buf_new, &_dv_buf_nelems, 0, sizeof(int)); } } } bsp_sync(); if (BROADCASTDV_OPT && dv_buf_nelems_old == _dv_buf_nelems && dv_buf_nelems_old != 0) { if (bsp_pid() != 0) { dv = vector_distribution_base(_dv_buf_nelems); memcpy(&_dv_buf[0], dv.getBuf(), dv.getBufSize()); } } else { if (bsp_pid() != 0) { dv = vector_distribution_base(_dv_buf_nelems); } if (_dv_buf.size() < dv.getBufSize()) { if (_dv_buf.size() != 0) { bsp_pop_reg(&_dv_buf[0]); } _dv_buf.resize(dv.getBufSize()); bsp_push_reg(&_dv_buf[0], dv.getBufSize()); bsp_sync(); } if (bsp_pid() == 0) { memcpy(&_dv_buf[0], dv.getBuf(), dv.getBufSize()); } else { bsp_get(0, &_dv_buf[0], 0, dv.getBuf(), dv.getBufSize()); } bsp_sync(); } } void ActorBase::get_part(const vector_distribution_base & dv, size_t offset, char * out_buf, size_t size) { _actorComm->dv_get_part(dv, offset, out_buf, size); } void ActorBase::bsp_seq_sync() { bsp_run(&ActorBase::bsp_sync); } int ActorBase::bsp_nprocs () { return _bsplib->nprocs(); } int ActorBase::bsp_pid () { return _bsplib->pid(); } double ActorBase::bsp_time () { return _bsplib->time(); } void ActorBase::bsp_sync() { _bsplib->sync(); } void ActorBase::bsp_send (int pid, const void *tag, const void *payload, size_t payload_nbytes) { _bsplib->send(pid, tag, payload, payload_nbytes); } void ActorBase::bsp_qsize (int * nmessages, size_t * accum_nbytes) { _bsplib->qsize(nmessages, accum_nbytes); } void ActorBase::bsp_get_tag (int * status , void * tag) { _bsplib->get_tag(status, tag); } void ActorBase::bsp_move (void *payload, size_t reception_nbytes) { _bsplib->move(payload, reception_nbytes); } void ActorBase::bsp_set_tagsize (size_t *tag_nbytes) { _bsplib->set_tagsize(tag_nbytes); } void ActorBase::bsp_push_reg (const void *ident, size_t size) { _bsplib->push_reg(ident, size); } void ActorBase::bsp_pop_reg (const void *ident) { _bsplib->pop_reg(ident); } void ActorBase::bsp_put (int pid, const void *src, void *dst, long int offset, size_t nbytes) { _bsplib->put(pid, src, dst, offset, nbytes); } void ActorBase::bsp_get (int pid, const void *src, long int offset, void *dst, size_t nbytes) { _bsplib->get(pid, src, offset, dst, nbytes); } } // namespace activebsp
22.326241
105
0.647872
fbaude
4dddd7f713a8f17cb86826201307aaf3f0d60e69
4,338
cc
C++
Source/BladeFramework/source/resource/SubFileDevice.cc
OscarGame/blade
6987708cb011813eb38e5c262c7a83888635f002
[ "MIT" ]
146
2018-12-03T08:08:17.000Z
2022-03-21T06:04:06.000Z
Source/BladeFramework/source/resource/SubFileDevice.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
1
2019-01-18T03:35:49.000Z
2019-01-18T03:36:08.000Z
Source/BladeFramework/source/resource/SubFileDevice.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
31
2018-12-03T10:32:43.000Z
2021-10-04T06:31:44.000Z
/******************************************************************** created: 2014/01/13 filename: SubFileDevice.cc author: Crazii purpose: *********************************************************************/ #include <BladePCH.h> #include "SubFileDevice.h" namespace Blade { ////////////////////////////////////////////////////////////////////////// SubFileDevice::SubFileDevice(const HFILEDEVICE& folder, const TString& subPath) :mParent(folder) ,mSubPath(TStringHelper::standardizePath(subPath)) { mLoaded = mParent->existDirectory(mSubPath); if( mLoaded ) mParent->getFullPath(mSubPath, mPathName); } ////////////////////////////////////////////////////////////////////////// SubFileDevice::~SubFileDevice() { this->unload(); } /************************************************************************/ /* IDevice interfaces */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// bool SubFileDevice::open() { mLoaded = mParent->isLoaded() && mParent->existDirectory(mPathName); if( mLoaded ) { mSubPath = mPathName; mParent->getFullPath(mSubPath, mPathName); } return mLoaded; } /************************************************************************/ /* IFileDevice interfaces */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// void SubFileDevice::getFullPath(const TString& subPath, TString& outFullPath) const noexcept { outFullPath = TStringHelper::standardizePath(mPathName + BTString("/") + subPath); } ////////////////////////////////////////////////////////////////////////// bool SubFileDevice::existFile(const TString& filepathname) const noexcept { return this->isLoaded() && mParent->existFile( mSubPath + BTString("/") + filepathname ); } ////////////////////////////////////////////////////////////////////////// HSTREAM SubFileDevice::openFile(const TString& filepathname,IStream::EAccessMode mode/* = IStream::AM_READ*/) const noexcept { if( this->isLoaded() ) return mParent->openFile( mSubPath + BTString("/") + filepathname, mode ); else return HSTREAM::EMPTY; } ////////////////////////////////////////////////////////////////////////// HSTREAM SubFileDevice::createFile(const TString& filepathname, IStream::EAccessMode mode) noexcept { if( this->isLoaded() ) return mParent->createFile( mSubPath + BTString("/") + filepathname, mode ); else return HSTREAM::EMPTY; } ////////////////////////////////////////////////////////////////////////// bool SubFileDevice::deleteFile(const TString& filepathname) noexcept { return this->isLoaded() && mParent->deleteFile( mSubPath + BTString("/") + filepathname ); } ////////////////////////////////////////////////////////////////////////// void SubFileDevice::findFile(TStringParam& result, const TString& pattern/* = BTString("*")*/, int findFlag/* = FF_DIR|FF_FILE*/) noexcept { if( this->isLoaded() ) { TStringParam temp; TString path = mSubPath + BTString("/"); mParent->findFile( temp, path + pattern, findFlag ); for(size_t i = 0; i < temp.size(); ++i) { const TString& str = temp[i]; assert( TStringHelper::isStartWith(str, path) ); result.push_back( str.substr( path.size() ) ) ; } } } ////////////////////////////////////////////////////////////////////////// bool SubFileDevice::createDirectory(const TString& name, bool bRecursive/* = false*/) { return this->isLoaded() && mParent->createDirectory( mSubPath + BTString("/") + name, bRecursive); } ////////////////////////////////////////////////////////////////////////// bool SubFileDevice::deleteDirectory(const TString& name) { return this->isLoaded() && mParent->deleteDirectory( mSubPath + BTString("/") + name ); } ////////////////////////////////////////////////////////////////////////// bool SubFileDevice::existDirectory(const TString& name) const noexcept { return this->isLoaded() && mParent->existDirectory( mSubPath + BTString("/") + name ); } }//namespace Blade
36.453782
141
0.454126
OscarGame
4de069685a286f4f08972302b98badd10a7c0f1a
2,582
cpp
C++
Plugins/org.mitk.m2.core.helper/src/m2SelectionProvider.cpp
jtfcordes/m2aia
62f8e9efe10365816c691888970ad306b7b7acd2
[ "BSD-3-Clause" ]
3
2020-12-01T19:20:49.000Z
2021-03-26T09:53:49.000Z
Plugins/org.mitk.m2.core.helper/src/m2SelectionProvider.cpp
jtfcordes/m2aia
62f8e9efe10365816c691888970ad306b7b7acd2
[ "BSD-3-Clause" ]
4
2020-11-26T07:56:04.000Z
2021-03-03T15:55:46.000Z
Plugins/org.mitk.m2.core.helper/src/m2SelectionProvider.cpp
jtfcordes/m2aia
62f8e9efe10365816c691888970ad306b7b7acd2
[ "BSD-3-Clause" ]
null
null
null
/*=================================================================== MSI applications for interactive analysis in MITK (M2aia) Copyright (c) Jonas Cordes. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or https://www.github.com/jtfcordes/m2aia for details. ===================================================================*/ #include "m2SelectionProvider.h" namespace m2 { SelectionProvider::SelectionProvider() : _selection(nullptr) {} void SelectionProvider::AddSelectionChangedListener(berry::ISelectionChangedListener *listener) { _selectionEvents.AddListener(listener); } void SelectionProvider::RemoveSelectionChangedListener(berry::ISelectionChangedListener *listener) { _selectionEvents.RemoveListener(listener); } berry::ISelection::ConstPointer SelectionProvider::GetSelection() const { return berry::ISelection::ConstPointer(_selection); } void SelectionProvider::SetSelection(const berry::ISelection::ConstPointer &selection) { _selection = berry::ISelection::ConstPointer(selection.GetPointer()); berry::SelectionChangedEvent::Pointer event( new berry::SelectionChangedEvent(berry::ISelectionProvider::Pointer(this), selection)); _selectionEvents.selectionChanged(event); } /*void SelectionProvider::SetNodeSelection(SelectionProvider::NodeSelection::ConstPointer selection) { if (_selection != selection) { _selection = selection; berry::SelectionChangedEvent::Pointer event( new berry::SelectionChangedEvent(berry::ISelectionProvider::Pointer(this), selection)); _selectionEvents.selectionChanged(event); } } void SelectionProvider::SetIonImageRefSelection( SelectionProvider::IonImageReferenceSelection::ConstPointer selection) { if (_selection != selection) { _selection = selection; berry::SelectionChangedEvent::Pointer event( new berry::SelectionChangedEvent(berry::ISelectionProvider::Pointer(this), selection)); _selectionEvents.selectionChanged(event); } } void SelectionProvider::SetOverViewSpectrumSelection( SelectionProvider::IonImageReferenceSelection::ConstPointer selection) { if (_selection != selection) { _selection = selection; berry::SelectionChangedEvent::Pointer event( new berry::SelectionChangedEvent(berry::ISelectionProvider::Pointer(this), selection)); _selectionEvents.selectionChanged(event); } }*/ } // namespace m2
31.487805
102
0.720372
jtfcordes
4de46485fa697d3fda61e5d40115ff42aa040310
703
cpp
C++
Loyalty/ApiServer/Service/Service.cpp
uno-labs-solana-hackathon/core-server
fdbdefd32e12fcaa19227f56154e0163c18a35cb
[ "Apache-2.0" ]
null
null
null
Loyalty/ApiServer/Service/Service.cpp
uno-labs-solana-hackathon/core-server
fdbdefd32e12fcaa19227f56154e0163c18a35cb
[ "Apache-2.0" ]
1
2021-03-06T11:38:01.000Z
2021-03-15T21:33:16.000Z
Loyalty/ApiServer/Service/Service.cpp
uno-labs-solana-hackathon/core-server
fdbdefd32e12fcaa19227f56154e0163c18a35cb
[ "Apache-2.0" ]
null
null
null
#include "Service.hpp" #include "ServiceMainTask.hpp" #include "CmdArgsDesc.hpp" #include "Configs/ServiceCfgDesc.hpp" namespace Sol::Loyalty::API::RPC { Service::Service (void): GpService("Solana loyalty API server"_sv) { } Service::~Service (void) noexcept { } GpArgBaseDesc::SP Service::CreateCmdLineArgsDesc (void) { return MakeSP<CmdArgsDesc>(); } GpServiceCfgBaseDesc::SP Service::CreateServiceCfgDesc (void) { return MakeSP<ServiceCfgDesc>(); } GpServiceMainTask::SP Service::CreateMainTask ( const GpArgBaseDesc& aCmdLineArgsDesc, GpServiceCfgBaseDesc::CSP aServiceCfgDesc ) { return MakeSP<ServiceMainTask>(aCmdLineArgsDesc, aServiceCfgDesc); } }//namespace Sol::Loyalty::API::RPC
19
67
0.769559
uno-labs-solana-hackathon
4e296dda42b9245effe98e938c0824e728ca7c1e
4,168
hpp
C++
2d/coords/MetricR2.hpp
danston/gbc
0cb1ae062919b053edc1558bdf41757460703eca
[ "MIT" ]
16
2016-12-06T10:35:46.000Z
2022-01-19T01:20:56.000Z
2d/coords/MetricR2.hpp
danston/gbc
0cb1ae062919b053edc1558bdf41757460703eca
[ "MIT" ]
1
2020-02-11T10:45:30.000Z
2021-03-12T11:08:03.000Z
2d/coords/MetricR2.hpp
danston/gbc
0cb1ae062919b053edc1558bdf41757460703eca
[ "MIT" ]
3
2018-05-10T14:34:35.000Z
2021-12-20T10:01:21.000Z
// Copyright Dmitry Anisimov danston@ymail.com (c) 2016-2017. // README: /* Metric coordinates. This class depends on: 1. BarycentricCoordinatesR2.hpp 2. SegmentCoordinatesR2.hpp 3. VertexExpressionsR2.hpp 4. VertexR2.hpp */ #ifndef GBC_METRICR2_HPP #define GBC_METRICR2_HPP // STL includes. #include <vector> #include <cassert> // Local includes. #include "../extra/VertexR2.hpp" #include "../extra/BarycentricCoordinatesR2.hpp" namespace gbc { // Metric coordinates in R2. class MetricR2 : public BarycentricCoordinatesR2 { public: // Constructor. MetricR2(const std::vector<VertexR2> &v, const double tol = 1.0e-10) : super(v, tol) { } // Return name of the coordinate function. inline std::string name() const { return "MetricR2"; } // Function that computes coordinates b at a point p. This implementation is based on the following paper: // K. Hormann and M. S. Floater. Mean value coordinates for arbitrary planar polygons. // ACM Transactions on Graphics, 25(4):1424-1441, 2006 (see Section 3). void compute(const VertexR2 &p, std::vector<double> &b) const { b.clear(); const size_t n = _v.size(); b.resize(n, 0.0); // Boundary. if (computeBoundaryCoordinates(p, b)) return; // Interior. std::vector<VertexR2> s(n); std::vector<VertexR2> e(n); std::vector<double> r(n); for (size_t i = 0; i < n; ++i) { const size_t ip = (i + 1) % n; s[i] = _v[i] - p; e[i] = _v[ip] - _v[i]; r[i] = s[i].length(); } std::vector<double> A(n); std::vector<double> B(n); std::vector<double> C(n); std::vector<double> q(n); for (size_t i = 0; i < n; ++i) { const size_t im = (i + n - 1) % n; const size_t ip = (i + 1) % n; A[i] = 0.5 * s[i].crossProduct(s[ip]); B[i] = 0.5 * s[im].crossProduct(s[ip]); C[i] = 0.5 * (e[i].crossProduct(-e[im])); q[i] = r[i] + r[ip] - e[i].length(); } std::vector<double> w(n); double W = 0.0; for (size_t i = 0; i < n; ++i) { const size_t imm = (i + n - 2) % n; const size_t im = (i + n - 1) % n; const size_t ip = (i + 1) % n; assert(fabs(q[imm] * q[im] * C[im]) > 0.0); assert(fabs(q[im] * q[i] * C[i]) > 0.0); assert(fabs(q[i] * q[ip] * C[ip]) > 0.0); w[i] = A[imm] / (q[imm] * q[im] * C[im]) - B[i] / (q[im] * q[i] * C[i]) + A[ip] / (q[i] * q[ip] * C[ip]); W += w[i]; } assert(fabs(W) > 0.0); const double invW = 1.0 / W; for (size_t i = 0; i < n; ++i) b[i] = w[i] * invW; } // Compute the coordinates at p using the internal storage from the VertexR2 class. inline void compute(VertexR2 &p) const { compute(p, p.b()); } // Compute coordinates bb at all points p in the vector. void compute(const std::vector<VertexR2> &p, std::vector<std::vector<double> > &bb) const { const size_t numP = p.size(); bb.resize(numP); for (size_t i = 0; i < numP; ++i) compute(p[i], bb[i]); } // Compute coordinates at all points p in the vector using the internal storage from the VertexR2 class. void compute(std::vector<VertexR2> &p) const { const size_t numP = p.size(); for (size_t i = 0; i < numP; ++i) compute(p[i], p[i].b()); } // Implementation of the virtual function to compute all coordinates. inline void bc(std::vector<VertexR2> &p) { compute(p); } private: // Some typedefs. typedef BarycentricCoordinatesR2 super; }; } // namespace gbc #endif // GBC_METRICR2_HPP
28.547945
121
0.495202
danston
4e2cf02c704662cfda8b7674dc2e0b58b6b53de4
504
cpp
C++
src/NodeEditor/Renderer/BoolPortRenderer.cpp
virusbear/CubiLightStudio
4c0c467c5e809f0dd0ba5bf79ba8d60b9a663b70
[ "Apache-2.0" ]
2
2022-01-29T12:48:18.000Z
2022-01-30T10:42:29.000Z
src/NodeEditor/Renderer/BoolPortRenderer.cpp
virusbear/CubiLightStudio
4c0c467c5e809f0dd0ba5bf79ba8d60b9a663b70
[ "Apache-2.0" ]
null
null
null
src/NodeEditor/Renderer/BoolPortRenderer.cpp
virusbear/CubiLightStudio
4c0c467c5e809f0dd0ba5bf79ba8d60b9a663b70
[ "Apache-2.0" ]
null
null
null
// // Created by Virusbear on 31.01.2022. // #include "NodeEditor/Renderer/BoolPortRenderer.h" #include "NodeEditor/PortData/BoolPortData.h" namespace CubiLight { Color BoolPortRenderer::GetPortColor(Port *port) { return {53, 150, 250, 180}; } PortShape BoolPortRenderer::GetPortShape(Port *port) { return PortShape::CircleFilled; } void BoolPortRenderer::Render(Port *port) { ImGui::Checkbox("##hidden", &((BoolPortData&)(port->GetData())).Value); } }
25.2
79
0.668651
virusbear
4e31012715eeaf302cf3c0e8fafd9c98971f0d8d
13,530
cpp
C++
src/render.cpp
mmacklin/tinsel
eabce7065ac26d9db590a6a9a45871fda5da7d6c
[ "Zlib" ]
316
2017-02-27T06:08:38.000Z
2022-03-30T17:02:44.000Z
src/render.cpp
mmacklin/tinsel
eabce7065ac26d9db590a6a9a45871fda5da7d6c
[ "Zlib" ]
4
2017-12-28T10:55:49.000Z
2021-07-30T05:30:04.000Z
src/render.cpp
mmacklin/tinsel
eabce7065ac26d9db590a6a9a45871fda5da7d6c
[ "Zlib" ]
24
2016-11-28T09:44:34.000Z
2021-12-27T16:09:01.000Z
#include "render.h" #include "intersection.h" #include "util.h" #include "sampler.h" #include "disney.h" //#include "lambert.h" #define kBsdfSamples 1.0f #define kProbeSamples 1.0f #define kRayEpsilon 0.0001f #define USE_LIGHT_SAMPLING 1 #define USE_SCENE_BVH 1 // trace a ray against the scene returning the closest intersection inline bool Trace(const Scene& scene, const Ray& ray, float& outT, Vec3& outNormal, const Primitive** outPrimitive) { #if USE_SCENE_BVH struct Callback { float minT; Vec3 closestNormal; const Primitive* closestPrimitive; Ray ray; const Scene& scene; Callback(const Scene& s, const Ray& r) : minT(REAL_MAX), closestPrimitive(NULL), ray(r), scene(s) { } void operator()(int index) { float t; Vec3 n, ns; const Primitive& primitive = scene.primitives[index]; if (PrimitiveIntersect(primitive, ray, t, &n)) { if (t < minT && t > 0.0f) { minT = t; closestPrimitive = &primitive; closestNormal = n; } } } }; Callback callback(scene, ray); QueryBVH(callback, scene.bvh.nodes, ray.origin, ray.dir); outT = callback.minT; outNormal = FaceForward(callback.closestNormal, -ray.dir); *outPrimitive = callback.closestPrimitive; return callback.closestPrimitive != NULL; #else // disgard hits closer than this distance to avoid self intersection artifacts float minT = REAL_MAX; const Primitive* closestPrimitive = NULL; Vec3 closestNormal(0.0f); for (Scene::PrimitiveArray::const_iterator iter=scene.primitives.begin(), end=scene.primitives.end(); iter != end; ++iter) { float t; Vec3 n, ns; const Primitive& primitive = *iter; if (PrimitiveIntersect(primitive, ray, t, &n)) { if (t < minT && t > 0.0f) { minT = t; closestPrimitive = &primitive; closestNormal = n; } } } outT = minT; outNormal = FaceForward(closestNormal, -ray.dir); *outPrimitive = closestPrimitive; return closestPrimitive != NULL; #endif } inline Vec3 SampleLights(const Scene& scene, const Primitive& surfacePrimitive, float etaI, float etaO, const Vec3& surfacePos, const Vec3& surfaceNormal, const Vec3& shadingNormal, const Vec3& wo, float time, Random& rand) { Vec3 sum(0.0f); if (scene.sky.probe.valid) { for (int i=0; i < kProbeSamples; ++i) { Vec3 skyColor; float skyPdf; Vec3 wi; ProbeSample(scene.sky.probe, wi, skyColor, skyPdf, rand); // check if occluded float t; Vec3 n; const Primitive* hit; if (Trace(scene, Ray(surfacePos + FaceForward(surfaceNormal, wi)*kRayEpsilon, wi, time), t, n, &hit) == false) { float bsdfPdf = BSDFPdf(surfacePrimitive.material, etaI, etaO, surfacePos, surfaceNormal, wo, wi); Vec3 f = BSDFEval(surfacePrimitive.material, etaI, etaO, surfacePos, surfaceNormal, wo, wi); if (bsdfPdf > 0.0f) { int N = kProbeSamples+kBsdfSamples; float cbsdf = kBsdfSamples/N; float csky = float(kProbeSamples)/N; float weight = csky*skyPdf/(cbsdf*bsdfPdf + csky*skyPdf); Validate(weight); if (weight > 0.0f) sum += weight*skyColor*f*Abs(Dot(wi, surfaceNormal))/skyPdf; } } } if (kProbeSamples > 0) sum /= float(kProbeSamples); } for (int i=0; i < scene.primitives.size(); ++i) { // assume all lights are area lights for now const Primitive& lightPrimitive = scene.primitives[i]; Vec3 L(0.0f); int numSamples = lightPrimitive.lightSamples; if (numSamples == 0) continue; for (int s=0; s < numSamples; ++s) { // sample light source Vec3 lightPos; Vec3 lightNormal; PrimitiveSample(lightPrimitive, time, lightPos, lightNormal, rand); Vec3 wi = lightPos-surfacePos; float dSq = LengthSq(wi); wi /= sqrtf(dSq); // check visibility float t; Vec3 n; const Primitive* hit; if (Trace(scene, Ray(surfacePos + FaceForward(surfaceNormal, wi)*kRayEpsilon, wi, time), t, n, &hit)) { float tSq = t*t; // if our next hit was further than distance to light then accept // sample, this works for portal sampling where you have a large light // that you sample through a small window const float kTolerance = 1.e-2f; if (fabsf(t - sqrtf(dSq)) <= kTolerance) { const float nl = Abs(Dot(lightNormal, wi)); // for glancing rays, note we use abs to include cases // where light surface is backfacing, e.g.: inside the weak furnace if (Abs(nl) < 1.e-6f) continue; // light pdf with respect to area and convert to pdf with respect to solid angle float lightArea = PrimitiveArea(lightPrimitive); float lightPdf = ((1.0f/lightArea)*tSq)/nl; // bsdf pdf for light's direction float bsdfPdf = BSDFPdf(surfacePrimitive.material, etaI, etaO, surfacePos, shadingNormal, wo, wi); Vec3 f = BSDFEval(surfacePrimitive.material, etaI, etaO, surfacePos, shadingNormal, wo, wi); Validate(bsdfPdf); Validate(f); // this branch is only necessary to exclude specular paths from light sampling // todo: make BSDFEval always return zero for pure specular paths and roll specular eval into BSDFSample() if (bsdfPdf > 0.0f) { // calculate relative weighting of the light and bsdf sampling int N = lightPrimitive.lightSamples+kBsdfSamples; float cbsdf = kBsdfSamples/N; float clight = float(lightPrimitive.lightSamples)/N; float weight = clight*lightPdf/(cbsdf*bsdfPdf + clight*lightPdf); Validate(lightPdf); Validate(weight); L += weight*f*hit->material.emission*(Abs(Dot(wi, shadingNormal))/Max(1.e-3f, lightPdf)); } } } } sum += L * (1.0f/numSamples); } return sum; } // reference, no light sampling, uniform hemisphere sampling Vec3 PathTrace(const Scene& scene, const Vec3& startOrigin, const Vec3& startDir, float time, int maxDepth, Random& rand) { // path throughput Vec3 pathThroughput(1.0f, 1.0f, 1.0f); // accumulated radiance Vec3 totalRadiance(0.0f, 0.0f, 0.0f); Vec3 rayOrigin = startOrigin; Vec3 rayDir = startDir; float rayTime = time; float rayEta = 1.0f; Vec3 rayAbsorption = 0.0f; BSDFType rayType = eReflected; float t = 0.0f; Vec3 n; const Primitive* hit; float bsdfPdf = 1.0f; for (int i=0; i < maxDepth; ++i) { // find closest hit if (Trace(scene, Ray(rayOrigin, rayDir, rayTime), t, n, &hit)) { float outEta; Vec3 outAbsorption; // index of refraction for transmission, 1.0 corresponds to air if (rayEta == 1.0f) { outEta = hit->material.GetIndexOfRefraction(); outAbsorption = Vec3(hit->material.absorption); } else { // returning to free space outEta = 1.0f; outAbsorption = 0.0f; } // update throughput based on absorption through the medium pathThroughput *= Exp(-rayAbsorption*t); // calculate new ray position const Vec3 p = rayOrigin + rayDir*t; #if USE_LIGHT_SAMPLING if (i == 0) { // first trace is our only chance to add contribution from directly visible light sources totalRadiance += hit->material.emission; } else if (kBsdfSamples > 0) { // area pdf that this dir was already included by the light sampling from previous step float lightArea = PrimitiveArea(*hit); if (lightArea > 0.0f) { // convert to pdf with respect to solid angle float lightPdf = ((1.0f/lightArea)*t*t)/Clamp(Dot(-rayDir, n), 1.e-3f, 1.0f); // calculate weight for bsdf sampling int N = hit->lightSamples+kBsdfSamples; float cbsdf = kBsdfSamples/N; float clight = float(hit->lightSamples)/N; float weight = cbsdf*bsdfPdf/(cbsdf*bsdfPdf+ clight*lightPdf); // specular paths have zero chance of being included by direct light sampling (zero pdf) if (rayType == eSpecular) weight = 1.0f; Validate(weight); // pathThroughput already includes the bsdf pdf totalRadiance += weight*pathThroughput*hit->material.emission; } } // integrate direct light over hemisphere totalRadiance += pathThroughput*SampleLights(scene, *hit, rayEta, outEta, p, n, n, -rayDir, rayTime, rand); #else // include emission from the new primitive totalRadiance += pathThroughput*hit->material.emission; #endif // terminate ray if we hit a light source if (hit->lightSamples) break; // integrate indirect light by sampling BRDF Vec3 u, v; BasisFromVector(n, &u, &v); Vec3 bsdfDir; BSDFType bsdfType; BSDFSample(hit->material, rayEta, outEta, p, u, v, n, -rayDir, bsdfDir, bsdfPdf, bsdfType, rand); if (bsdfPdf <= 0.0f) break; Validate(bsdfDir); Validate(bsdfPdf); // reflectance Vec3 f = BSDFEval(hit->material, rayEta, outEta, p, n, -rayDir, bsdfDir); Validate(f); // update ray medium if we are transmitting through the material if (Dot(bsdfDir, n) <= 0.0f) { rayEta = outEta; rayType = eTransmitted; rayAbsorption = outAbsorption; } else { rayType = eReflected; } // update throughput with primitive reflectance pathThroughput *= f * Abs(Dot(n, bsdfDir))/bsdfPdf; // update path direction rayType = bsdfType; rayDir = bsdfDir; rayOrigin = p + FaceForward(n, bsdfDir)*kRayEpsilon; } else { // hit nothing, sample sky dome and terminate float weight = 1.0f; if (scene.sky.probe.valid && i > 0 && rayType != eSpecular) { // probability that this dir was already sampled by probe sampling float skyPdf = ProbePdf(scene.sky.probe, rayDir); int N = kProbeSamples+kBsdfSamples; float cbsdf = kBsdfSamples/N; float csky = float(kProbeSamples)/N; weight = cbsdf*bsdfPdf/(cbsdf*bsdfPdf+ csky*skyPdf); } totalRadiance += weight*scene.sky.Eval(rayDir)*pathThroughput; break; } } return totalRadiance; } struct CpuRenderer : public Renderer { CpuRenderer(const Scene* s) : scene(s) { } const Scene* scene; Random rand; void AddSample(Color* output, int width, int height, float rasterX, float rasterY, float clamp, const Filter& filter, const Vec3& sample) { switch (filter.type) { case eFilterBox: { int startX = Max(0, int(rasterX - filter.width)); int startY = Max(0, int(rasterY - filter.width)); int endX = Min(int(rasterX + filter.width), width-1); int endY = Min(int(rasterY + filter.width), height-1); Vec3 c = ClampLength(sample, clamp); for (int x=startX; x <= endX; ++x) { for (int y=startY; y <= endY; ++y) { output[y*width+x] += Color(c, 1.0f); } } break; } case eFilterGaussian: { int startX = Max(0, int(rasterX - filter.width)); int startY = Max(0, int(rasterY - filter.width)); int endX = Min(int(rasterX + filter.width), width-1); int endY = Min(int(rasterY + filter.width), height-1); Vec3 c = ClampLength(sample, clamp); for (int x=startX; x <= endX; ++x) { for (int y=startY; y <= endY; ++y) { float w = filter.Eval(x-rasterX, y-rasterY); output[y*width+x] += Color(c*w, w); } } break; } }; } void Render(const Camera& camera, const Options& options, Color* output) { // create a sampler for the camera CameraSampler sampler( Transform(camera.position, camera.rotation), camera.fov, 0.001f, 1.0f, options.width, options.height); Random decorrelation; //for (int k=0; k < options.numSamples; ++k) { for (int j=0; j < options.height; ++j) { for (int i=0; i < options.width; ++i) { Vec3 origin; Vec3 dir; // generate a ray switch (options.mode) { case ePathTrace: { float x, y, t; Sample2D(rand, x, y); Sample1D(rand, t); float time = Lerp(camera.shutterStart, camera.shutterEnd, t); x += i; y += j; sampler.GenerateRay(x, y, origin, dir); Vec3 sample = PathTrace(*scene, origin, dir, time, options.maxDepth, rand); Validate(sample); AddSample(output, options.width, options.height, x, y, options.clamp, options.filter, sample); break; } case eNormals: { const float x = i;// + 0.5f; const float y = j;// + 0.5f; sampler.GenerateRay(x, y, origin, dir); const Primitive* p; float t; Vec3 n; if (Trace(*scene, Ray(origin, dir, 1.0f), t, n, &p)) { n = n*0.5f+0.5f; output[j*options.width+i] = Color(n.x, n.y, n.z, 1.0f); } else { output[j*options.width+i] = Color(0.0f); } break; } case eComplexity: { break; } } } } } } }; Renderer* CreateCpuRenderer(const Scene* s) { return new CpuRenderer(s); } struct NullRenderer : public Renderer { virtual ~NullRenderer() {} virtual void Init(int width, int height) {} virtual void Render(const Camera& c, const Options& options, Color* output) { memset(output, 0, options.width*options.height*sizeof(Color)); }; }; Renderer* CreateNullRenderer(const Scene* s) { return new NullRenderer(); }
24.555354
223
0.621212
mmacklin
4e3311978981f7778dfb9f95cbf02e9a28e0d0f8
496
cpp
C++
SVEngine/src/rendercore/SVResFBO.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
34
2018-09-28T08:28:27.000Z
2022-01-15T10:31:41.000Z
SVEngine/src/rendercore/SVResFBO.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
null
null
null
SVEngine/src/rendercore/SVResFBO.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
8
2018-10-11T13:36:35.000Z
2021-04-01T09:29:34.000Z
// // SVResFBO.cpp // SVEngine // Copyright 2017-2020 // yizhou Fu,long Yin,longfei Lin,ziyu Xu,xiaofan Li,daming Li // #include "SVResFBO.h" #include "../app/SVInst.h" #include "../work/SVTdCore.h" #include "SVRenderer.h" SVResFBO::SVResFBO(SVInst* _app) :SVRObjBase(_app){ m_uid = mApp->m_IDPool.applyUID(); } SVResFBO:: ~SVResFBO(){ mApp->m_IDPool.returnUID(m_uid); } void SVResFBO::create(SVRendererPtr _renderer){ } void SVResFBO::destroy(SVRendererPtr _renderer){ }
16.533333
62
0.691532
SVEChina
4e33599bb9350d8b5a4c3b147b03f8cfba58767f
103
cpp
C++
docs/tutorials/compile-and-link-cxx/src/library/hello_world.cpp
willmbaker/forge
99c39bf44d8ff875cefb68161b1306072f7f4cc9
[ "MIT" ]
9
2018-11-15T01:02:10.000Z
2021-12-10T07:57:18.000Z
docs/tutorials/compile-and-link-cxx/src/library/hello_world.cpp
willmbaker/forge
99c39bf44d8ff875cefb68161b1306072f7f4cc9
[ "MIT" ]
14
2018-08-15T08:39:49.000Z
2022-01-11T07:04:04.000Z
docs/tutorials/compile-and-link-cxx/src/library/hello_world.cpp
cwbaker/sweet_build_tool
afb675641a6dc88a4680fa6bc582a2ae1b1adc90
[ "MIT" ]
1
2020-11-16T00:06:22.000Z
2020-11-16T00:06:22.000Z
#include "hello_world.hpp" #include <stdio.h> void hello_world() { printf( "Hello World!\n" ); }
11.444444
31
0.640777
willmbaker
4e35405cfc6dbc45334cd8e45b5094563ce0ba81
11,686
cpp
C++
pwiz_tools/BiblioSpec/src/ShimadzuMLBReader.cpp
vagisha/pwiz
aa65186bf863cdebde3d15c293d137085365bead
[ "Apache-2.0" ]
null
null
null
pwiz_tools/BiblioSpec/src/ShimadzuMLBReader.cpp
vagisha/pwiz
aa65186bf863cdebde3d15c293d137085365bead
[ "Apache-2.0" ]
null
null
null
pwiz_tools/BiblioSpec/src/ShimadzuMLBReader.cpp
vagisha/pwiz
aa65186bf863cdebde3d15c293d137085365bead
[ "Apache-2.0" ]
null
null
null
// // $Id: ShimadzuMLBReader.cpp 9898 2016-07-13 22:38:39Z kaipot $ // // // Original author: Brian Pratt <bspratt@u.washington.edu> // Based on msfReader by Kaipo Tamura <kaipot@u.washington.edu> // // Copyright 2016 University of Washington - Seattle, WA 98195 // // 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 "ShimadzuMLBReader.h" namespace BiblioSpec { ShimadzuMLBReader::ShimadzuMLBReader(BlibBuilder& maker, const char* mlbFile, const ProgressIndicator* parent_progress) : BuildParser(maker, mlbFile, parent_progress), mlbName_(mlbFile), schemaVersion_(-1) { setSpecFileName(mlbFile, false); lookUpBy_ = INDEX_ID; // point to self as spec reader delete specReader_; specReader_ = this; } ShimadzuMLBReader::~ShimadzuMLBReader() { sqlite3_close(mlbFile_); specReader_ = NULL; // so the parent class doesn't try to delete itself // free spectra for (map<int, SpecData*>::iterator it = spectra_.begin(); it != spectra_.end(); ++it) { if (it->second != NULL) { delete it->second; it->second = NULL; } } } bool ShimadzuMLBReader::parseFile() { sqlite3_open(mlbName_, &mlbFile_); if (!mlbFile_) { throw BlibException(true, "Couldn't open '%s'.", mlbName_); } // Get the schema version sqlite3_stmt* statement = getStmt( "SELECT DBVer FROM PROPERTY"); if (hasNext(statement)) { string version = lexical_cast<string>(sqlite3_column_text(statement, 0)); sqlite3_finalize(statement); vector<string> versionPieces; boost::split(versionPieces, version, boost::is_any_of(".")); try { schemaVersion_ = lexical_cast<int>(versionPieces.front()); Verbosity::debug("Schema version is %d (%s)", schemaVersion_, version.c_str()); } catch (...) { Verbosity::error("Unknown schema version format: '%s'", version.c_str()); } } if (schemaVersion_ < 1) { Verbosity::error("Could not determine schema version."); } readMSMSSP(); // add psms by filename for (map< string, vector<PSM*> >::iterator iter = fileMap_.begin(); iter != fileMap_.end(); ++iter) { if (iter->second.size() > 0) { psms_.assign(iter->second.begin(), iter->second.end()); setSpecFileName(iter->first, false); buildTables(UNKNOWN_SCORE_TYPE, iter->first); } } return true; } vector<PSM_SCORE_TYPE> ShimadzuMLBReader::getScoreTypes() { return vector<PSM_SCORE_TYPE>(1, UNKNOWN_SCORE_TYPE); } double ShimadzuMLBReader::ReadDoubleFromBuffer(const char * & buf) { double result; char *p = reinterpret_cast<char *>(&result); for (int n = sizeof(double); n--;) *p++ = *buf++; return result; } const char * ShimadzuMLBReader::getAdduct(int adductType, int& charge) { const char *precursorAdduct; switch (adductType) // Per email from Shimadzu's Yutaro Yamamura to Brian Pratt { case 0x1: precursorAdduct = "[M+H]"; charge = 1; break; case 0x2: precursorAdduct = "[M+Na]"; charge = 1; break; case 0x4: precursorAdduct = "[M+K]"; charge = 1; break; case 0x8: precursorAdduct = "[M+NH4]"; charge = 1; break; case 0x10: // "other(+)" precursorAdduct = "[M+]"; charge = 1; break; case 0x20: precursorAdduct = "[M-H]"; charge = 1; break; case 0x40: precursorAdduct = "[M+HCOO]"; charge = 1; break; case 0x80: precursorAdduct = "[M+CH3COO]"; charge = 1; break; case 0x100: precursorAdduct = "[M+Cl]"; charge = 1; break; case 0x200: // "other(-)" precursorAdduct = "[M-]"; charge = 1; break; default: precursorAdduct = NULL; charge = 0; break; } if (precursorAdduct == NULL) { throw BlibException(false, "Unknown adduct type"); } return precursorAdduct; } void ShimadzuMLBReader::readMSMSSP() { int specCount = getRowCount("(SELECT DISTINCT SP_ID FROM MSMSSP WHERE MSStage IS 2)"); Verbosity::status("Parsing %d spectra.", specCount); ProgressIndicator progress(specCount); sqlite3_stmt* statement = getStmt( "SELECT SP_ID, RT, PrecursorMZ, SpecPeak, AdductType, CompForm, CompName, IUPACNo, CASNo, DataFilePath " "FROM MSMSSP " "WHERE SP_ID IN (SELECT DISTINCT SP_ID FROM MSMSSP WHERE MSStage IS 2)"); // turn each row of returned table into a spectrum while (hasNext(statement)) { SpecData* specData = new SpecData(); int specId = sqlite3_column_int(statement, 0); specData->id = specId; specData->retentionTime = sqlite3_column_double(statement, 1) / 60000.0; // convert msec to minutes specData->mz = sqlite3_column_int(statement, 2); const char* spectrum_ptr = static_cast<const char*>(sqlite3_column_blob(statement, 3)); size_t spectrumLen = sqlite3_column_bytes(statement, 3); specData->numPeaks = spectrumLen / (4 * sizeof(double)); specData->mzs = new double[specData->numPeaks]; specData->intensities = new float[specData->numPeaks]; int confirm_nPeaks = ReadDoubleFromBuffer(spectrum_ptr)/4; if (confirm_nPeaks != specData->numPeaks) { throw BlibException(false, "Inconsistent peak count"); } for (int n = 0; n < specData->numPeaks; n++) { specData->mzs[n] = ReadDoubleFromBuffer(spectrum_ptr); specData->intensities[n] = ReadDoubleFromBuffer(spectrum_ptr); spectrum_ptr += 2 * sizeof(double); } int adductType = sqlite3_column_int(statement, 4); int charge; curPSM_ = new PSM(); curPSM_->specKey = specId; curPSM_->specIndex = specId; curPSM_->smallMolMetadata.precursorAdduct = getAdduct(adductType, charge); curPSM_->charge = charge; curPSM_->smallMolMetadata.chemicalFormula = lexical_cast<string>(sqlite3_column_text(statement, 5)); curPSM_->smallMolMetadata.moleculeName = lexical_cast<string>(sqlite3_column_text(statement, 6)); curPSM_->smallMolMetadata.inchiKey = lexical_cast<string>(sqlite3_column_text(statement, 7)); string cas = lexical_cast<string>(sqlite3_column_text(statement, 8)); bal::replace_all(cas, " ", ""); // Example had random spaces in the CAS string if (!cas.empty()) { curPSM_->smallMolMetadata.otherKeys = "cas:" + cas; } string datafilepath = lexical_cast<string>(sqlite3_column_text(statement, 9)); if (datafilepath.empty()) datafilepath = "unknown"; fileMap_[datafilepath].push_back(curPSM_); // add spectrum to map spectra_[specId] = specData; spectraChargeStates_[specId] = charge; progress.increment(); } Verbosity::debug("Map has %d spectra", spectra_.size()); } /** * Prepares the given string as a SQLite query and verifies the return value. */ sqlite3_stmt* ShimadzuMLBReader::getStmt(const string& query) const { return getStmt(mlbFile_, query); } sqlite3_stmt* ShimadzuMLBReader::getStmt(sqlite3* handle, const string& query) { sqlite3_stmt* statement; if (sqlite3_prepare(handle, query.c_str(), -1, &statement, NULL) != SQLITE_OK) { throw BlibException("Cannot prepare SQL statement: %s ", sqlite3_errmsg(handle)); } return statement; } /** * Attempts to return the next row of the SQLite statement. Returns true on success. * Otherwise, finalize the statement and return false. */ bool ShimadzuMLBReader::hasNext(sqlite3_stmt* statement) { if (sqlite3_step(statement) != SQLITE_ROW) { sqlite3_finalize(statement); return false; } return true; } /** * Returns the number of records in the SQLite table. */ int ShimadzuMLBReader::getRowCount(string table) const { sqlite3_stmt* statement = getStmt("SELECT COUNT(*) FROM " + table); sqlite3_step(statement); int count = sqlite3_column_int(statement, 0); sqlite3_finalize(statement); return count; } // SpecFileReader methods /** * Implemented to satisfy SpecFileReader interface. Since spec and * results files are the same, no need to open a new one. */ void ShimadzuMLBReader::openFile(const char* filename, bool mzSort) {} void ShimadzuMLBReader::setIdType(SPEC_ID_TYPE type) {} /** * Return a spectrum via the returnData argument. If not found in the * spectra map, return false and leave returnData unchanged. */ bool ShimadzuMLBReader::getSpectrum(int identifier, SpecData& returnData, SPEC_ID_TYPE findBy, bool getPeaks) { map<int, SpecData*>::iterator found = spectra_.find(identifier); if (found == spectra_.end()) { return false; } SpecData* foundData = found->second; returnData = *foundData; return true; } /** * Only specific spectra can be accessed from the ShimadzuMLBReader. */ bool ShimadzuMLBReader::getSpectrum(string identifier, SpecData& returnData, bool getPeaks) { Verbosity::warn("ShimadzuMLBReader cannot fetch spectra by string identifier, " "only by spectrum index."); return false; } /** * Only specific spectra can be accessed from the ShimadzuMLBReader. */ bool ShimadzuMLBReader::getNextSpectrum(SpecData& returnData, bool getPeaks) { Verbosity::warn("ShimadzuMLBReader does not support sequential file reading."); return false; } }
35.737003
121
0.564265
vagisha
4e36e2446ad3bac76f11d899f7a584471b08d0ee
1,110
cpp
C++
ex2/code/chessboard/greedy/chessboard.cpp
dionyziz/ntua-algo
ed42637aef153f75a7d080170ff98369be90a5b3
[ "CC-BY-3.0", "Unlicense" ]
1
2015-11-21T20:21:02.000Z
2015-11-21T20:21:02.000Z
ex2/code/chessboard/greedy/chessboard.cpp
dionyziz/ntua-algo
ed42637aef153f75a7d080170ff98369be90a5b3
[ "CC-BY-3.0", "Unlicense" ]
null
null
null
ex2/code/chessboard/greedy/chessboard.cpp
dionyziz/ntua-algo
ed42637aef153f75a7d080170ff98369be90a5b3
[ "CC-BY-3.0", "Unlicense" ]
null
null
null
#include <cstdio> #include <cstdlib> using namespace std; struct field { int value; int x; int y; }; bool B[ 4 ][ 10000 ]; int N; int cmp( const void* a, const void* b ) { return ( ( const field* )b )->value - ( ( const field* )a )->value; } bool taken( int x, int y ) { if ( ( y + 1 < 4 && B[ y + 1 ][ x ] ) || ( y - 1 >= 0 && B[ y - 1 ][ x ] ) || ( x + 1 < N && B[ y ][ x + 1 ] ) || ( x - 1 >= 0 && B[ y ][ x - 1 ] ) ) { return true; } return false; } int main() { field A[ 40000 ]; int x, y, k = 0, profit = 0; scanf( "%i", &N ); for ( x = 0; x < N; ++x ) { for ( y = 0; y < 4; ++y ) { scanf( "%i", &A[ k ].value ); A[ k ].x = x; A[ k ].y = y; B[ y ][ x ] = false; ++k; } } qsort( A, 4 * N, sizeof( field ), cmp ); for ( k = 0; k < 4 * N; ++k ) { if ( !taken( A[ k ].x, A[ k ].y ) ) { profit += A[ k ].value; B[ A[ k ].y ][ A[ k ].x ] = true; } } printf( "%i\n", profit ); return 0; }
19.821429
71
0.353153
dionyziz
4e375c8fa235f172451df2b3ed504d281976e6ec
1,573
cpp
C++
leetcode/longest-word-in-dict.cpp
maximg/comp-prog
3d7a3e936becb0bc25b890396fa2950ac072ffb8
[ "MIT" ]
null
null
null
leetcode/longest-word-in-dict.cpp
maximg/comp-prog
3d7a3e936becb0bc25b890396fa2950ac072ffb8
[ "MIT" ]
null
null
null
leetcode/longest-word-in-dict.cpp
maximg/comp-prog
3d7a3e936becb0bc25b890396fa2950ac072ffb8
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/longest-word-in-dictionary/ #include <iostream> #include <unordered_map> #include <vector> #include <string> using namespace std; class Solution { struct Node { char c; unordered_map<char, Node*> children; bool isWord = false; }; string longest; Node root; public: string longestWord(vector<string>& words) { root.isWord = true; sort(words.begin(), words.end(), [](const string& a, const string& b){ return a.length() < b.length() || (a.length() == b.length() && a < b); }); for (auto w: words) check(w); return longest; } void check(const string& s) { Node *curP = &root; bool canMake = true; for (size_t i = 0; i < s.length(); ++i ) { Node& cur = *curP; const auto it = cur.children.find(s[i]); if (it == cur.children.end()) { Node* nn = new Node; nn->c = s[i]; nn->isWord = i+1 == s.length(); curP = cur.children[s[i]] = nn; } else curP = it->second; canMake = canMake && curP->isWord; } if (canMake && longest.length() < s.length()) longest = s; } }; int main() { vector<string> words = { "d","do","dog","p","pe","pen","peng","pengu","pengui","penguin","e","el","ele","elep","eleph","elepha","elephan","elephant" }; cout << Solution().longestWord(words) << endl; return 0; }
26.216667
155
0.492689
maximg
4e3fe2c07a623f5d81f1ddaabce46b60ca2b9c6d
288
cpp
C++
Google-Test-Poroject/Google Test Project/main.cpp
e-fever/qt-creator-project-wizards
0843d3e2213a961f0a4a99758fed46ddf369c7d9
[ "Apache-2.0" ]
16
2017-10-22T09:57:11.000Z
2021-11-28T03:07:24.000Z
Google-Test-Poroject/Google Test Project/main.cpp
e-fever/qt-creator-project-wizards
0843d3e2213a961f0a4a99758fed46ddf369c7d9
[ "Apache-2.0" ]
1
2018-02-07T21:48:30.000Z
2018-02-09T11:55:04.000Z
Google-Test-Poroject/Google Test Project/main.cpp
e-fever/qt-creator-project-wizards
0843d3e2213a961f0a4a99758fed46ddf369c7d9
[ "Apache-2.0" ]
4
2019-04-05T20:56:21.000Z
2021-07-01T08:35:39.000Z
#include <gtest/gtest.h> #include <QCoreApplication> TEST(%{ProjectName}ests, test_basic) { ASSERT_EQ(true, true); } int main(int argc, char** argv) { QCoreApplication app(argc, argv); Q_UNUSED(app); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
18
41
0.677083
e-fever
4e42b0971657066ed6b0d3dbc4417ad29328f641
1,266
cpp
C++
PathingLib/PathingLib/Path.cpp
woroniecki/PathingLib
f89d03b69e4fd92c55c1964d17a70744f10360bf
[ "MIT" ]
4
2017-10-13T02:49:19.000Z
2020-01-19T06:53:30.000Z
PathingLib/PathingLib/Path.cpp
woroniecki/PathingLib
f89d03b69e4fd92c55c1964d17a70744f10360bf
[ "MIT" ]
1
2017-09-02T10:26:56.000Z
2020-01-19T06:54:56.000Z
PathingLib/PathingLib/Path.cpp
woroniecki/PathingLib
f89d03b69e4fd92c55c1964d17a70744f10360bf
[ "MIT" ]
2
2017-10-13T02:49:09.000Z
2019-12-01T11:53:00.000Z
#include "stdafx.h" #include "Graph.h" #include "Utility.h" #include "Path.h" #include <fstream> #include <sstream> using namespace std; namespace PathingLib { Path::Path() {}; Path::Path(int targetIndex, int* nodes, Graph& g, int distance, int maxNodesAmount) { int nextNode = targetIndex; int nodesAmount = 0; while (nextNode != -1 || nodesAmount >= maxNodesAmount) { this->nodes.push_back(g.getNode(nextNode)); nextNode = nodes[nextNode]; nodesAmount++; } this->distance = distance; std::reverse(this->nodes.begin(), this->nodes.end()); } double Path::getDistance(char unit) { if (unit == 'k') return (double)distance / 100000.0; else if (unit == 'm') return (double)distance / 100.0; else if (unit == 'c') return (double)distance; return (double)distance; } int Path::getNodesAmount() { return nodes.size(); } void Path::saveToFileCSV(string filePath) { string tempLine = ""; ofstream file; file.open(filePath); for (int i = 0; i < nodes.size() - 1; i++) { tempLine = Utility::getLineString( nodes[i].latitude, nodes[i].longtitude, nodes[i + 1].latitude, nodes[i + 1].longtitude ); if (i < nodes.size() - 2) tempLine += "\n"; file << tempLine; } file.close(); } }
22.210526
86
0.634281
woroniecki
4e463cd9f4fbafed0ccde90f4dac9b3d1cf877b9
12,110
cpp
C++
R9M_Relay/src/R9M_Relay/CPPM.cpp
Andrey-Prikupets/RC
abda396e3f3947b1c394a2177281c06bd84fb3e3
[ "CC0-1.0" ]
11
2019-11-23T20:21:12.000Z
2022-01-17T11:19:38.000Z
R9M_Relay/src/R9M_Relay/CPPM.cpp
Andrey-Prikupets/RC
abda396e3f3947b1c394a2177281c06bd84fb3e3
[ "CC0-1.0" ]
1
2019-10-27T23:09:04.000Z
2019-10-27T23:09:04.000Z
R9M_Relay/src/R9M_Relay/CPPM.cpp
Andrey-Prikupets/RC
abda396e3f3947b1c394a2177281c06bd84fb3e3
[ "CC0-1.0" ]
1
2020-10-22T22:06:44.000Z
2020-10-22T22:06:44.000Z
#include "CPPM.h" //#include <avr/io.h> //#include <Arduino.h> //------------------------------------------------------------------------------ void iservos_reset(uint8_t fail_reason); //------------------------------------------------------------------------------ volatile uint16_t CPPM_T_W; // extended TCNT0 timer maintained by cycle function volatile uint16_t CPPM_T_X; // extended TCNT0 timer maintained by cycle function volatile uint16_t CPPM_T_T; // extended TCNT0 timer timeout volatile bool CPPM_T_cycling; // GPIOR0.0 = CPPM_T_cycle() in action, could be stopped by CPPM_T_interrupt() volatile bool CPPM_T_syncing; // GPIOR0.1 = CPPM sync falling edge detected volatile bool CPPM_T_checking; // GPIOR0.2 = CPPM check timeout //------------------------------------------------------------------------------ uint16_t CPPM_T_get() { uint16_t tcnt_x; cli(); tcnt_x = CPPM_T_X; sei(); return tcnt_x; } void CPPM_T_set(uint16_t tcnt_x) { cli(); CPPM_T_X = tcnt_x; sei(); } void CPPM_T_cycle() { CPPM_T_cycling = true; cli(); CPPM_T_W = TCNT1; sei(); cli(); if (CPPM_T_cycling) CPPM_T_X = CPPM_T_W; sei(); CPPM_T_cycling = false; } uint16_t CPPM_T_interrupt() { uint16_t tcnt_x; tcnt_x = ICR1; CPPM_T_X = tcnt_x; CPPM_T_W = tcnt_x; CPPM_T_cycling = false; return tcnt_x; } uint16_t CPPM_T_timeout() { uint16_t tcnt_x; cli(); tcnt_x = CPPM_T_X - CPPM_T_T; sei(); return tcnt_x; } void CPPM_T_check() { if (CPPM_T_checking && (uint8_t) (CPPM_T_timeout()>>8)==0) iservos_reset(CPPM_FAIL_T_CHECK); } void CPPM_T_setup() { ICR1 = TCNT0; // init the Input Capture Register OCR1A = TCNT0; // init the Output Compare Register // Configure timer1: disable PWM, set prescaler /8 (0.5 usec ticks) TCCR1A = (1<<COM1A0); // Toggle OC1A/OC1B on Compare Match. TCCR1B = (1<<ICNC1) | (0<<ICES1) | (1<<CS11); // falling edge TCCR1C = 0; CPPM_T_W = CPPM_T_X = TCNT0; // init CPPM_T_X } //------------------------------------------------------------------------------ void iservos_reset(uint8_t fail_reason) { // disable "pin change" interrupt from CPPM input frame... // cbi(PCMSK,PCINT4); bitClear(TIMSK1, ICIE1); // disable interrupt // cbi(GPIOR0,CPPM_T_syncing); // cbi(GPIOR0,CPPM_T_checking); CPPM_T_syncing = false; CPPM_T_checking = false; // PORTB = (PORTB & ~CPPM_PBMASK); // clear PWM channels CPPM.state = 0; if (fail_reason) CPPM.errors++; else CPPM.errors = 0; CPPM.fail_reason = fail_reason; CPPM.iservo = 0; CPPM.nservo = CPPM_MSERVO; CPPM.jservo = 0; // CPPM.kservo = 0; // enable "pin change" interrupt from CPPM input frame... // sbi(PCMSK,PCINT4); // Enable Timer1 input capture interrupt... TCCR1B = (1<<ICNC1) | (0<<ICES1) | (1<<CS11); // falling edge bitSet(TIFR1, ICF1); // clr pending interrupt bitSet(TIMSK1, ICIE1); // enable interrupt } void iservos_setup() { // Configure the input capture pin pinMode(CPPM_ICP1, INPUT_PULLUP); iservos_reset(CPPM_NO_FAIL); } void oservos_setup() { // Configure the output compare pin digitalWrite(CPPM_OC1A, HIGH); pinMode(CPPM_OC1A, OUTPUT); CPPM.oservo = 0; for (int i=0; i<CPPM_MSERVO; i++) CPPM.oservos[i] = CPPM_T_round(R615X_PULSE_CENTER); // start CPPM frame after 22ms... OCR1A += CPPM_T_round(R615X_FRAME_LENGTH); // Enable Timer1 output compare interrupt... bitSet(TIFR1, OCF1A); // clr pending interrupt bitSet(TIMSK1, OCIE1A); // enable interrupt CPPM.outputEnabled = true; } //------------------------------------------------------------------------------ //ISR(PCINT0_vect) ISR(TIMER1_CAPT_vect) { uint16_t tcnt0 = CPPM_T_interrupt(); // get time from extended TCNT0 timer // if (PB_tst(PB4)) // ? rising edge => end 300us synchro pulse if (TCCR1B & (1<<ICES1)) // rising edge => end 300us synchro pulse ? { TCCR1B = (1<<ICNC1) | (0<<ICES1) | (1<<CS11); // next falling edge // if (tbi(GPIOR0,CPPM_T_syncing)) // ? follow a start edge if (CPPM_T_syncing) // ? follow a start edge { // cbi(GPIOR0,CPPM_T_syncing); CPPM_T_syncing = false; CPPM.sync2 = tcnt0 - CPPM.time0; // compute width of synch pulse CPPM.time1 = tcnt0; CPPM._sync2[CPPM.iservo] = CPPM.sync2; // store sync width of current PWM servo pulse // if( CPPM.sync2 < CPPM_T_floor(FRSKY_PULSE_SYNC-10) || // CPPM.sync2 > CPPM_T_ceil(FRSKY_PULSE_SYNC+50) ) // check sync width... (FRSKY_PULSE_SYNC+20) is too short with R615X if( CPPM.sync2 < CPPM_PULSE_SYNC_MIN_FLOOR || CPPM.sync2 > CPPM_PULSE_SYNC_MAX_CEIL ) { iservos_reset(CPPM.sync2 < CPPM_PULSE_SYNC_MIN_FLOOR ? CPPM_FAIL_SYNC_PULSE_MIN : CPPM_FAIL_SYNC_PULSE_MAX); } else { if (CPPM.state==0) CPPM.state = 1; // 1st well formed sync pulse found. if (CPPM.state==1) // ? get pulse until gap pulse found { // CPPM_T_T = tcnt0 + CPPM_T_ceil(R615X_FRAME_NOTSYNC-FRSKY_PULSE_SYNC); // could be a stange frame if wait so long ! CPPM_T_T = CPPM.time5 + CPPM_FRAME_NOTSYNC_CEIL; // could be a stange frame if wait so long ! } else // : gap pulse found => start time of frame known. if (CPPM.state==2) // ? get pulses and compute nservo. { // CPPM_T_T = CPPM.time5 + CPPM_T_ceil(R615X_FRAME_NOTSYNC); // 2% max oscillator error CPPM_T_T = CPPM.time5 + CPPM_FRAME_NOTSYNC_CEIL; // set frame timeout } else // : check pulses and gap. { if (CPPM.iservo<CPPM.nservo) // CPPM_T_T = CPPM.time0 + CPPM_T_ceil(R615X_PULSE_CENTER+R615X_PULSE_C150PC); // middle stick+150% // CPPM_T_T = CPPM.time0 + CPPM_T_ceil(R615X_PULSE_CENTER+R615X_PULSE_C200PC); // middle stick+200% CPPM_T_T = CPPM.time0 + CPPM_PULSE_CENTER_PLUS_C200PC_CEIL; // middle stick+200% else // CPPM_T_T = CPPM.time5 + CPPM_T_ceil(R615X_FRAME_NOTSYNC); CPPM_T_T = CPPM.time5 + CPPM_FRAME_NOTSYNC_CEIL; } // sbi(GPIOR0,CPPM_T_checking); CPPM_T_syncing = true; } } } else // : falling edge => start 300us sync pulse and start PWM servo pulse. { TCCR1B = (1<<ICNC1) | (1<<ICES1) | (1<<CS11); // next rising edge // if (state==3) PORTB = (PORTB & ~CPPM_PBMASK) | (kservo & CPPM_PBMASK); // update PWM channels, stop current pulse, start next pulse CPPM._received = false; // sbi(GPIOR0,CPPM_T_syncing); CPPM_T_syncing = true; // CPPM_T_T = tcnt0 + CPPM_T_ceil(FRSKY_PULSE_SYNC+50); CPPM_T_T = tcnt0 + CPPM_PULSE_SYNC_MAX_CEIL; // sbi(GPIOR0,CPPM_T_checking); CPPM_T_checking = true; if (CPPM.state==0) { CPPM.time5 = CPPM.time0 = tcnt0; // set start time of next PWM servo pulse (and sync pulse) } else // : state>=1 { CPPM.puls3 = tcnt0 - CPPM.time0; // compute width of elapsed pulse CPPM.time0 = tcnt0; // set start time of next PWM servo pulse (and sync pulse) CPPM._puls3[CPPM.iservo] = CPPM.puls3; // store width of servo pulse int puls3i = ((signed) CPPM.puls3 - R615X_PULSE_CENTER) / 4; // middle centered servo pulse // int puls3i = (signed) CPPM.puls3 / 4 - (CPPM.sync2 + CPPM.sync2/4); // middle centered servo pulse if (puls3i > 127) puls3i = 127; else if (puls3i < -128) puls3i= -128; CPPM._puls3i8[CPPM.iservo] = puls3i; // if (CPPM.puls3 < CPPM_T_floor(R615X_PULSE_CENTER-R615X_PULSE_C150PC)) // too short servo pulse (middle stick-150%) ? // if (CPPM.puls3 < CPPM_T_floor(R615X_PULSE_CENTER-R615X_PULSE_C200PC)) // too short servo pulse (middle stick-200%) ? if (CPPM.puls3 < CPPM_PULSE_CENTER_MINUS_C200PC_FLOOR) // too short servo pulse (middle stick-200%) ? { iservos_reset(CPPM_FAIL_SERVO_PULSE_MIN); } else // if (CPPM.puls3 > CPPM_T_ceil(R615X_PULSE_CENTER+R615X_PULSE_C150PC)) // is a gap pulse (middle stick+150%) ? // if (CPPM.puls3 > CPPM_T_ceil(R615X_PULSE_CENTER+R615X_PULSE_C200PC)) // is a gap pulse (middle stick+200%) ? if (CPPM.puls3 > CPPM_PULSE_CENTER_PLUS_C200PC_CEIL) // is a gap pulse (middle stick+200%) ? { CPPM.cppm4 = tcnt0 - CPPM.time5; // compute length of elapsed CPPM frame CPPM.time5 = tcnt0; // set start time of next CPPM frame CPPM._puls3[CPPM.iservo+1] = CPPM.cppm4; // store CPPM frame length CPPM._sync2[CPPM.iservo+1] = 0; // if( (CPPM.state==3 && CPPM.cppm4 < CPPM_T_floor(R615X_FRAME_LENGTH)) || // frame length too short ? if( (CPPM.state==3 && CPPM.cppm4 < CPPM_FRAME_LENGTH_FLOOR) || // frame length too short ? // CPPM.cppm4 > CPPM_T_ceil(R615X_FRAME_NOTSYNC) ) // frame length too long ? CPPM.cppm4 > CPPM_FRAME_NOTSYNC_CEIL ) // frame length too long ? { iservos_reset(CPPM.cppm4 > CPPM_FRAME_NOTSYNC_CEIL ? CPPM_FAIL_FRAME_TOO_LONG : CPPM_FAIL_FRAME_TOO_SHORT); } else { if (CPPM.state==2) CPPM.nservo = CPPM.iservo; CPPM.iservo = 0; // set crnt servo (1st) CPPM.jservo = 1; // set next servo (2nd) // CPPM.kservo = CPPM.lservo[1]; // set mask of next servo if (CPPM.state < 3) CPPM.state++; } } else // valid servo pulse. { CPPM.iservo = CPPM.jservo; // set index of current servo pulse if (CPPM.jservo > CPPM_MSERVO) // servos overflow ? { iservos_reset(CPPM_FAIL_SERVOS_NUM_MAX); } else if (CPPM.jservo > CPPM.nservo) // servos overflow ? { iservos_reset(CPPM_FAIL_SERVOS_NUM_FOUND); } else if (CPPM.jservo == CPPM.nservo) { CPPM.jservo = 0; // kservo = lservo[0]; // set next mask of 1st servo CPPM._received = true; } else { CPPM.jservo++; // kservo = lservo[jservo]; // set next mask of next servo } } } } } //------------------------------------------------------------------------------ ISR(TIMER1_COMPA_vect) // *2015-06-05,+2015-02-05 { static uint16_t time5 = 0; if (CPPM.oservo < CPPM_MSERVO) // PPM pulse ? { if ((PINB & _BV(PINB1))) // rising edge ? { OCR1A += CPPM.oservos[CPPM.oservo] - CPPM_T_round(R615X_PULSE_SYNC); CPPM.oservo++; // next PPM pulse (or gap) } else // falling edge. { if (CPPM.oservo == 0) time5 = OCR1A; OCR1A += CPPM_T_round(R615X_PULSE_SYNC); // CPPM._sent = false; } } else // gap pulse. { if ((PINB & _BV(PINB1))) // rising edge ? { OCR1A = time5 + CPPM_T_round( R615X_FRAME_LENGTH ); CPPM.oservo = 0; // next PPM pulse } else // falling edge. { OCR1A += CPPM_T_round(R615X_GAP_SYNC); CPPM._sent = true; } } } //------------------------------------------------------------------------------ void CPPM_Class::begin() { CPPM_T_setup(); iservos_setup(); oservos_setup(); fail_reason = CPPM_NO_FAIL; } void CPPM_Class::end() { bitClear(TIMSK1, OCIE1A); // disable interrupt bitClear(TIMSK1, ICIE1); // disable interrupt } void CPPM_Class::cycle() { CPPM_T_cycle(); CPPM_T_check(); } bool CPPM_Class::synchronized() { return state == 3; } bool CPPM_Class::received(void) // +2015-02-05 { bool received = _received; _received = false; return received; } bool CPPM_Class::sent(void) // +2015-06-23 { bool sent = _sent; _sent = false; return sent; } int CPPM_Class::read(int n) { uint16_t *servo2_p = &_puls3[n]; cli(); uint16_t servo2 = *servo2_p; sei(); return (int) servo2; } void CPPM_Class::write(int n, int v) // +2015-04-01 { uint16_t *oservo_p = &oservos[n]; cli(); *oservo_p = v; sei(); } int CPPM_Class::read_us(int n) { return (CPPM_T_div*(long)read(n)+(CPPM_T_mul-1)/2)/CPPM_T_mul; //round } void CPPM_Class::write_us(int n, int v) // +2015-04-01 { write(n, CPPM_T_round(v)); } void CPPM_Class::enableOutput(boolean enable) { if (enable == outputEnabled) return; outputEnabled = enable; // enable or disable CPPM timer; cli(); digitalWrite(CPPM_OC1A, HIGH); if (enable) { TCCR1A = (1<<COM1A0); // Toggle OC1A/OC1B on Compare Match. CPPM.oservo = 0; // start CPPM frame after 22ms... OCR1A += CPPM_T_round(R615X_FRAME_LENGTH); // Enable Timer1 output compare interrupt... bitSet(TIFR1, OCF1A); // clr pending interrupt bitSet(TIMSK1, OCIE1A); // enable interrupt } else { TCCR1A = 0; // Disable toggling OC1A/OC1B on Compare Match. bitClear(TIFR1, OCF1A); // clr pending interrupt bitClear(TIMSK1, OCIE1A); // enable interrupt } sei(); } CPPM_Class CPPM;
27.460317
135
0.643105
Andrey-Prikupets
4e491aad53f1eeee1f9432514a4138486ec87e2d
597
cpp
C++
Source/src/utils/Bool2.cpp
AkitaInteractive/Hachiko-Engine
9d682ed7e00e1f6b889e6e73afa36f290cfb2222
[ "MIT" ]
4
2022-02-17T11:44:39.000Z
2022-03-10T02:20:05.000Z
Source/src/utils/Bool2.cpp
AkitaInteractive/Hachiko-Engine
9d682ed7e00e1f6b889e6e73afa36f290cfb2222
[ "MIT" ]
26
2022-02-17T20:02:51.000Z
2022-03-31T22:52:14.000Z
Source/src/utils/Bool2.cpp
AkitaInteractive/Hachiko-Engine
9d682ed7e00e1f6b889e6e73afa36f290cfb2222
[ "MIT" ]
null
null
null
#include "core/hepch.h" #include "Bool2.h" Hachiko::bool2& Hachiko::bool2::operator=(const bool2& other) { if (this == &other) { return *this; } x = other.x; y = other.y; return *this; } Hachiko::bool2::bool2(const bool x, const bool y) : x(x), y(y) { } Hachiko::bool2::bool2(const bool scalar): x(scalar), y(scalar) { } Hachiko::bool2::bool2(const bool* data) { assert(data != nullptr); x = data[0]; y = data[1]; } const Hachiko::bool2 Hachiko::bool2::True = bool2(true); const Hachiko::bool2 Hachiko::bool2::False = bool2(false);
16.583333
61
0.592965
AkitaInteractive
4e4bc0bf50c1c33c89719d0410c116fb75c90879
3,925
cpp
C++
dynamic/wrappers/cell_based/AbstractCellBasedSimulationModifier2_2.cppwg.cpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
6
2017-02-04T16:10:53.000Z
2021-07-01T08:03:16.000Z
dynamic/wrappers/cell_based/AbstractCellBasedSimulationModifier2_2.cppwg.cpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
6
2017-06-22T08:50:41.000Z
2019-12-15T20:17:29.000Z
dynamic/wrappers/cell_based/AbstractCellBasedSimulationModifier2_2.cppwg.cpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
3
2017-05-15T21:33:58.000Z
2019-10-27T21:43:07.000Z
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <set> #include <vector> #include <string> #include <map> #include "SmartPointers.hpp" #include "UblasIncludes.hpp" #include "AbstractCellBasedSimulationModifier.hpp" #include "AbstractCellBasedSimulationModifier2_2.cppwg.hpp" namespace py = pybind11; typedef AbstractCellBasedSimulationModifier<2,2 > AbstractCellBasedSimulationModifier2_2; PYBIND11_DECLARE_HOLDER_TYPE(T, boost::shared_ptr<T>); class AbstractCellBasedSimulationModifier2_2_Overloads : public AbstractCellBasedSimulationModifier2_2{ public: using AbstractCellBasedSimulationModifier2_2::AbstractCellBasedSimulationModifier; void UpdateAtEndOfTimeStep(::AbstractCellPopulation<2, 2> & rCellPopulation) override { PYBIND11_OVERLOAD_PURE( void, AbstractCellBasedSimulationModifier2_2, UpdateAtEndOfTimeStep, rCellPopulation); } void UpdateAtEndOfOutputTimeStep(::AbstractCellPopulation<2, 2> & rCellPopulation) override { PYBIND11_OVERLOAD( void, AbstractCellBasedSimulationModifier2_2, UpdateAtEndOfOutputTimeStep, rCellPopulation); } void SetupSolve(::AbstractCellPopulation<2, 2> & rCellPopulation, ::std::string outputDirectory) override { PYBIND11_OVERLOAD_PURE( void, AbstractCellBasedSimulationModifier2_2, SetupSolve, rCellPopulation, outputDirectory); } void UpdateAtEndOfSolve(::AbstractCellPopulation<2, 2> & rCellPopulation) override { PYBIND11_OVERLOAD( void, AbstractCellBasedSimulationModifier2_2, UpdateAtEndOfSolve, rCellPopulation); } void OutputSimulationModifierParameters(::out_stream & rParamsFile) override { PYBIND11_OVERLOAD_PURE( void, AbstractCellBasedSimulationModifier2_2, OutputSimulationModifierParameters, rParamsFile); } }; void register_AbstractCellBasedSimulationModifier2_2_class(py::module &m){ py::class_<AbstractCellBasedSimulationModifier2_2 , AbstractCellBasedSimulationModifier2_2_Overloads , boost::shared_ptr<AbstractCellBasedSimulationModifier2_2 > >(m, "AbstractCellBasedSimulationModifier2_2") .def(py::init< >()) .def( "UpdateAtEndOfTimeStep", (void(AbstractCellBasedSimulationModifier2_2::*)(::AbstractCellPopulation<2, 2> &)) &AbstractCellBasedSimulationModifier2_2::UpdateAtEndOfTimeStep, " " , py::arg("rCellPopulation") ) .def( "UpdateAtEndOfOutputTimeStep", (void(AbstractCellBasedSimulationModifier2_2::*)(::AbstractCellPopulation<2, 2> &)) &AbstractCellBasedSimulationModifier2_2::UpdateAtEndOfOutputTimeStep, " " , py::arg("rCellPopulation") ) .def( "SetupSolve", (void(AbstractCellBasedSimulationModifier2_2::*)(::AbstractCellPopulation<2, 2> &, ::std::string)) &AbstractCellBasedSimulationModifier2_2::SetupSolve, " " , py::arg("rCellPopulation"), py::arg("outputDirectory") ) .def( "UpdateAtEndOfSolve", (void(AbstractCellBasedSimulationModifier2_2::*)(::AbstractCellPopulation<2, 2> &)) &AbstractCellBasedSimulationModifier2_2::UpdateAtEndOfSolve, " " , py::arg("rCellPopulation") ) .def( "OutputSimulationModifierInfo", (void(AbstractCellBasedSimulationModifier2_2::*)(::out_stream &)) &AbstractCellBasedSimulationModifier2_2::OutputSimulationModifierInfo, " " , py::arg("rParamsFile") ) .def( "OutputSimulationModifierParameters", (void(AbstractCellBasedSimulationModifier2_2::*)(::out_stream &)) &AbstractCellBasedSimulationModifier2_2::OutputSimulationModifierParameters, " " , py::arg("rParamsFile") ) ; }
45.114943
210
0.695287
jmsgrogan
4e51e427ab019097c9e6e1b94496eb0f6890b8b5
1,681
cc
C++
week6/typed_array/unit_tests.cc
yxc07/EEP_520_Winter2022
6a66e957c8afe78ed3703fda6113e55ccf5b66b2
[ "MIT" ]
13
2020-01-10T00:25:27.000Z
2020-09-14T20:26:23.000Z
week6/typed_array/unit_tests.cc
yxc07/EEP_520_Winter2022
6a66e957c8afe78ed3703fda6113e55ccf5b66b2
[ "MIT" ]
null
null
null
week6/typed_array/unit_tests.cc
yxc07/EEP_520_Winter2022
6a66e957c8afe78ed3703fda6113e55ccf5b66b2
[ "MIT" ]
19
2021-04-07T02:39:30.000Z
2021-12-12T00:40:22.000Z
#include <math.h> #include <float.h> /* defines DBL_EPSILON */ #include <assert.h> #include "typed_array.h" #include "point.h" #include "gtest/gtest.h" namespace { TEST(TypedArray, Construction) { TypedArray<Point> b; b.set(0, Point(1,2,3)); b.set(1, Point(2,3,4)); b.set(20, Point(3,4,5)); EXPECT_EQ(b.get(0).x, 1); EXPECT_EQ(b.get(1).y, 3); EXPECT_EQ(b.get(20).z, 5); } TEST(TypedArray, Defaults) { TypedArray<Point> x; Point& y = x.get(3); std::cout << x << "\n"; EXPECT_DOUBLE_EQ(y.magnitude(), 0.0); } TEST(TypedArray, Matrix) { TypedArray<TypedArray<double>> m; for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { m.get(i).set(j,3*i+j); } } std::cout << m << "\n"; for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { EXPECT_DOUBLE_EQ(m.get(i).get(j),3*i+j); } } } TEST(TypedArray,CopyElementsInSet1) { TypedArray<Point> b; Point p(1,2,3); b.set(0, p); p.x = 4; EXPECT_DOUBLE_EQ(b.get(0).x, 1); } TEST(TypedArray,CopyElementsInSet2) { TypedArray<TypedArray<double>> m; TypedArray<double> x; x.set(0,0); m.set(0,x); x.set(0,-1); EXPECT_DOUBLE_EQ(m.get(0).get(0),0.0); // If set didn't make a copy // then we would expect m[0][0] // to be x[0], which we changed // to -1. } }
25.089552
79
0.443189
yxc07
4e53040677a7ed1322d363d5a13c49d3a63b893b
1,663
cpp
C++
src/common/patcher/patcher.cpp
Hallowizer/MinecraftBlacksmith
f9b5ad0d90f3559ce6b267c2c16b396264923839
[ "BSD-2-Clause" ]
19
2018-11-04T07:34:27.000Z
2022-03-10T11:16:02.000Z
src/common/patcher/patcher.cpp
Hallowizer/MinecraftBlacksmith
f9b5ad0d90f3559ce6b267c2c16b396264923839
[ "BSD-2-Clause" ]
3
2019-02-11T01:03:22.000Z
2021-09-04T07:26:07.000Z
src/common/patcher/patcher.cpp
Hallowizer/MinecraftBlacksmith
f9b5ad0d90f3559ce6b267c2c16b396264923839
[ "BSD-2-Clause" ]
3
2019-12-04T01:50:02.000Z
2022-03-02T21:16:25.000Z
// // patcher.cpp // MinecraftBlacksmith // // Created by Hallowizer on 11/2/18. // // #include <stdlib.h> #include <stdio.h> #include <iostream> #include <string> #include "patcher.hpp" #include "patchApplier.hpp" using namespace std; static void applyPatch(vector<char>&); static void differentBinary(void); struct patchHeader { int srcLength; int checksum; int patchLength; }; static char *binpatchFile; static bool ignoreDiscrepancies; void init(char *gameDir, bool ignorePatchDiscrepancies) { ignoreDiscrepancies = ignorePatchDiscrepancies; } void patchTransform(ModBytecode& bytecode) { if (bytecode.modid != "minecraft") return; applyPatch(bytecode.bytes); } static void applyPatch(vector<char>& bytes) { FILE *file = fopen(binpatchFile, "r"); struct patchHeader *header = malloc(sizeof(struct patchHeader)); fread(header, sizeof(struct patchHeader), 1, file); if (bytes.size() != header->srcLength) differentBinary(); int a = 1; int b = 0; int i; for (i = 0; i < header->srcLength; i++) { // Adler 32 hash a += bytes[i]; b += a; } if (header->checksum != b) differentBinary(); patch(bytes, file); fclose(file); } static void differentBinary(void) { cerr << "There is a binary discrepancy between the expected and actual Minecraft binary. Did you modify Minecraft?\n"; if (ignoreDiscrepancies) cerr << "BML will ignore this error. This may result in an invalid patched binary."; else { cerr << "The game will exit, because this is a severe error. Please get a clean binary."; exit(1); } }
21.320513
119
0.658449
Hallowizer
4e5447cf02f838247af897e81745e9a341e0eaba
1,952
cpp
C++
Firmware/src/grid/PulsingLeds.cpp
zukaitis/midi-grid
527ad37348983f481511fef52d1645eab3a2f60e
[ "BSD-3-Clause" ]
59
2018-03-17T10:32:48.000Z
2022-03-19T17:59:29.000Z
Firmware/src/grid/PulsingLeds.cpp
zukaitis/midi-grid
527ad37348983f481511fef52d1645eab3a2f60e
[ "BSD-3-Clause" ]
3
2019-11-12T09:49:59.000Z
2020-12-09T11:55:00.000Z
Firmware/src/grid/PulsingLeds.cpp
zukaitis/midi-grid
527ad37348983f481511fef52d1645eab3a2f60e
[ "BSD-3-Clause" ]
10
2019-03-14T22:53:39.000Z
2021-12-26T13:42:20.000Z
#include "grid/PulsingLeds.h" #include "grid/LedOutputInterface.h" #include "ThreadConfigurations.h" #include <freertos/ticks.hpp> #include <iterator> namespace grid { static const uint32_t PULSE_STEP_INTERVAL = 67; // 1000ms / 15 = 66.6... ms static const uint8_t PULSE_STEP_COUNT = 15; PulsingLeds::PulsingLeds( LedOutputInterface* ledOutput ): Thread( "PulsingLeds", kPulsingLeds.stackDepth, kPulsingLeds.priority ), ledOutput_( *ledOutput ), led_( 0 ) { Thread::Start(); Thread::Suspend(); } void PulsingLeds::Run() { static const TickType_t delayPeriod = freertos::Ticks::MsToTicks( PULSE_STEP_INTERVAL ); static uint8_t stepNumber = 0; Thread::DelayUntil( delayPeriod ); for (const auto& l : led_) { Color dimmedColor = l.color; if (stepNumber <= 3) { // y = x / 4 dimmedColor = dimmedColor * (static_cast<float>(stepNumber + 1) / 4); } else { // y = -x / 16 dimmedColor = dimmedColor * (static_cast<float>(19 - stepNumber) / 16); } ledOutput_.set( l.coordinates, dimmedColor ); } stepNumber = (stepNumber + 1) % PULSE_STEP_COUNT; } void PulsingLeds::add( const Coordinates& coordinates, const Color& color ) { led_.push_back( {coordinates, color} ); // TODO: use emplace if (1 == led_.size()) { Thread::Resume(); } // don't change output value, it will be set on next flash period } void PulsingLeds::remove( const Coordinates& coordinates ) { // TODO: try some fancy implementation when everything works for (auto& l : led_) { if (coordinates == l.coordinates) { led_.erase( &l ); if (led_.empty()) { Thread::Suspend(); } break; } } } void PulsingLeds::removeAll() { led_.clear(); Thread::Suspend(); } }
22.436782
92
0.589652
zukaitis
4e55056f34a7ca3a8ba185b1091f8fb0c30b32a7
1,125
cpp
C++
core/src/Misc/dateTime.cpp
vdmitriev90/OrbMod
30e968cc23a6ba8864ac1369dd307189400d159c
[ "MIT" ]
4
2016-07-28T19:54:31.000Z
2021-05-01T00:41:25.000Z
core/src/Misc/dateTime.cpp
vdmitriev90/OrbMod
30e968cc23a6ba8864ac1369dd307189400d159c
[ "MIT" ]
null
null
null
core/src/Misc/dateTime.cpp
vdmitriev90/OrbMod
30e968cc23a6ba8864ac1369dd307189400d159c
[ "MIT" ]
null
null
null
#define _CRT_SECURE_NO_WARNINGS #include"dateTime.h" using namespace std; namespace OrbMod { dateTime::dateTime() { Y = 0, M = 0, D = 0, h = 0, min = 0, sec = 0; } dateTime::dateTime(int Y_, int M_, int D_, int h_, int min_, double sec_) { Y = Y_, M = M_, D = D_, h = h_, min = min_, sec = sec_; } dateTime::dateTime(int Y_, int M_, int D_, int h_, int min_, int sec_, int msec_) { Y = Y_, M = M_, D = D_, h = h_, min = min_, sec = sec_ + msec_ / 1000.0; } double dateTime::msec() { return (int)((sec - (int)sec) * 1000 + 0.5); } string dateTime::toString() { char c_Y[5], c_Mounth[3], c_Day[3], c_hours[3], c_min[3]; sprintf(c_Y, "%.4i", Y); sprintf(c_Mounth, "%.2i", M); sprintf(c_Day, "%.2i", D); sprintf(c_hours, "%.2i", h); sprintf(c_min, "%.2i", min); string s = ""; s += c_Y; s += '-'; s += c_Mounth; s += '-'; s += +c_Day; s += 'T'; s += c_hours; s += ':'; s += c_min; s += ':'; s += to_string(sec); return s; } dateTime::~dateTime() { } JD2::JD2(double jd1_, double jd2_) { jd1 = jd1_, jd2 = jd2_; } JD2::JD2(const dateTime & dt, char* scale) { } }
20.833333
82
0.546667
vdmitriev90
4e57547027728cc51ebbe2e4714091268fa2611c
837
cpp
C++
DEF/FENCE/Scaachan.cpp
Scaachan/Advanced-Algorithm-Study
03971389615e855d27d6d0d30598f55ef32970dc
[ "MIT" ]
9
2021-01-06T04:17:37.000Z
2021-01-11T12:44:47.000Z
DEF/FENCE/Scaachan.cpp
Queue-ri/Advanced-Algorithm-Study
f44a75e55fffedcd988bfe8301eac224462c872d
[ "MIT" ]
115
2022-01-13T07:37:23.000Z
2022-03-13T14:09:15.000Z
DEF/FENCE/Scaachan.cpp
Scaachan/Advanced-Algorithm-Study
03971389615e855d27d6d0d30598f55ef32970dc
[ "MIT" ]
8
2021-01-09T16:46:48.000Z
2021-01-24T01:13:48.000Z
#include <bits/stdc++.h> #define endl '\n' #define rep(V,S,T) for(int V=S; V<T; ++V) using namespace std; int N, fence[20000]; int divnq(int l, int r) { if (l == r) return fence[l]; int m = (l + r) >> 1; int ans = max(divnq(l, m), divnq(m + 1, r)); // cmp l,r int low = m, high = m + 1; int minh = min(fence[low], fence[high]); ans = max(ans, minh << 1); // cmp max(l,r), low2high while (low > l || high < r) { if (high < r && (low == l || fence[low-1] < fence[high+1])) { ++high; minh = min(minh, fence[high]); } else { --low; minh = min(minh, fence[low]); } ans = max(ans, minh * (high - low + 1)); } return ans; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int TC; cin >> TC; while (TC--) { cin >> N; rep(i,0,N) cin >> fence[i]; cout << divnq(0, N-1) << endl; } }
19.928571
63
0.529271
Scaachan
4e594a6f288af09c9a9d243cdf15657669376c54
15,509
cpp
C++
models/selectedmarketmodel.cpp
doctorcee/betfair_ladder_trader
ba2e975e9c4fe6bd83083fd3074c54c3e6dcafe9
[ "MIT" ]
null
null
null
models/selectedmarketmodel.cpp
doctorcee/betfair_ladder_trader
ba2e975e9c4fe6bd83083fd3074c54c3e6dcafe9
[ "MIT" ]
null
null
null
models/selectedmarketmodel.cpp
doctorcee/betfair_ladder_trader
ba2e975e9c4fe6bd83083fd3074c54c3e6dcafe9
[ "MIT" ]
null
null
null
#include "selectedmarketmodel.h" #include <QDebug> #include <QFont> #include <QBrush> #include <sstream> //================================================================= SelectedMarketModel::SelectedMarketModel(QObject *parent, betfair::TBetfairMarket& my_market_ref, const QString& image_dir, const std::uint16_t& disptheme) : QAbstractTableModel(parent), m_bf_market(my_market_ref), m_image_dir(image_dir), m_display_theme(disptheme), m_betting_enabled(false) { } //================================================================= int SelectedMarketModel::rowCount(const QModelIndex & /*parent*/) const { int size = 0; if (m_bf_market.valid()) { size = static_cast<int>(m_bf_market.getNumRunners()); } return size; } //================================================================= int SelectedMarketModel::columnCount(const QModelIndex & /*parent*/) const { return gridview::COLUMN_COUNT; } //================================================================= QString SelectedMarketModel::getSelectedMarketID() const { return (m_bf_market.valid() ? m_bf_market.getMarketID() : ""); } //================================================================= void SelectedMarketModel::refresh() { if (m_bf_market.valid()) { beginResetModel(); endResetModel(); } } //================================================================= void SelectedMarketModel::updateData() { // Dont update the FIRST column if (m_bf_market.valid()) { QModelIndex topLeft = createIndex(0,0); QModelIndex bottomRight = createIndex(static_cast<int>(m_bf_market.getNumRunners()),gridview::COLUMN_COUNT); //emit a signal to make the view reread identified data emit dataChanged(topLeft, bottomRight); } } //================================================================= QVariant SelectedMarketModel::data(const QModelIndex &index, int role) const { int row = index.row(); int col = index.column(); if (m_bf_market.valid() && row >= 0 && col >= gridview::IMAGE) { bool b_suspended = (m_bf_market.getMarketStatus() == "SUSPENDED"); switch(role) { case Qt::DecorationRole: if (gridview::NAME == col) { int num_runners = static_cast<int>(m_bf_market.getNumRunners()); if (row < num_runners) { auto runners = m_bf_market.getRunners(); const std::size_t runner_index = static_cast<std::size_t>(row); std::shared_ptr<betfair::TRunner> this_runner = runners[runner_index]; QString fname = m_image_dir + "/" + QString::number(this_runner->getID()) + ".jpg"; QPixmap pixmap(fname); return pixmap; } } break; case Qt::DisplayRole: { QString display_val(""); int num_runners = static_cast<int>(m_bf_market.getNumRunners()); if (row < num_runners) { auto runners = m_bf_market.getRunners(); const std::size_t runner_index = static_cast<std::size_t>(row); std::shared_ptr<betfair::TRunner> this_runner = runners[runner_index]; bool b_runner_active = this_runner->isActive(); bool b_runner_won = this_runner->isWinner(); if (col == gridview::NAME) { display_val = this_runner->getName(); if (b_runner_active == false) { display_val.append(" N/R"); } else { QString draw = this_runner->getStallDraw(); if (!draw.isEmpty()) { display_val.append(" [" + draw + "]"); } } } else if (col == gridview::PROFIT) { double profitifwins = this_runner->getProfit(); display_val = profitifwins < 0.0 ? "-£" : "£"; display_val += QString::number(std::abs(profitifwins),'f',2); } else if (col >= gridview::BACK3 && col <= gridview::BACK1) { if (b_runner_won) { display_val = "WINNER"; } else { if (b_runner_active) { const int pindex = 5 - col; std::pair<double,double> bp = this_runner->getOrderedBackPrice(pindex); if (bp.first > 0.0) { display_val = QString::number(bp.first,'f',2) + QString("\n£") + QString::number(bp.second,'f',2); } } } } else if (col >= gridview::LAY1 && col <= gridview::LAY3) { if (b_runner_won) { display_val = "WINNER"; } else { if (b_runner_active) { const int pindex = col-6; std::pair<double,double> bp = this_runner->getOrderedLayPrice(pindex); if (bp.first > 0.0) { display_val = QString::number(bp.first,'f',2) + QString("\n£") + QString::number(bp.second,'f',2); } } } } else if (gridview::HEDGE == col) { display_val = "HEDGE POSITION"; } } return display_val; } case Qt::FontRole: if (col == gridview::LAY1 || col == gridview::BACK1 || col == gridview::NAME || col == gridview::PROFIT) { QFont boldFont; boldFont.setBold(true); return boldFont; } break; case Qt::ForegroundRole: if (col == gridview::NAME) { if (m_display_theme == 1) { QBrush t(Qt::black); return t; } } else if (col >= gridview::BACK3 && col <= gridview::LAY3) { if (m_display_theme == 1) { QBrush t(Qt::black); return t; } } else if (col == gridview::PROFIT) { int num_runners = static_cast<int>(m_bf_market.getNumRunners()); if (row < num_runners) { auto runners = m_bf_market.getRunners(); const std::size_t runner_index = static_cast<std::size_t>(row); std::shared_ptr<betfair::TRunner> this_runner = runners[runner_index]; bool b_runner_active = this_runner->isActive(); if (b_runner_active) { if (this_runner->getProfit() > 0.0) { return (m_display_theme == 0) ? QBrush(betfair::utils::green1) : QBrush(Qt::white); } else if (this_runner->getProfit() < 0.0) { return (m_display_theme == 0) ? QBrush(betfair::utils::redTwo) : QBrush(Qt::white); } else { return (m_display_theme == 0) ? QBrush(Qt::black) : QBrush(Qt::white); } } } } break; case Qt::BackgroundRole: switch (col) { case gridview::NAME: return QBrush(Qt::white); case gridview::PROFIT: { int num_runners = static_cast<int>(m_bf_market.getNumRunners()); if (row < num_runners) { auto runners = m_bf_market.getRunners(); const std::size_t runner_index = static_cast<std::size_t>(row); std::shared_ptr<betfair::TRunner> this_runner = runners[runner_index]; bool b_runner_active = this_runner->isActive(); if (b_runner_active) { if (this_runner->getProfit() > 0.0) { return (m_display_theme == 1) ? QBrush(betfair::utils::green1) : QBrush(Qt::white); } else if (this_runner->getProfit() < 0.0) { return (m_display_theme == 1) ? QBrush(betfair::utils::redTwo) : QBrush(Qt::white); } else { return (m_display_theme == 1) ? QBrush(betfair::utils::midgrey1) : QBrush(Qt::white); } } } } break; case gridview::BACK3: { if (m_betting_enabled) { return b_suspended ? QBrush(betfair::utils::susp) : QBrush(betfair::utils::backThree); } else { return QBrush(betfair::utils::midgrey1); } } case gridview::BACK2: { if (m_betting_enabled) { return b_suspended ? QBrush(betfair::utils::susp) : QBrush(betfair::utils::backTwo); } else { return QBrush(betfair::utils::midgrey1); } } case gridview::BACK1: { if (m_betting_enabled) { return b_suspended ? QBrush(betfair::utils::susp) : QBrush(betfair::utils::backOne); } else { return QBrush(betfair::utils::midgrey1); } } case gridview::LAY1: { if (m_betting_enabled) { return b_suspended ? QBrush(betfair::utils::susp) : QBrush(betfair::utils::layOne); } else { return QBrush(betfair::utils::midgrey1); } } case gridview::LAY2: { if (m_betting_enabled) { return b_suspended ? QBrush(betfair::utils::susp) : QBrush(betfair::utils::layTwo); } else { return QBrush(betfair::utils::midgrey1); } } case gridview::LAY3: { if (m_betting_enabled) { return b_suspended ? QBrush(betfair::utils::susp) : QBrush(betfair::utils::layThree); } else { return QBrush(betfair::utils::midgrey1); } } case gridview::HEDGE: { if (m_betting_enabled) { return b_suspended ? QBrush(betfair::utils::susp) : QBrush(betfair::utils::green1); } else { return QBrush(betfair::utils::midgrey1); } } default: break; } break; case Qt::TextAlignmentRole: if (row >= 0 && col >= 0) { return Qt::AlignHCenter + Qt::AlignVCenter; } break; default: break; } } return QVariant(); } //================================================================= QVariant SelectedMarketModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole) { if (orientation == Qt::Horizontal) { switch (section) { case gridview::NAME: return QString("SELECTION"); case gridview::PROFIT: return QString("PROFIT"); case gridview::BACK1: return QString("BACK"); case gridview::LAY1: return QString("LAY"); default: break; } } else if (orientation == Qt::Vertical) { return (QString(" ") + QString::number(section + 1) + QString(" ")); } } return QVariant(); }
40.706037
134
0.352956
doctorcee
4e5c25b77d4a65bf724af557e8eed0f259339a51
7,165
cc
C++
mcg/src/external/BSR/src/math/random/sources/mersenne_twister_32.cc
mouthwater/rgb
3fafca24ecc133910923182581a2133b8568bf77
[ "BSD-2-Clause" ]
392
2015-01-14T13:19:40.000Z
2022-02-12T08:47:33.000Z
mcg/src/external/BSR/src/math/random/sources/mersenne_twister_32.cc
mouthwater/rgb
3fafca24ecc133910923182581a2133b8568bf77
[ "BSD-2-Clause" ]
45
2015-02-03T12:16:10.000Z
2022-03-07T00:25:09.000Z
mcg/src/external/BSR/src/math/random/sources/mersenne_twister_32.cc
mouthwater/rgb
3fafca24ecc133910923182581a2133b8568bf77
[ "BSD-2-Clause" ]
168
2015-01-05T02:29:53.000Z
2022-02-22T04:32:04.000Z
/* * Mersenne Twister 32-bit pseudorandom source. * * This implementation is based on freely distributed code by Takuji Nishimura * and Makoto Matsumoto. The copyright notice for the original version is * included below. */ /* * A C-program for MT19937, with initialization improved 2002/1/26. * Coded by Takuji Nishimura and Makoto Matsumoto. * * Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, * 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. The names of its contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Any feedback is very welcome. * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html * email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) */ #include "lang/array.hh" #include "math/random/sources/mersenne_twister_32.hh" #include "math/random/sources/rand_source.hh" #include "math/random/sources/system_entropy.hh" namespace math { namespace random { namespace sources { /* * Imports. */ using lang::array; /* * Generator parameters. */ namespace { const unsigned long N = 624; const unsigned long M = 397; const unsigned int MATRIX_A = 0x9908b0df; /* constant vector a */ const unsigned int UPPER_MASK = 0x80000000; /* most significant w-r bits */ const unsigned int LOWER_MASK = 0x7fffffff; /* least significant r bits */ } /* * Constructor. * Initialize the state randomly using entropy from the system. */ mersenne_twister_32::mersenne_twister_32() : _state(N), _curr(N) { system_entropy sys_entropy; this->initialize(sys_entropy); } /* * Constructor. * Initialize the state by using the given random source. */ mersenne_twister_32::mersenne_twister_32(rand_source& r) : _state(N), _curr(N) { this->initialize(r); } /* * Constructor. * Initialize the state using the given data. */ mersenne_twister_32::mersenne_twister_32(const array<unsigned int>& seed) : _state(N), _curr(N) { this->initialize(seed); } /* * Initialize the state using the given random source. */ void mersenne_twister_32::initialize(rand_source& r) { /* generate random data for initialization */ array<unsigned int> seed(N); for (unsigned long n = 0; n < N; n++) seed[n] = r.gen_uniform_unsigned_int(); /* initialize using random data */ this->initialize(seed); } /* * Initialize the state using the given data. */ void mersenne_twister_32::initialize(const array<unsigned int>& seed) { /* check if seed is empty */ if (seed.is_empty()) { /* use a predefined seed */ array<unsigned int> default_seed(4); default_seed[0] = 0x123; default_seed[1] = 0x234; default_seed[2] = 0x345; default_seed[3] = 0x456; this->initialize(default_seed); } else { /* initialize state to predefined pattern */ _state[0]= 19650218; for (unsigned long n = 1; n < N; n++) { _state[n] = (1812433253 * (_state[n-1] ^ (_state[n-1] >> 30)) + n); /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ /* In the previous versions, MSBs of the seed affect */ /* only MSBs of the array _state[]. */ /* 2002/01/09 modified by Makoto Matsumoto */ _state[n] &= 0xffffffff; /* for >32 bit machines */ } /* modify state with the given seed */ unsigned long seed_size = seed.size(); unsigned long i = 1; unsigned long j = 0; unsigned long k = (N > seed_size) ? N : seed_size; for (; k > 0; k--) { _state[i] = (_state[i] ^ ((_state[i-1] ^ (_state[i-1] >> 30)) * 1664525)) + seed[j] + static_cast<unsigned int>(j); /* non linear */ _state[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */ i++; j++; if (i >= N) { _state[0] = _state[N-1]; i = 1; } if (j >= seed_size) { j = 0; } } for (k = N-1; k > 0; k--) { _state[i] = (_state[i] ^ ((_state[i-1] ^ (_state[i-1] >> 30)) * 1566083941)) - static_cast<unsigned int>(i); /* non linear */ _state[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */ i++; if (i >= N) { _state[0] = _state[N-1]; i = 1; } } _state[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */ } } /* * Copy constructor. * Give the copy the same state as the original. */ mersenne_twister_32::mersenne_twister_32(const mersenne_twister_32& r) : _state(r._state), _curr(r._curr) { } /* * Destructor. */ mersenne_twister_32::~mersenne_twister_32() { /* do nothing */ } /* * Generate a pseudorandom unsigned 32-bit integer uniformly distributed * on the closed interval [0, 2^32-1]. */ unsigned int mersenne_twister_32::generate() { static const unsigned int mag01[2] = {0x0, MATRIX_A}; unsigned int x; /* check if new items need to be generated */ if (_curr >= N) { /* generate NN items at once */ unsigned long i; for (i = 0; i < (N-M); i++) { x = (_state[i] & UPPER_MASK) | (_state[i+1] & LOWER_MASK); _state[i] = _state[i+M] ^ (x >> 1) ^ mag01[static_cast<unsigned long>(x & 0x1)]; } for (; i < (N-1); i++) { x = (_state[i] & UPPER_MASK) | (_state[i+1] & LOWER_MASK); _state[i] = _state[i + M - N] ^ (x >> 1) ^ mag01[static_cast<unsigned long>(x & 0x1)]; } x = (_state[N-1] & UPPER_MASK) | (_state[0] & LOWER_MASK); _state[N-1] = _state[M-1] ^ (x >> 1) ^ mag01[static_cast<unsigned long>(x & 0x1)]; _curr = 0; } /* retrieve next item */ x = _state[_curr++]; x ^= (x >> 11); x ^= (x << 7) & 0x9d2c5680; x ^= (x << 15) & 0xefc60000; x ^= (x >> 18); return x; } } /* namespace sources */ } /* namespace random */ } /* namespace math */
32.716895
95
0.633496
mouthwater
4e5fa9463dbaea112d1ff9619a814b70134c3949
17,757
cpp
C++
src/IntoRobot_UC1701X.cpp
intoyuniot/IntoRobot_UC1701X
315eb89d6f5a8c1c06535ff053d98ca33ed08c90
[ "MIT" ]
null
null
null
src/IntoRobot_UC1701X.cpp
intoyuniot/IntoRobot_UC1701X
315eb89d6f5a8c1c06535ff053d98ca33ed08c90
[ "MIT" ]
null
null
null
src/IntoRobot_UC1701X.cpp
intoyuniot/IntoRobot_UC1701X
315eb89d6f5a8c1c06535ff053d98ca33ed08c90
[ "MIT" ]
null
null
null
/* ****************************************************************************** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, see <http://www.gnu.org/licenses/>. Adapted for IntoRobot by Robin, Sept 19, 2015 ******************************************************************** */ #include "IntoRobot_UC1701X.h" // the memory buffer for the LCD static uint8_t buffer[LCD_HEIGHT * LCD_WIDTH / 8] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xA0,0xA0,0xA0,0xA0,0x80,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40, 0x40,0x40,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x80,0x00,0xA0,0xA0,0xA0,0xA0,0xA0,0xA0,0xA0,0xA0,0xA0,0xA0, 0xA0,0x80,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x80,0x00,0xD0,0xD0,0xD0,0xD0,0xD0,0x00,0xC0,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x40,0x40,0x40,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x70,0x07,0xF8,0xFF,0xFF,0xFF,0xFF,0x1F,0x71,0xCE,0xF8, 0xFA,0xFA,0xF8,0xF4,0xF4,0xF8,0xFA,0xFA,0xFA,0xF8,0xF0,0x00,0xF8,0xFA,0xFE,0xFF, 0xFF,0xFF,0xFF,0xFB,0xFA,0x3B,0xD0,0xE8,0xF4,0xF4,0xF8,0xFA,0xFA,0xFA,0xFA,0xF0, 0xF4,0xE8,0x10,0x3C,0xE1,0xFE,0xFF,0xFF,0xFF,0xBF,0xA7,0xBF,0xBF,0xCF,0xFF,0xFF, 0xFF,0xFF,0xFF,0x00,0xB3,0xD0,0xE8,0xF4,0xF4,0xFA,0xFA,0xFA,0xFA,0xFA,0xF4,0xF4, 0xE8,0x10,0x0E,0xF0,0xFF,0xFF,0xFF,0xFF,0xFF,0xF9,0xFA,0xFA,0xFA,0xF8,0xF4,0xC0, 0xB0,0xD0,0xE8,0xF4,0xF4,0xFA,0xFA,0xFA,0xFA,0xFA,0xF4,0xF4,0xE8,0x00,0xF8,0xFA, 0xFE,0xFF,0xFF,0xFF,0xFF,0xFB,0xFA,0x3B,0x40,0x10,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xE0,0x0E,0xF0,0xFF,0xFF,0xFF,0xFF,0x1F,0x61,0x86,0xFC,0xFF,0xFF, 0xFF,0x7F,0x87,0x1D,0xF2,0xFE,0xFF,0xFF,0xFF,0x1F,0xE1,0x06,0xFC,0xFF,0xFF,0xFF, 0xFF,0xEF,0xEA,0x0E,0xB0,0xFF,0xFF,0xFF,0xFF,0xFF,0xEA,0xEE,0xFA,0xFF,0xFF,0x7F, 0xBF,0x0F,0xC0,0xFE,0xFF,0xFF,0xFF,0x7F,0xAF,0x6F,0xBF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xEB,0xBD,0xC6,0x78,0xFF,0xFF,0xFF,0xFF,0xEF,0xEA,0xEB,0xFC,0xFF,0xFF,0x7F,0xBF, 0x07,0xE0,0xFF,0xFF,0xFF,0xFF,0xFF,0xEB,0xEE,0xFA,0xFF,0xFF,0xFF,0xBF,0x8F,0x78, 0xFF,0xFF,0xFF,0xFF,0xEF,0xEA,0xEB,0xFC,0xFF,0xFF,0x7F,0xBF,0xE7,0x00,0xFC,0xFF, 0xFF,0xFF,0xFF,0xEF,0xEA,0x02,0xE0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x01,0x05,0x05,0x05,0x05,0x01,0x00,0x00,0x01,0x05,0x05,0x05, 0x05,0x00,0x01,0x00,0x05,0x05,0x05,0x05,0x01,0x00,0x01,0x00,0x01,0x05,0x05,0x05, 0x05,0x05,0x05,0x00,0x01,0x02,0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x02,0x01, 0x01,0x00,0x05,0x05,0x05,0x05,0x05,0x00,0x01,0x00,0x01,0x00,0x05,0x05,0x05,0x05, 0x05,0x05,0x00,0x01,0x02,0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x01,0x02,0x01,0x01, 0x00,0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x02,0x00,0x00,0x00,0x01, 0x02,0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x01,0x02,0x01,0x00,0x00,0x00,0x01,0x05, 0x05,0x05,0x05,0x05,0x05,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }; // the most basic function, set a single pixel void IntoRobot_UC1701X::drawPixel(int16_t x, int16_t y, uint16_t color) { if ((x < 0) || (x >= width()) || (y < 0) || (y >= height())) return; // check rotation, move pixel around if necessary switch (getRotation()) { case 1: swap(x, y); x = WIDTH - x - 1; break; case 2: x = WIDTH - x - 1; y = HEIGHT - y - 1; break; case 3: swap(x, y); y = HEIGHT - y - 1; break; } // x is which column if (color == WHITE) buffer[x+ (y/8)*LCD_WIDTH] |= (1 << (y&7)); else buffer[x+ (y/8)*LCD_WIDTH] &= ~(1 << (y&7)); } // constructor for software SPI - we indicate DataCommand, ChipSelect, Reset IntoRobot_UC1701X::IntoRobot_UC1701X(int8_t CS,int8_t RST,int8_t DC,int8_t SID, int8_t SCLK) : Adafruit_GFX(LCD_WIDTH, LCD_HEIGHT) { cs = CS; rst = RST; dc = DC; sclk = SCLK; sid = SID; hwSPI = false; } // constructor for hardware SPI - we indicate DataCommand, ChipSelect, Reset IntoRobot_UC1701X::IntoRobot_UC1701X(int8_t CS, int8_t RST, int8_t DC) : Adafruit_GFX(LCD_WIDTH, LCD_HEIGHT) { dc = DC; rst = RST; cs = CS; hwSPI = true; } void IntoRobot_UC1701X::begin(void) { // set pin directions pinMode(dc, OUTPUT); pinMode(cs, OUTPUT); if (!hwSPI) { // set pins for software-SPI pinMode(sid, OUTPUT); pinMode(sclk, OUTPUT); digitalWrite(sclk, LOW); } else // hardware spi { digitalWrite(cs, HIGH); SPI.setBitOrder(MSBFIRST); SPI.setClockDivider(SPI_CLOCK_DIV8); // 72MHz / 8 = 9Mhz //SPI.setDataMode(0); SPI.begin(); } // Setup reset pin direction (used by both SPI and I2C) pinMode(rst, OUTPUT); digitalWrite(rst, HIGH); // VDD (3.3V) goes high at start, lets just chill for a ms delay(1); // bring reset low digitalWrite(rst, LOW); // wait 10ms delay(10); // bring out of reset digitalWrite(rst, HIGH); // turn on VCC (9V?) uc1701x_command(0xE2); //System Reset uc1701x_command(0x40); // Set display start line to 0 uc1701x_command(0xA0); //Set SEG Direction uc1701x_command(0xC8); //Set COM Direction uc1701x_command(0xA2); //Set Bias = 1/9 uc1701x_command(0x2C); //Boost ON uc1701x_command(0x2E); //Voltage Regular On uc1701x_command(0x2F); //Voltage Follower On uc1701x_command(0xF8); //Set booster ratio to uc1701x_command(0x00); // x uc1701x_command(0x23); //Set Resistor Ratio = 3 uc1701x_command(0x81); uc1701x_command(0x28); //Set Electronic Volume = 40 uc1701x_command(0xAC);//Set Static indicator off uc1701x_command(0x00); uc1701x_command(0XA6); // Disable inverse uc1701x_command(0xAF); //Set Display Enable delay(100); uc1701x_command(0xA5); //display all points delay(200); uc1701x_command(0xA4); //normal display clearScreen(); display(); delay(3000); clearScreen(); } void IntoRobot_UC1701X::clearScreen(void) { fillScreen(0x00); } void IntoRobot_UC1701X::fullScreen(void) { fillScreen(0xff); } void IntoRobot_UC1701X::fillScreen(unsigned char dat) { for (unsigned short j = 0; j < 8; j++) { set_uc1701xCursor(0, j); for (unsigned short i = 0; i < 132 ; i++) { uc1701x_data(dat); } } set_uc1701xCursor(0, 0); } void IntoRobot_UC1701X::set_uc1701xCursor(unsigned char column, unsigned char page) { uc1701x_command(0xb0+page); uc1701x_command(0x10 | ((column >> 4) & 0x0f)); uc1701x_command(column & 0x0F); } void IntoRobot_UC1701X::uc1701x_command(uint8_t c) { digitalWrite(cs, HIGH); digitalWrite(dc, LOW); digitalWrite(cs, LOW); fastSPIwrite(c); digitalWrite(cs, HIGH); } void IntoRobot_UC1701X::uc1701x_data(uint8_t c) { digitalWrite(cs, HIGH); digitalWrite(dc, HIGH); digitalWrite(cs, LOW); fastSPIwrite(c); digitalWrite(cs, HIGH); } inline void IntoRobot_UC1701X::fastSPIwrite(uint8_t d) { if(hwSPI) { (void)SPI.transfer(d); } else { shiftOut(sid, sclk, MSBFIRST, d); // uc1701x specs show MSB out first } } //粗调对比度 0x20-0x2f void IntoRobot_UC1701X::coarseContrast(uint8_t contrast) { uint8_t contrastValue; if(contrast < 0x20) contrastValue = 0x20; else if(contrast > 0x2f) contrastValue = 0x2f; else contrastValue = contrast; uc1701x_command(contrastValue); } //细调对比度 0-63 void IntoRobot_UC1701X::fineTuneContrast(uint8_t contrast) { uint8_t contrastValue; if(contrast < 0) contrastValue = 0; else if(contrast > 63) contrastValue = 63; else contrastValue = contrast; uc1701x_command(0x81); uc1701x_command(contrastValue); } void IntoRobot_UC1701X::display(void) { for (unsigned char page = 0; page < 8; page++) { uc1701x_command(0xb0+page); uc1701x_command(0x10); uc1701x_command(0x00); digitalWrite(cs, HIGH); digitalWrite(dc, HIGH); digitalWrite(cs, LOW); for(unsigned char column = 0; column< 128 ; column++) { fastSPIwrite(buffer[page*128 + column]); } digitalWrite(cs, HIGH); } } // clear everything void IntoRobot_UC1701X::clearDisplay(void) { memset(buffer, 0, (LCD_WIDTH*LCD_HEIGHT/8)); } void IntoRobot_UC1701X::drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color) { boolean bSwap = false; switch(rotation) { case 0: // 0 degree rotation, do nothing break; case 1: // 90 degree rotation, swap x & y for rotation, then invert x bSwap = true; swap(x, y); x = WIDTH - x - 1; break; case 2: // 180 degree rotation, invert x and y - then shift y around for height. x = WIDTH - x - 1; y = HEIGHT - y - 1; x -= (w-1); break; case 3: // 270 degree rotation, swap x & y for rotation, then invert y and adjust y for w (not to become h) bSwap = true; swap(x, y); y = HEIGHT - y - 1; y -= (w-1); break; } if(bSwap) { drawFastVLineInternal(x, y, w, color); } else { drawFastHLineInternal(x, y, w, color); } } void IntoRobot_UC1701X::drawFastHLineInternal(int16_t x, int16_t y, int16_t w, uint16_t color) { // Do bounds/limit checks if(y < 0 || y >= HEIGHT) { return; } // make sure we don't try to draw below 0 if(x < 0) { w += x; x = 0; } // make sure we don't go off the edge of the display if( (x + w) > WIDTH) { w = (HEIGHT- x); } // if our width is now negative, punt if(w <= 0) { return; } // set up the pointer for movement through the buffer register uint8_t *pBuf = buffer; // adjust the buffer pointer for the current row pBuf += ((y/8) * LCD_WIDTH); // and offset x columns in pBuf += x; register uint8_t mask = 1 << (y&7); if(color == WHITE) { while(w--) { *pBuf++ |= mask; } } else { mask = ~mask; while(w--) { *pBuf++ &= mask; } } } void IntoRobot_UC1701X::drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color) { bool bSwap = false; switch(rotation) { case 0: break; case 1: // 90 degree rotation, swap x & y for rotation, then invert x and adjust x for h (now to become w) bSwap = true; swap(x, y); x = WIDTH - x - 1; x -= (h-1); break; case 2: // 180 degree rotation, invert x and y - then shift y around for height. x = WIDTH - x - 1; y = HEIGHT - y - 1; y -= (h-1); break; case 3: // 270 degree rotation, swap x & y for rotation, then invert y bSwap = true; swap(x, y); y = HEIGHT - y - 1; break; } if(bSwap) { drawFastHLineInternal(x, y, h, color); } else { drawFastVLineInternal(x, y, h, color); } } void IntoRobot_UC1701X::drawFastVLineInternal(int16_t x, int16_t __y, int16_t __h, uint16_t color) { // do nothing if we're off the left or right side of the screen if(x < 0 || x >= WIDTH) { return; } // make sure we don't try to draw below 0 if(__y < 0) { // __y is negative, this will subtract enough from __h to account for __y being 0 __h += __y; __y = 0; } // make sure we don't go past the height of the display if( (__y + __h) > HEIGHT) { __h = (HEIGHT - __y); } // if our height is now negative, punt if(__h <= 0) { return; } // this display doesn't need ints for coordinates, use local byte registers for faster juggling register uint8_t y = __y; register uint8_t h = __h; // set up the pointer for fast movement through the buffer register uint8_t *pBuf = buffer; // adjust the buffer pointer for the current row pBuf += ((y/8) * LCD_WIDTH); // and offset x columns in pBuf += x; // do the first partial byte, if necessary - this requires some masking register uint8_t mod = (y&7); if(mod) { // mask off the high n bits we want to set mod = 8-mod; // note - lookup table results in a nearly 10% performance improvement in fill* functions // register uint8_t mask = ~(0xFF >> (mod)); static uint8_t premask[8] = {0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE }; register uint8_t mask = premask[mod]; // adjust the mask if we're not going to reach the end of this byte if( h < mod) { mask &= (0XFF >> (mod-h)); } if(color == WHITE) { *pBuf |= mask; } else { *pBuf &= ~mask; } // fast exit if we're done here! if(h<mod) { return; } h -= mod; pBuf += LCD_WIDTH; } // write solid bytes while we can - effectively doing 8 rows at a time if(h >= 8) { // store a local value to work with register uint8_t val = (color == WHITE) ? 255 : 0; do { // write our value in *pBuf = val; // adjust the buffer forward 8 rows worth of data pBuf += LCD_WIDTH; // adjust h & y (there's got to be a faster way for me to do this, but this should still help a fair bit for now) h -= 8; } while(h >= 8); } // now do the final partial byte, if necessary if(h) { mod = h & 7; // this time we want to mask the low bits of the byte, vs the high bits we did above // register uint8_t mask = (1 << mod) - 1; // note - lookup table results in a nearly 10% performance improvement in fill* functions static uint8_t postmask[8] = {0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F }; register uint8_t mask = postmask[mod]; if(color == WHITE) { *pBuf |= mask; } else { *pBuf &= ~mask; } } }
33.37782
130
0.627978
intoyuniot
4e602eb19491e26aa266dad80a1702305ae582e4
148,713
cpp
C++
3dc/avp/bh_xeno.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
3dc/avp/bh_xeno.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
3dc/avp/bh_xeno.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
/* Patrick 4/7/97 ---------------------------------------------------- Source file for Xenoborg AI behaviour functions.... --------------------------------------------------------------------*/ /* ChrisF 6/7/98. Hopeless. I'll have to take off and nuke the entire site from orbit. */ #include "3dc.h" #include "io.h" #include "inline.h" #include "module.h" #include "strategy_def.h" #include "gamedef.h" #include "bh_types.h" #include "compiled_shapes.h" #include "dynblock.h" #include "dynamics.h" #include "pfarlocs.h" #include "pvisible.h" #include "bh_predator.h" #include "bh_xeno.h" #include "lighting.h" #include "bh_weapon.h" #include "weapons.h" #include "bh_debris.h" #include "plat_shp.h" #include "particle.h" #include "ai_sight.h" #include "sequences.h" #include "huddefs.h" #include "showcmds.h" #include "sfx.h" #include "bh_marine.h" #include "bh_far.h" #include "pldghost.h" #include "pheromone.h" #include "targeting.h" #include "dxlog.h" #include "los.h" #include "bh_alien.h" #include "bh_corpse.h" #include "bh_dummy.h" #include "player.h" #define UseLocalAssert TRUE #include "ourasert.h" #include "psnd.h" #define XENO_SENTRYTIME (20) #define FAR_XENO_ACTIVITY 0 #define FAR_XENO_FIRING 0 #define XENO_WALKING_ANIM_SPEED (ONE_FIXED<<1) #define XENO_TURNING_ANIM_SPEED (ONE_FIXED<<1) /* external global variables used in this file */ extern int ModuleArraySize; extern char *ModuleCurrVisArray; extern unsigned char Null_Name[8]; VECTORCH null_vec={0,0,0}; extern HIERARCHY_SHAPE_REPLACEMENT* GetHierarchyAlternateShapeSetFromLibrary(const char* rif_name,const char* shape_set_name); extern SECTION * GetNamedHierarchyFromLibrary(const char * rif_name, const char * hier_name); extern void HandleWeaponImpact(VECTORCH *positionPtr, STRATEGYBLOCK *sbPtr, enum AMMO_ID AmmoID, VECTORCH *directionPtr, int multiple, SECTION_DATA *section_pointer); int PrintDebuggingText(const char* t, ...); extern void CurrentGameStats_CreatureKilled(STRATEGYBLOCK *sbPtr, SECTION_DATA *sectionDataPtr); int ShowXenoStats=0; int RATweak=40; void EnforceXenoborgShapeAnimSequence_Core(STRATEGYBLOCK *sbPtr,HMODEL_SEQUENCE_TYPES type, int subtype, int length, int tweeningtime); void SetXenoborgShapeAnimSequence_Core(STRATEGYBLOCK *sbPtr,HMODEL_SEQUENCE_TYPES type, int subtype, int length, int tweeningtime); void SetXenoborgShapeAnimSequence(STRATEGYBLOCK *sbPtr,HMODEL_SEQUENCE_TYPES type, int subtype, int length); void XenoborgHandleMovingAnimation(STRATEGYBLOCK *sbPtr); static void ComputeDeltaValues(STRATEGYBLOCK *sbPtr); static void KillXeno(STRATEGYBLOCK *sbPtr,int wounds,DAMAGE_PROFILE *damage, int multiple,VECTORCH *incoming); void CreateXenoborg(VECTORCH *Position,int type); void Xenoborg_ActivateAllDeltas(STRATEGYBLOCK *sbPtr); void Xenoborg_DeactivateAllDeltas(STRATEGYBLOCK *sbPtr); STRATEGYBLOCK *Xenoborg_GetNewTarget(VECTORCH *xenopos, STRATEGYBLOCK *me); void Xenoborg_GetRelativeAngles(STRATEGYBLOCK *sbPtr, int *anglex, int *angley, VECTORCH *pivotPoint); void Xeno_UpdateTargetTrackPos(STRATEGYBLOCK *sbPtr); int Xeno_Activation_Test(STRATEGYBLOCK *sbPtr); void Xeno_HeadMovement_ScanLeftRight(STRATEGYBLOCK *sbPtr,int rate); void Xeno_HeadMovement_ScanUpDown(STRATEGYBLOCK *sbPtr,int rate); void Xeno_LeftArmMovement_TrackLeftRight(STRATEGYBLOCK *sbPtr,int rate); void Xeno_LeftArmMovement_TrackUpDown(STRATEGYBLOCK *sbPtr,int rate); void Xeno_RightArmMovement_TrackLeftRight(STRATEGYBLOCK *sbPtr,int rate); void Xeno_RightArmMovement_TrackUpDown(STRATEGYBLOCK *sbPtr,int rate); void Xeno_TorsoMovement_TrackLeftRight(STRATEGYBLOCK *sbPtr,int rate); void Xeno_LeftArmMovement_WaveUp(STRATEGYBLOCK *sbPtr,int rate); void Xeno_RightArmMovement_WaveUp(STRATEGYBLOCK *sbPtr,int rate); void Xeno_TorsoMovement_TrackToAngle(STRATEGYBLOCK *sbPtr,int rate,int in_anglex); void Xenoborg_MaintainLeftGun(STRATEGYBLOCK *sbPtr); void Xenoborg_MaintainRightGun(STRATEGYBLOCK *sbPtr); void Xeno_MaintainLasers(STRATEGYBLOCK *sbPtr); void Xeno_SwitchLED(STRATEGYBLOCK *sbPtr,int state); void Xeno_Stomp(STRATEGYBLOCK *sbPtr); void Xeno_MaintainSounds(STRATEGYBLOCK *sbPtr); int Xeno_HeadMovement_TrackToAngles(STRATEGYBLOCK *sbPtr,int rate,int in_anglex,int in_angley); void Xeno_TorsoMovement_TrackToAngles(STRATEGYBLOCK *sbPtr,int rate,int in_anglex); int Xeno_LeftArmMovement_TrackToAngles(STRATEGYBLOCK *sbPtr,int rate,int in_anglex,int in_angley); int Xeno_RightArmMovement_TrackToAngles(STRATEGYBLOCK *sbPtr,int rate,int in_anglex,int in_angley); void Xeno_TorsoMovement_Centre(STRATEGYBLOCK *sbPtr,int rate); void Xeno_LeftArmMovement_Centre(STRATEGYBLOCK *sbPtr,int rate); void Xeno_RightArmMovement_Centre(STRATEGYBLOCK *sbPtr,int rate); void Xeno_Limbs_ShootTheRoof(STRATEGYBLOCK *sbPtr); void Xeno_Enter_PowerUp_State(STRATEGYBLOCK *sbPtr); void Xeno_Enter_PowerDown_State(STRATEGYBLOCK *sbPtr); void Xeno_Enter_ActiveWait_State(STRATEGYBLOCK *sbPtr); void Xeno_Enter_Dormant_State(STRATEGYBLOCK *sbPtr); void Xeno_Enter_TurnToFace_State(STRATEGYBLOCK *sbPtr); void Xeno_Enter_Following_State(STRATEGYBLOCK *sbPtr); void Xeno_Enter_Returning_State(STRATEGYBLOCK *sbPtr); void Xeno_Enter_ShootingTheRoof_State(STRATEGYBLOCK *sbPtr); void Execute_Xeno_Dying(STRATEGYBLOCK *sbPtr); void Execute_Xeno_Inactive(STRATEGYBLOCK *sbPtr); void Execute_Xeno_PowerUp(STRATEGYBLOCK *sbPtr); void Execute_Xeno_PowerDown(STRATEGYBLOCK *sbPtr); void Execute_Xeno_ActiveWait(STRATEGYBLOCK *sbPtr); void Execute_Xeno_TurnToFace(STRATEGYBLOCK *sbPtr); void Execute_Xeno_Follow(STRATEGYBLOCK *sbPtr); void Execute_Xeno_Return(STRATEGYBLOCK *sbPtr); void Execute_Xeno_Avoidance(STRATEGYBLOCK *sbPtr); void Execute_Xeno_ShootTheRoof(STRATEGYBLOCK *sbPtr); void Execute_Xeno_ActiveWait_Far(STRATEGYBLOCK *sbPtr); void Execute_Xeno_TurnToFace_Far(STRATEGYBLOCK *sbPtr); void Execute_Xeno_Follow_Far(STRATEGYBLOCK *sbPtr); void Execute_Xeno_Return_Far(STRATEGYBLOCK *sbPtr); void Execute_Xeno_Avoidance_Far(STRATEGYBLOCK *sbPtr); int XenoActivation_FrustumReject(VECTORCH *localOffset); /* Begin Code! */ void CastXenoborg(void) { #define BOTRANGE 2000 VECTORCH position; if (AvP.Network!=I_No_Network) { NewOnScreenMessage("NO XENOBORGS IN MULTIPLAYER MODE"); return; } position=Player->ObStrategyBlock->DynPtr->Position; position.vx+=MUL_FIXED(Player->ObStrategyBlock->DynPtr->OrientMat.mat31,BOTRANGE); position.vy+=MUL_FIXED(Player->ObStrategyBlock->DynPtr->OrientMat.mat32,BOTRANGE); position.vz+=MUL_FIXED(Player->ObStrategyBlock->DynPtr->OrientMat.mat33,BOTRANGE); CreateXenoborg(&position, 0); } void CreateXenoborg(VECTORCH *Position,int type) { STRATEGYBLOCK* sbPtr; int i; /* create and initialise a strategy block */ sbPtr = CreateActiveStrategyBlock(); if(!sbPtr) { NewOnScreenMessage("FAILED TO CREATE BOT: SB CREATION FAILURE"); return; /* failure */ } InitialiseSBValues(sbPtr); sbPtr->I_SBtype = I_BehaviourXenoborg; AssignNewSBName(sbPtr); /* create, initialise and attach a dynamics block */ sbPtr->DynPtr = AllocateDynamicsBlock(DYNAMICS_TEMPLATE_SPRITE_NPC); if(sbPtr->DynPtr) { EULER zeroEuler = {0,0,0}; DYNAMICSBLOCK *dynPtr = sbPtr->DynPtr; GLOBALASSERT(dynPtr); dynPtr->PrevPosition = dynPtr->Position = *Position; dynPtr->OrientEuler = zeroEuler; CreateEulerMatrix(&dynPtr->OrientEuler, &dynPtr->OrientMat); TransposeMatrixCH(&dynPtr->OrientMat); dynPtr->Mass=500; /* As opposed to 160. */ } else { /* dynamics block allocation failed... */ RemoveBehaviourStrategy(sbPtr); NewOnScreenMessage("FAILED TO CREATE BOT: DYNBLOCK CREATION FAILURE"); return; } sbPtr->shapeIndex = 0; sbPtr->maintainVisibility = 1; sbPtr->containingModule = ModuleFromPosition(&(sbPtr->DynPtr->Position), (MODULE*)0); /* create, initialise and attach an alien data block */ sbPtr->SBdataptr = (void *)AllocateMem(sizeof(XENO_STATUS_BLOCK)); if(sbPtr->SBdataptr) { SECTION *root_section; XENO_STATUS_BLOCK *xenoStatus = (XENO_STATUS_BLOCK *)sbPtr->SBdataptr; NPC_InitMovementData(&(xenoStatus->moveData)); NPC_InitWanderData(&(xenoStatus->wanderData)); InitWaypointManager(&xenoStatus->waypointManager); /* Initialise xenoborg's stats */ { NPC_DATA *NpcData; NpcData=GetThisNpcData(I_NPC_Xenoborg); LOCALASSERT(NpcData); sbPtr->SBDamageBlock.Health=NpcData->StartingStats.Health<<ONE_FIXED_SHIFT; sbPtr->SBDamageBlock.Armour=NpcData->StartingStats.Armour<<ONE_FIXED_SHIFT; sbPtr->SBDamageBlock.SB_H_flags=NpcData->StartingStats.SB_H_flags; } xenoStatus->behaviourState=XS_Inactive; xenoStatus->lastState=XS_Inactive; xenoStatus->Target=NULL; COPY_NAME(xenoStatus->Target_SBname,Null_Name); xenoStatus->targetTrackPos.vx=0; xenoStatus->targetTrackPos.vy=0; xenoStatus->targetTrackPos.vz=0; xenoStatus->Wounds=0; xenoStatus->GibbFactor=0; xenoStatus->stateTimer=XENO_POWERDOWN_TIME; xenoStatus->my_module=sbPtr->containingModule->m_aimodule; xenoStatus->my_spot_therin=sbPtr->DynPtr->Position; { /* Pull out my_orientdir_therin. */ xenoStatus->my_orientdir_therin.vx=0; xenoStatus->my_orientdir_therin.vy=0; xenoStatus->my_orientdir_therin.vz=1000; RotateVector(&xenoStatus->my_orientdir_therin,&sbPtr->DynPtr->OrientMat); } xenoStatus->module_range=7; xenoStatus->UpTime=XENO_SENTRYTIME*ONE_FIXED; xenoStatus->Head_Pan=0; xenoStatus->Head_Tilt=0; xenoStatus->Left_Arm_Pan=0; xenoStatus->Left_Arm_Tilt=0; xenoStatus->Right_Arm_Pan=0; xenoStatus->Right_Arm_Tilt=0; xenoStatus->Torso_Twist=0; xenoStatus->headpandir=0; xenoStatus->headtiltdir=0; xenoStatus->leftarmpandir=0; xenoStatus->leftarmtiltdir=0; xenoStatus->rightarmpandir=0; xenoStatus->rightarmtiltdir=0; xenoStatus->torsotwistdir=0; xenoStatus->Old_Head_Pan=0; xenoStatus->Old_Head_Tilt=0; xenoStatus->Old_Left_Arm_Pan=0; xenoStatus->Old_Left_Arm_Tilt=0; xenoStatus->Old_Right_Arm_Pan=0; xenoStatus->Old_Right_Arm_Tilt=0; xenoStatus->Old_Torso_Twist=0; xenoStatus->headLock=0; xenoStatus->leftArmLock=0; xenoStatus->rightArmLock=0; xenoStatus->targetSightTest=0; xenoStatus->IAmFar=1; xenoStatus->ShotThisFrame=0; xenoStatus->obstruction.environment=0; xenoStatus->obstruction.destructableObject=0; xenoStatus->obstruction.otherCharacter=0; xenoStatus->obstruction.anySingleObstruction=0; /* Init beams. */ xenoStatus->LeftMainBeam.BeamIsOn = 0; xenoStatus->RightMainBeam.BeamIsOn = 0; xenoStatus->TargetingLaser[0].SourcePosition=null_vec; xenoStatus->TargetingLaser[0].TargetPosition=null_vec; xenoStatus->TargetingLaser[0].BeamHasHitPlayer=0; xenoStatus->TargetingLaser[0].BeamIsOn=0; xenoStatus->TargetingLaser[1].SourcePosition=null_vec; xenoStatus->TargetingLaser[1].TargetPosition=null_vec; xenoStatus->TargetingLaser[1].BeamHasHitPlayer=0; xenoStatus->TargetingLaser[1].BeamIsOn=0; xenoStatus->TargetingLaser[2].SourcePosition=null_vec; xenoStatus->TargetingLaser[2].TargetPosition=null_vec; xenoStatus->TargetingLaser[2].BeamHasHitPlayer=0; xenoStatus->TargetingLaser[2].BeamIsOn=0; xenoStatus->FiringLeft=0; xenoStatus->FiringRight=0; xenoStatus->UseHeadLaser=0; xenoStatus->UseLALaser=0; xenoStatus->UseRALaser=0; xenoStatus->head_moving=0; xenoStatus->la_moving=0; xenoStatus->ra_moving=0; xenoStatus->torso_moving=0; xenoStatus->HeadLaserOnTarget=0; xenoStatus->LALaserOnTarget=0; xenoStatus->RALaserOnTarget=0; xenoStatus->soundHandle1=SOUND_NOACTIVEINDEX; xenoStatus->soundHandle2=SOUND_NOACTIVEINDEX; xenoStatus->incidentFlag=0; xenoStatus->incidentTimer=0; xenoStatus->head_whirr=SOUND_NOACTIVEINDEX; xenoStatus->left_arm_whirr=SOUND_NOACTIVEINDEX; xenoStatus->right_arm_whirr=SOUND_NOACTIVEINDEX; xenoStatus->torso_whirr=SOUND_NOACTIVEINDEX; xenoStatus->HModelController.section_data=NULL; xenoStatus->HModelController.Deltas=NULL; for(i=0;i<SB_NAME_LENGTH;i++) xenoStatus->death_target_ID[i] =0; xenoStatus->death_target_sbptr=0; xenoStatus->death_target_request=0; root_section=GetNamedHierarchyFromLibrary("hnpc_xenoborg","xenobasic"); if (!root_section) { RemoveBehaviourStrategy(sbPtr); NewOnScreenMessage("FAILED TO CREATE BOT: NO HMODEL"); return; } Create_HModel(&xenoStatus->HModelController,root_section); InitHModelSequence(&xenoStatus->HModelController,HMSQT_Xenoborg,XBSS_Powered_Down_Standard,ONE_FIXED); { DELTA_CONTROLLER *delta; delta=Add_Delta_Sequence(&xenoStatus->HModelController,"HeadTilt",(int)HMSQT_Xenoborg,(int)XBSS_Head_Vertical_Delta,0); GLOBALASSERT(delta); delta->timer=32767; delta->Active=0; delta=Add_Delta_Sequence(&xenoStatus->HModelController,"HeadPan",(int)HMSQT_Xenoborg,(int)XBSS_Head_Horizontal_Delta,0); GLOBALASSERT(delta); delta->timer=32767; delta->Active=0; delta=Add_Delta_Sequence(&xenoStatus->HModelController,"LeftArmTilt",(int)HMSQT_Xenoborg,(int)XBSS_LeftArm_Vertical_Delta,0); GLOBALASSERT(delta); delta->timer=32767; delta->Active=0; delta=Add_Delta_Sequence(&xenoStatus->HModelController,"LeftArmPan",(int)HMSQT_Xenoborg,(int)XBSS_LeftArm_Horizontal_Delta,0); GLOBALASSERT(delta); delta->timer=32767; delta->Active=0; delta=Add_Delta_Sequence(&xenoStatus->HModelController,"RightArmTilt",(int)HMSQT_Xenoborg,(int)XBSS_RightArm_Vertical_Delta,0); GLOBALASSERT(delta); delta->timer=32767; delta->Active=0; delta=Add_Delta_Sequence(&xenoStatus->HModelController,"RightArmPan",(int)HMSQT_Xenoborg,(int)XBSS_RightArm_Horizontal_Delta,0); GLOBALASSERT(delta); delta->timer=32767; delta->Active=0; delta=Add_Delta_Sequence(&xenoStatus->HModelController,"TorsoTwist",(int)HMSQT_Xenoborg,(int)XBSS_Torso_Delta,0); GLOBALASSERT(delta); delta->timer=32767; delta->Active=0; } /* Containment test NOW! */ if(!(sbPtr->containingModule)) { /* no containing module can be found... abort*/ RemoveBehaviourStrategy(sbPtr); NewOnScreenMessage("FAILED TO CREATE BOT: MODULE CONTAINMENT FAILURE"); return; } LOCALASSERT(sbPtr->containingModule); Xeno_SwitchLED(sbPtr,0); MakeXenoborgNear(sbPtr); NewOnScreenMessage("XENOBORG CREATED"); } else { /* no data block can be allocated */ RemoveBehaviourStrategy(sbPtr); NewOnScreenMessage("FAILED TO CREATE BOT: MALLOC FAILURE"); return; } } static void VerifyDeltaControllers(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Nothing has deltas like a xenoborg does. */ xenoStatusPointer->head_pan=Get_Delta_Sequence(&xenoStatusPointer->HModelController,"HeadPan"); GLOBALASSERT(xenoStatusPointer->head_pan); xenoStatusPointer->head_tilt=Get_Delta_Sequence(&xenoStatusPointer->HModelController,"HeadTilt"); GLOBALASSERT(xenoStatusPointer->head_tilt); xenoStatusPointer->left_arm_pan=Get_Delta_Sequence(&xenoStatusPointer->HModelController,"LeftArmPan"); GLOBALASSERT(xenoStatusPointer->left_arm_pan); xenoStatusPointer->left_arm_tilt=Get_Delta_Sequence(&xenoStatusPointer->HModelController,"LeftArmTilt"); GLOBALASSERT(xenoStatusPointer->left_arm_tilt); xenoStatusPointer->right_arm_pan=Get_Delta_Sequence(&xenoStatusPointer->HModelController,"RightArmPan"); GLOBALASSERT(xenoStatusPointer->right_arm_pan); xenoStatusPointer->right_arm_tilt=Get_Delta_Sequence(&xenoStatusPointer->HModelController,"RightArmTilt"); GLOBALASSERT(xenoStatusPointer->right_arm_tilt); xenoStatusPointer->torso_twist=Get_Delta_Sequence(&xenoStatusPointer->HModelController,"TorsoTwist"); GLOBALASSERT(xenoStatusPointer->torso_twist); } /* Patrick 4/7/97 ---------------------------------------------------- Xenoborg initialiser, visibility management, behaviour shell, and damage functions ChrisF 6/7/98. I don't think so... --------------------------------------------------------------------*/ void InitXenoborgBehaviour(void* bhdata, STRATEGYBLOCK *sbPtr) { TOOLS_DATA_XENO *toolsData; int i; LOCALASSERT(bhdata); toolsData = (TOOLS_DATA_XENO *)bhdata; LOCALASSERT(sbPtr); /* check we're not in a net game */ if(AvP.Network != I_No_Network) { RemoveBehaviourStrategy(sbPtr); return; } /* make the assumption that the loader has initialised the strategy block sensibly... so just set the shapeIndex from the tools data & copy the name id*/ sbPtr->shapeIndex = toolsData->shapeIndex; for(i=0;i<SB_NAME_LENGTH;i++) sbPtr->SBname[i] = toolsData->nameID[i]; /* create, initialise and attach a dynamics block */ sbPtr->DynPtr = AllocateDynamicsBlock(DYNAMICS_TEMPLATE_SPRITE_NPC); if(sbPtr->DynPtr) { DYNAMICSBLOCK *dynPtr = sbPtr->DynPtr; GLOBALASSERT(dynPtr); dynPtr->PrevPosition = dynPtr->Position = toolsData->position; dynPtr->OrientEuler = toolsData->starteuler; CreateEulerMatrix(&dynPtr->OrientEuler, &dynPtr->OrientMat); TransposeMatrixCH(&dynPtr->OrientMat); dynPtr->Mass=1000; /* As opposed to 160. */ } else { /* dynamics block allocation failed... */ RemoveBehaviourStrategy(sbPtr); return; } sbPtr->maintainVisibility = 1; sbPtr->containingModule = ModuleFromPosition(&(sbPtr->DynPtr->Position), (MODULE*)0); /* create, initialise and attach a xeno data block */ sbPtr->SBdataptr = (void *)AllocateMem(sizeof(XENO_STATUS_BLOCK)); if(sbPtr->SBdataptr) { SECTION *root_section; XENO_STATUS_BLOCK *xenoStatus = (XENO_STATUS_BLOCK *)sbPtr->SBdataptr; NPC_InitMovementData(&(xenoStatus->moveData)); NPC_InitWanderData(&(xenoStatus->wanderData)); InitWaypointManager(&xenoStatus->waypointManager); /* Initialise xenoborg's stats */ { NPC_DATA *NpcData; NpcData=GetThisNpcData(I_NPC_Xenoborg); LOCALASSERT(NpcData); sbPtr->SBDamageBlock.Health=NpcData->StartingStats.Health<<ONE_FIXED_SHIFT; sbPtr->SBDamageBlock.Armour=NpcData->StartingStats.Armour<<ONE_FIXED_SHIFT; sbPtr->SBDamageBlock.SB_H_flags=NpcData->StartingStats.SB_H_flags; } xenoStatus->behaviourState=XS_Inactive; xenoStatus->lastState=XS_Inactive; xenoStatus->Target=NULL; COPY_NAME(xenoStatus->Target_SBname,Null_Name); xenoStatus->targetTrackPos.vx=0; xenoStatus->targetTrackPos.vy=0; xenoStatus->targetTrackPos.vz=0; xenoStatus->Wounds=0; xenoStatus->GibbFactor=0; xenoStatus->stateTimer=XENO_POWERDOWN_TIME; xenoStatus->my_module=sbPtr->containingModule->m_aimodule; xenoStatus->my_spot_therin=sbPtr->DynPtr->Position; { /* Pull out my_orientdir_therin. */ xenoStatus->my_orientdir_therin.vx=0; xenoStatus->my_orientdir_therin.vy=0; xenoStatus->my_orientdir_therin.vz=1000; RotateVector(&xenoStatus->my_orientdir_therin,&sbPtr->DynPtr->OrientMat); } xenoStatus->module_range=toolsData->ModuleRange; xenoStatus->UpTime=toolsData->UpTime*ONE_FIXED; xenoStatus->Head_Pan=0; xenoStatus->Head_Tilt=0; xenoStatus->Left_Arm_Pan=0; xenoStatus->Left_Arm_Tilt=0; xenoStatus->Right_Arm_Pan=0; xenoStatus->Right_Arm_Tilt=0; xenoStatus->Torso_Twist=0; xenoStatus->headpandir=0; xenoStatus->headtiltdir=0; xenoStatus->leftarmpandir=0; xenoStatus->leftarmtiltdir=0; xenoStatus->rightarmpandir=0; xenoStatus->rightarmtiltdir=0; xenoStatus->torsotwistdir=0; xenoStatus->Old_Head_Pan=0; xenoStatus->Old_Head_Tilt=0; xenoStatus->Old_Left_Arm_Pan=0; xenoStatus->Old_Left_Arm_Tilt=0; xenoStatus->Old_Right_Arm_Pan=0; xenoStatus->Old_Right_Arm_Tilt=0; xenoStatus->Old_Torso_Twist=0; xenoStatus->headLock=0; xenoStatus->leftArmLock=0; xenoStatus->rightArmLock=0; xenoStatus->targetSightTest=0; xenoStatus->IAmFar=1; xenoStatus->ShotThisFrame=0; xenoStatus->obstruction.environment=0; xenoStatus->obstruction.destructableObject=0; xenoStatus->obstruction.otherCharacter=0; xenoStatus->obstruction.anySingleObstruction=0; /* Init beams. */ xenoStatus->LeftMainBeam.BeamIsOn = 0; xenoStatus->RightMainBeam.BeamIsOn = 0; xenoStatus->TargetingLaser[0].SourcePosition=null_vec; xenoStatus->TargetingLaser[0].TargetPosition=null_vec; xenoStatus->TargetingLaser[0].BeamHasHitPlayer=0; xenoStatus->TargetingLaser[0].BeamIsOn=0; xenoStatus->TargetingLaser[1].SourcePosition=null_vec; xenoStatus->TargetingLaser[1].TargetPosition=null_vec; xenoStatus->TargetingLaser[1].BeamHasHitPlayer=0; xenoStatus->TargetingLaser[1].BeamIsOn=0; xenoStatus->TargetingLaser[2].SourcePosition=null_vec; xenoStatus->TargetingLaser[2].TargetPosition=null_vec; xenoStatus->TargetingLaser[2].BeamHasHitPlayer=0; xenoStatus->TargetingLaser[2].BeamIsOn=0; xenoStatus->FiringLeft=0; xenoStatus->FiringRight=0; xenoStatus->UseHeadLaser=0; xenoStatus->UseLALaser=0; xenoStatus->UseRALaser=0; xenoStatus->head_moving=0; xenoStatus->la_moving=0; xenoStatus->ra_moving=0; xenoStatus->torso_moving=0; xenoStatus->HeadLaserOnTarget=0; xenoStatus->LALaserOnTarget=0; xenoStatus->RALaserOnTarget=0; xenoStatus->soundHandle1=SOUND_NOACTIVEINDEX; xenoStatus->soundHandle2=SOUND_NOACTIVEINDEX; xenoStatus->incidentFlag=0; xenoStatus->incidentTimer=0; xenoStatus->head_whirr=SOUND_NOACTIVEINDEX; xenoStatus->left_arm_whirr=SOUND_NOACTIVEINDEX; xenoStatus->right_arm_whirr=SOUND_NOACTIVEINDEX; xenoStatus->torso_whirr=SOUND_NOACTIVEINDEX; xenoStatus->HModelController.section_data=NULL; xenoStatus->HModelController.Deltas=NULL; for(i=0;i<SB_NAME_LENGTH;i++) xenoStatus->death_target_ID[i] = toolsData->death_target_ID[i]; xenoStatus->death_target_sbptr=0; xenoStatus->death_target_request=toolsData->death_target_request; root_section=GetNamedHierarchyFromLibrary("hnpc_xenoborg","xenobasic"); GLOBALASSERT(root_section); Create_HModel(&xenoStatus->HModelController,root_section); InitHModelSequence(&xenoStatus->HModelController,HMSQT_Xenoborg,XBSS_Powered_Down_Standard,ONE_FIXED); { DELTA_CONTROLLER *delta; delta=Add_Delta_Sequence(&xenoStatus->HModelController,"HeadTilt",(int)HMSQT_Xenoborg,(int)XBSS_Head_Vertical_Delta,0); GLOBALASSERT(delta); delta->timer=32767; delta->Active=0; delta=Add_Delta_Sequence(&xenoStatus->HModelController,"HeadPan",(int)HMSQT_Xenoborg,(int)XBSS_Head_Horizontal_Delta,0); GLOBALASSERT(delta); delta->timer=32767; delta->Active=0; delta=Add_Delta_Sequence(&xenoStatus->HModelController,"LeftArmTilt",(int)HMSQT_Xenoborg,(int)XBSS_LeftArm_Vertical_Delta,0); GLOBALASSERT(delta); delta->timer=32767; delta->Active=0; delta=Add_Delta_Sequence(&xenoStatus->HModelController,"LeftArmPan",(int)HMSQT_Xenoborg,(int)XBSS_LeftArm_Horizontal_Delta,0); GLOBALASSERT(delta); delta->timer=32767; delta->Active=0; delta=Add_Delta_Sequence(&xenoStatus->HModelController,"RightArmTilt",(int)HMSQT_Xenoborg,(int)XBSS_RightArm_Vertical_Delta,0); GLOBALASSERT(delta); delta->timer=32767; delta->Active=0; delta=Add_Delta_Sequence(&xenoStatus->HModelController,"RightArmPan",(int)HMSQT_Xenoborg,(int)XBSS_RightArm_Horizontal_Delta,0); GLOBALASSERT(delta); delta->timer=32767; delta->Active=0; delta=Add_Delta_Sequence(&xenoStatus->HModelController,"TorsoTwist",(int)HMSQT_Xenoborg,(int)XBSS_Torso_Delta,0); GLOBALASSERT(delta); delta->timer=32767; delta->Active=0; } /* Containment test NOW! */ GLOBALASSERT(sbPtr->containingModule); Xeno_SwitchLED(sbPtr,0); } else { /* no data block can be allocated */ RemoveBehaviourStrategy(sbPtr); return; } } void XenoborgBehaviour(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; NPC_DATA *NpcData; int xenoborgIsNear; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); NpcData=GetThisNpcData(I_NPC_Xenoborg); /* test if we've got a containing module: if we haven't, do nothing. This is important as the object could have been marked for deletion by the visibility management system...*/ if(!sbPtr->containingModule) { DestroyAnyStrategyBlock(sbPtr); /* just to make sure */ return; } if(sbPtr->SBdptr) { xenoborgIsNear=1; LOCALASSERT(ModuleCurrVisArray[(sbPtr->containingModule->m_index)]); } else { xenoborgIsNear=0; } VerifyDeltaControllers(sbPtr); #if 0 /* zero velocity */ LOCALASSERT(sbPtr->DynPtr); sbPtr->DynPtr->LinVelocity.vx = 0; sbPtr->DynPtr->LinVelocity.vy = 0; sbPtr->DynPtr->LinVelocity.vz = 0; #endif InitWaypointSystem(0); if (sbPtr->SBdptr) { xenoStatusPointer->IAmFar=0; } else { xenoStatusPointer->IAmFar=1; } /* Store angles. */ xenoStatusPointer->Old_Head_Pan =xenoStatusPointer->Head_Pan; xenoStatusPointer->Old_Head_Tilt =xenoStatusPointer->Head_Tilt; xenoStatusPointer->Old_Left_Arm_Pan =xenoStatusPointer->Left_Arm_Pan; xenoStatusPointer->Old_Left_Arm_Tilt =xenoStatusPointer->Left_Arm_Tilt; xenoStatusPointer->Old_Right_Arm_Pan =xenoStatusPointer->Right_Arm_Pan; xenoStatusPointer->Old_Right_Arm_Tilt =xenoStatusPointer->Right_Arm_Tilt; xenoStatusPointer->Old_Torso_Twist =xenoStatusPointer->Torso_Twist; xenoStatusPointer->head_moving=0; xenoStatusPointer->la_moving=0; xenoStatusPointer->ra_moving=0; xenoStatusPointer->torso_moving=0; /* Target handling. */ if (Validate_Target(xenoStatusPointer->Target,xenoStatusPointer->Target_SBname)==0) { xenoStatusPointer->Target=NULL; } xenoStatusPointer->FiringLeft=0; xenoStatusPointer->FiringRight=0; xenoStatusPointer->UseHeadLaser=0; xenoStatusPointer->UseLALaser=0; xenoStatusPointer->UseRALaser=0; xenoStatusPointer->LeftMainBeam.BeamIsOn = 0; xenoStatusPointer->RightMainBeam.BeamIsOn = 0; xenoStatusPointer->TargetingLaser[0].BeamIsOn=0; xenoStatusPointer->TargetingLaser[1].BeamIsOn=0; xenoStatusPointer->TargetingLaser[2].BeamIsOn=0; if (xenoStatusPointer->Target==NULL) { if ((xenoborgIsNear)||(xenoStatusPointer->incidentFlag)) { /* Get new target. */ xenoStatusPointer->Target=Xenoborg_GetNewTarget(&sbPtr->DynPtr->Position,sbPtr); xenoStatusPointer->targetSightTest=0; if (xenoStatusPointer->Target) { COPY_NAME(xenoStatusPointer->Target_SBname,xenoStatusPointer->Target->SBname); xenoStatusPointer->targetSightTest=1; } Xeno_UpdateTargetTrackPos(sbPtr); xenoStatusPointer->headLock=0; xenoStatusPointer->leftArmLock=0; xenoStatusPointer->rightArmLock=0; } } else if (NPCCanSeeTarget(sbPtr,xenoStatusPointer->Target,XENO_NEAR_VIEW_WIDTH)) { Xeno_UpdateTargetTrackPos(sbPtr); xenoStatusPointer->targetSightTest=1; } else { /* We have a target that we can't see. */ xenoStatusPointer->headLock=0; xenoStatusPointer->leftArmLock=0; xenoStatusPointer->rightArmLock=0; xenoStatusPointer->targetSightTest=0; } if (xenoStatusPointer->GibbFactor) { /* If you're gibbed, you're dead. */ sbPtr->SBDamageBlock.Health = 0; } /* Unset incident flag. */ xenoStatusPointer->incidentFlag=0; xenoStatusPointer->incidentTimer-=NormalFrameTime; if (xenoStatusPointer->incidentTimer<0) { xenoStatusPointer->incidentFlag=1; xenoStatusPointer->incidentTimer=32767+(FastRandom()&65535); } if (sbPtr->SBDamageBlock.IsOnFire) { /* Why not? */ CauseDamageToObject(sbPtr,&firedamage,NormalFrameTime,NULL); if (sbPtr->I_SBtype==I_BehaviourNetCorpse) { /* Gettin' out of here... */ return; } if (xenoStatusPointer->incidentFlag) { if ((FastRandom()&65535)<32767) { sbPtr->SBDamageBlock.IsOnFire=0; } } } /* Now, switch by state. */ switch (xenoStatusPointer->behaviourState) { case XS_ActiveWait: if (xenoStatusPointer->IAmFar) { Execute_Xeno_ActiveWait_Far(sbPtr); } else { Execute_Xeno_ActiveWait(sbPtr); } break; case XS_TurnToFace: if (xenoStatusPointer->IAmFar) { Execute_Xeno_TurnToFace_Far(sbPtr); } else { Execute_Xeno_TurnToFace(sbPtr); } break; case XS_Following: if (xenoStatusPointer->IAmFar) { Execute_Xeno_Follow_Far(sbPtr); } else { Execute_Xeno_Follow(sbPtr); } break; case XS_Returning: if (xenoStatusPointer->IAmFar) { Execute_Xeno_Return_Far(sbPtr); } else { Execute_Xeno_Return(sbPtr); } break; case XS_Avoidance: if (xenoStatusPointer->IAmFar) { Execute_Xeno_Avoidance_Far(sbPtr); } else { Execute_Xeno_Avoidance(sbPtr); } break; case XS_Inactive: Execute_Xeno_Inactive(sbPtr); break; case XS_Activating: Execute_Xeno_PowerUp(sbPtr); break; case XS_Deactivating: Execute_Xeno_PowerDown(sbPtr); break; case XS_Regenerating: break; case XS_Dying: Execute_Xeno_Dying(sbPtr); break; case XS_ShootingTheRoof: Execute_Xeno_ShootTheRoof(sbPtr); break; default: /* No action? */ break; } /* if we have actually died, we need to remove the strategyblock... so do this here */ if((xenoStatusPointer->behaviourState == XS_Dying)&&(xenoStatusPointer->stateTimer <= 0)) { DestroyAnyStrategyBlock(sbPtr); } if ((xenoStatusPointer->behaviourState!=XS_Dying) &&(xenoStatusPointer->behaviourState!=XS_Inactive) &&(xenoStatusPointer->behaviourState!=XS_Activating) &&(xenoStatusPointer->behaviourState!=XS_Deactivating)) { /* Time to regenerate? */ if ((sbPtr->SBDamageBlock.Health<(NpcData->StartingStats.Health<<(ONE_FIXED_SHIFT-2))) &&(sbPtr->SBDamageBlock.Health>0)) { /* 25% health or less. */ Xeno_Enter_PowerDown_State(sbPtr); } } ComputeDeltaValues(sbPtr); ProveHModel_Far(&xenoStatusPointer->HModelController,sbPtr); #if (FAR_XENO_FIRING==0) if (xenoStatusPointer->IAmFar) { xenoStatusPointer->FiringLeft=0; xenoStatusPointer->FiringRight=0; } #endif /* Now lets deal with the sounds. */ Xeno_MaintainSounds(sbPtr); if (xenoStatusPointer->IAmFar) { /* No lasers if far. */ xenoStatusPointer->UseHeadLaser=0; xenoStatusPointer->UseLALaser=0; xenoStatusPointer->UseRALaser=0; } /* Now consider the lasers. */ Xeno_MaintainLasers(sbPtr); Xeno_Stomp(sbPtr); /* Now, are we firing? */ Xenoborg_MaintainLeftGun(sbPtr); Xenoborg_MaintainRightGun(sbPtr); /* Unset shot flag. */ xenoStatusPointer->ShotThisFrame=0; } void MakeXenoborgNear(STRATEGYBLOCK *sbPtr) { extern MODULEMAPBLOCK AlienDefaultMap; MODULE tempModule; DISPLAYBLOCK *dPtr; DYNAMICSBLOCK *dynPtr; XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); dynPtr = sbPtr->DynPtr; xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); LOCALASSERT(dynPtr); LOCALASSERT(sbPtr->SBdptr == NULL); AlienDefaultMap.MapShape = sbPtr->shapeIndex; tempModule.m_mapptr = &AlienDefaultMap; tempModule.m_sbptr = (STRATEGYBLOCK*)NULL; tempModule.m_numlights = 0; tempModule.m_lightarray = (struct lightblock *)0; tempModule.m_extraitemdata = (struct extraitemdata *)0; tempModule.m_dptr = NULL; AllocateModuleObject(&tempModule); dPtr = tempModule.m_dptr; if(dPtr==NULL) return; /* if cannot create displayblock, leave far */ sbPtr->SBdptr = dPtr; dPtr->ObStrategyBlock = sbPtr; dPtr->ObMyModule = NULL; /* need to initialise positional information in the new display block */ dPtr->ObWorld = dynPtr->Position; dPtr->ObEuler = dynPtr->OrientEuler; dPtr->ObMat = dynPtr->OrientMat; /* zero linear velocity in dynamics block */ sbPtr->DynPtr->LinVelocity.vx = 0; sbPtr->DynPtr->LinVelocity.vy = 0; sbPtr->DynPtr->LinVelocity.vz = 0; /* state and sequence init */ NPC_InitMovementData(&(xenoStatusPointer->moveData)); InitWaypointManager(&xenoStatusPointer->waypointManager); dPtr->ShapeAnimControlBlock = NULL; dPtr->ObTxAnimCtrlBlks = NULL; dPtr->HModelControlBlock=&xenoStatusPointer->HModelController; ProveHModel(dPtr->HModelControlBlock,dPtr); xenoStatusPointer->IAmFar=0; /* make a sound */ //Sound_Play(SID_ALIEN_HISS,"d",&sbPtr->DynPtr->Position); } void MakeXenoborgFar(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; int i; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); LOCALASSERT(sbPtr->SBdptr != NULL); /* get rid of the displayblock */ i = DestroyActiveObject(sbPtr->SBdptr); LOCALASSERT(i==0); sbPtr->SBdptr = NULL; /* xenoborg data block init */ if(xenoStatusPointer->behaviourState != XS_Dying) { xenoStatusPointer->stateTimer=0; } /* zero linear velocity in dynamics block */ sbPtr->DynPtr->LinVelocity.vx = 0; sbPtr->DynPtr->LinVelocity.vy = 0; sbPtr->DynPtr->LinVelocity.vz = 0; xenoStatusPointer->IAmFar=1; } void Xenoborg_ActivateAllDeltas(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); if (xenoStatusPointer->head_pan) { xenoStatusPointer->head_pan->Active=1; } if (xenoStatusPointer->head_tilt) { xenoStatusPointer->head_tilt->Active=1; } if (xenoStatusPointer->left_arm_pan) { xenoStatusPointer->left_arm_pan->Active=1; } if (xenoStatusPointer->left_arm_tilt) { xenoStatusPointer->left_arm_tilt->Active=1; } if (xenoStatusPointer->right_arm_pan) { xenoStatusPointer->right_arm_pan->Active=1; } if (xenoStatusPointer->right_arm_tilt) { xenoStatusPointer->right_arm_tilt->Active=1; } if (xenoStatusPointer->torso_twist) { xenoStatusPointer->torso_twist->Active=1; } } void Xenoborg_DeactivateAllDeltas(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); if (xenoStatusPointer->head_pan) { xenoStatusPointer->head_pan->Active=0; } xenoStatusPointer->Head_Pan=0; if (xenoStatusPointer->head_tilt) { xenoStatusPointer->head_tilt->Active=0; } xenoStatusPointer->Head_Tilt=0; if (xenoStatusPointer->left_arm_pan) { xenoStatusPointer->left_arm_pan->Active=0; } xenoStatusPointer->Left_Arm_Pan=0; if (xenoStatusPointer->left_arm_tilt) { xenoStatusPointer->left_arm_tilt->Active=0; } xenoStatusPointer->Left_Arm_Tilt=0; if (xenoStatusPointer->right_arm_pan) { xenoStatusPointer->right_arm_pan->Active=0; } xenoStatusPointer->Right_Arm_Pan=0; if (xenoStatusPointer->right_arm_tilt) { xenoStatusPointer->right_arm_tilt->Active=0; } xenoStatusPointer->Right_Arm_Tilt=0; if (xenoStatusPointer->torso_twist) { xenoStatusPointer->torso_twist->Active=0; } xenoStatusPointer->Torso_Twist=0; } void XenoborgIsDamaged(STRATEGYBLOCK *sbPtr, DAMAGE_PROFILE *damage, int multiple, int wounds,VECTORCH *incoming) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); LOCALASSERT(sbPtr->DynPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); xenoStatusPointer->Wounds|=wounds; xenoStatusPointer->ShotThisFrame=1; if (sbPtr->SBDamageBlock.Health <= 0) { /* Oh yes, kill them, too. */ if (xenoStatusPointer->behaviourState!=XS_Dying) { CurrentGameStats_CreatureKilled(sbPtr,NULL); KillXeno(sbPtr,wounds,damage,multiple,incoming); } } if (xenoStatusPointer->behaviourState==XS_Inactive) { if (xenoStatusPointer->stateTimer>=XENO_POWERDOWN_TIME) { /* Ow, that hurt. */ Xeno_Enter_PowerUp_State(sbPtr); } } xenoStatusPointer->Target=NULL; } /* patrick 29/7/97 ----------------------------------- Thess functions to be called only from behaviour ------------------------------------------------------*/ static void KillXeno(STRATEGYBLOCK *sbPtr,int wounds,DAMAGE_PROFILE *damage, int multiple,VECTORCH *incoming) { XENO_STATUS_BLOCK *xenoStatusPointer; int deathtype,tkd; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* make an explosion sound */ Sound_Play(SID_SENTRYGUNDEST,"d",&sbPtr->DynPtr->Position); xenoStatusPointer->stateTimer=XENO_DYINGTIME; xenoStatusPointer->HModelController.Looped=0; xenoStatusPointer->HModelController.LoopAfterTweening=0; /* switch state */ xenoStatusPointer->behaviourState=XS_Dying; Xenoborg_DeactivateAllDeltas(sbPtr); Xeno_SwitchLED(sbPtr,0); if(xenoStatusPointer->death_target_sbptr) { RequestState(xenoStatusPointer->death_target_sbptr,xenoStatusPointer->death_target_request, 0); } if (xenoStatusPointer->soundHandle1!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->soundHandle1); } if (xenoStatusPointer->soundHandle2!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->soundHandle2); } if (xenoStatusPointer->head_whirr!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->head_whirr); } if (xenoStatusPointer->left_arm_whirr!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->left_arm_whirr); } if (xenoStatusPointer->right_arm_whirr!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->right_arm_whirr); } if (xenoStatusPointer->torso_whirr!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->torso_whirr); } /* Set up gibb factor. */ tkd=TotalKineticDamage(damage); deathtype=0; if (tkd>40) { /* Explosion case. */ if (MUL_FIXED(tkd,(multiple&((ONE_FIXED<<1)-1)))>20) { /* Okay, you can gibb now. */ xenoStatusPointer->GibbFactor=-(ONE_FIXED>>3); deathtype=2; } } else if ( (multiple>>16)>1 ) { int newmult; newmult=DIV_FIXED(multiple,NormalFrameTime); if (MUL_FIXED(tkd,newmult)>700) { /* Excessive bullets case 1. */ xenoStatusPointer->GibbFactor=-(ONE_FIXED>>5); deathtype=2; } else if (MUL_FIXED(tkd,newmult)>250) { /* Excessive bullets case 2. */ //xenoStatusPointer->GibbFactor=ONE_FIXED>>6; deathtype=1; } } if (tkd>200) { /* Basically SADARS only. */ xenoStatusPointer->GibbFactor=-(ONE_FIXED>>2); deathtype=3; } /* No gibbing for flamethrower. */ { SECTION_DATA *chest=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"chest"); if (chest==NULL) { /* I'm impressed. */ deathtype+=2; } else if ((chest->flags&section_data_notreal) &&(chest->flags&section_data_terminate_here)) { /* That's gotta hurt. */ deathtype++; } } { DEATH_DATA *this_death; HIT_FACING facing; facing.Front=0; facing.Back=0; facing.Left=0; facing.Right=0; if (incoming) { if (incoming->vz>0) { facing.Back=1; } else { facing.Front=1; } if (incoming->vx>0) { facing.Right=1; } else { facing.Left=1; } } this_death=GetXenoborgDeathSequence(&xenoStatusPointer->HModelController,NULL, xenoStatusPointer->Wounds,(xenoStatusPointer->Wounds&( section_flag_left_leg|section_flag_right_leg|section_flag_left_foot|section_flag_right_foot)), deathtype,&facing,0,0,0); GLOBALASSERT(this_death); Convert_Xenoborg_To_Corpse(sbPtr,this_death); } } void Execute_Xeno_Dying(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); { DISPLAYBLOCK *dispPtr = sbPtr->SBdptr; /* do we have a displayblock? */ if (dispPtr) { dispPtr->SpecialFXFlags |= SFXFLAG_MELTINGINTOGROUND; dispPtr->ObFlags2 = xenoStatusPointer->stateTimer/2; if (dispPtr->ObFlags2<ONE_FIXED) { xenoStatusPointer->HModelController.DisableBleeding=1; } } } xenoStatusPointer->stateTimer -= NormalFrameTime; } void EnforceXenoborgShapeAnimSequence_Core(STRATEGYBLOCK *sbPtr,HMODEL_SEQUENCE_TYPES type, int subtype, int length, int tweeningtime) { XENO_STATUS_BLOCK *xenoStatus; xenoStatus=(XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); if ((xenoStatus->HModelController.Sequence_Type==type) &&(xenoStatus->HModelController.Sub_Sequence==subtype)) { return; } else { SetXenoborgShapeAnimSequence_Core(sbPtr,type,subtype,length,tweeningtime); } } void SetXenoborgShapeAnimSequence_Core(STRATEGYBLOCK *sbPtr,HMODEL_SEQUENCE_TYPES type, int subtype, int length, int tweeningtime) { XENO_STATUS_BLOCK *xenoStatus=(XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); GLOBALASSERT(length!=0); if (tweeningtime<=0) { InitHModelSequence(&xenoStatus->HModelController,(int)type,subtype,length); } else { InitHModelTweening(&xenoStatus->HModelController, tweeningtime, (int)type,subtype,length, 1); //xenoStatus->HModelController.ElevationTweening=1; } xenoStatus->HModelController.Playing=1; /* Might be unset... */ } void SetXenoborgShapeAnimSequence(STRATEGYBLOCK *sbPtr,HMODEL_SEQUENCE_TYPES type, int subtype, int length) { SetXenoborgShapeAnimSequence_Core(sbPtr,type,subtype,length,(ONE_FIXED>>2)); } void Xenoborg_GetRelativeAngles(STRATEGYBLOCK *sbPtr, int *anglex, int *angley, VECTORCH *pivotPoint) { XENO_STATUS_BLOCK *xenoStatusPointer; MATRIXCH WtoL; VECTORCH targetPos; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* First, extract relative angle. */ WtoL=sbPtr->DynPtr->OrientMat; TransposeMatrixCH(&WtoL); targetPos=xenoStatusPointer->targetTrackPos; targetPos.vx-=pivotPoint->vx; targetPos.vy-=pivotPoint->vy; targetPos.vz-=pivotPoint->vz; RotateVector(&targetPos,&WtoL); /* Now... */ { int offsetx,offsety,offsetz,offseta; offsetx=(targetPos.vx); offsety=(targetPos.vz); offseta=-(targetPos.vy); while( (offsetx>(ONE_FIXED>>2)) ||(offsety>(ONE_FIXED>>2)) ||(offseta>(ONE_FIXED>>2)) ||(offsetx<-(ONE_FIXED>>2)) ||(offsety<-(ONE_FIXED>>2)) ||(offseta<-(ONE_FIXED>>2))) { offsetx>>=1; offsety>>=1; offseta>>=1; } offsetz=SqRoot32((offsetx*offsetx)+(offsety*offsety)); if (angley) { (*angley)=ArcTan(offseta,offsetz); if ((*angley)>=3072) (*angley)-=4096; if ((*angley)>=2048) (*angley)=(*angley)-3072; if ((*angley)> 1024) (*angley)=2048-(*angley); } if (anglex) { (*anglex)=ArcTan(offsetx,offsety); if ((*anglex)>=3072) (*anglex)-=4096; if ((*anglex)>=2048) (*anglex)=(*anglex)-4096; } } } void Execute_Xeno_Inactive(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; NPC_DATA *NpcData; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); NpcData=GetThisNpcData(I_NPC_Xenoborg); if (ShowXenoStats) { PrintDebuggingText("In Inactive.\n"); } if (!sbPtr->SBdptr) { /* We're far... do the timer! */ ProveHModel_Far(&xenoStatusPointer->HModelController,sbPtr); } /* Regenerate a bit? */ if (sbPtr->SBDamageBlock.Health>0) { int health_increment; health_increment=DIV_FIXED((NpcData->StartingStats.Health*NormalFrameTime),XENO_REGEN_TIME); sbPtr->SBDamageBlock.Health+=health_increment; if (sbPtr->SBDamageBlock.Health>(NpcData->StartingStats.Health<<ONE_FIXED_SHIFT)) { sbPtr->SBDamageBlock.Health=(NpcData->StartingStats.Health<<ONE_FIXED_SHIFT); } HModel_Regen(&xenoStatusPointer->HModelController,XENO_REGEN_TIME); } if (xenoStatusPointer->stateTimer<XENO_POWERDOWN_TIME) { xenoStatusPointer->stateTimer+=NormalFrameTime; } else { /* Tum te tum te tum. */ if (Xeno_Activation_Test(sbPtr)) { /* Oh well, orange alert. */ Xeno_Enter_PowerUp_State(sbPtr); } } } void Xeno_Enter_PowerUp_State(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); if (xenoStatusPointer->behaviourState!=XS_Inactive) { /* Ha! */ return; } xenoStatusPointer->Target=NULL; xenoStatusPointer->stateTimer=0; xenoStatusPointer->behaviourState=XS_Activating; GLOBALASSERT(xenoStatusPointer->HModelController.Sequence_Type==HMSQT_Xenoborg); GLOBALASSERT(xenoStatusPointer->HModelController.Sub_Sequence==XBSS_Powered_Down_Standard); SetXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Power_Up,(ONE_FIXED*4),(ONE_FIXED>>2)); xenoStatusPointer->HModelController.LoopAfterTweening=0; Xenoborg_ActivateAllDeltas(sbPtr); Xeno_SwitchLED(sbPtr,1); /* Now play with a sound. */ if (xenoStatusPointer->soundHandle1!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->soundHandle1); } if (xenoStatusPointer->soundHandle2!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->soundHandle2); } Sound_Play(SID_POWERUP,"de",&sbPtr->DynPtr->Position,&xenoStatusPointer->soundHandle1); } void Xeno_Enter_PowerDown_State(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); if (xenoStatusPointer->behaviourState==XS_Inactive) { /* Ha! */ return; } xenoStatusPointer->Target=NULL; xenoStatusPointer->stateTimer=0; xenoStatusPointer->behaviourState=XS_Deactivating; SetXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Power_Down,ONE_FIXED,(ONE_FIXED>>2)); xenoStatusPointer->HModelController.LoopAfterTweening=0; /* zero velocity */ LOCALASSERT(sbPtr->DynPtr); sbPtr->DynPtr->LinVelocity.vx = 0; sbPtr->DynPtr->LinVelocity.vy = 0; sbPtr->DynPtr->LinVelocity.vz = 0; Xenoborg_DeactivateAllDeltas(sbPtr); Xeno_SwitchLED(sbPtr,0); if (xenoStatusPointer->soundHandle1!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->soundHandle1); } if (xenoStatusPointer->soundHandle2!=SOUND_NOACTIVEINDEX) { /* Stop BorgOn. */ Sound_Stop(xenoStatusPointer->soundHandle2); } Sound_Play(SID_POWERDN,"de",&sbPtr->DynPtr->Position,&xenoStatusPointer->soundHandle1); } void Xeno_Enter_ActiveWait_State(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); xenoStatusPointer->stateTimer=0; xenoStatusPointer->behaviourState=XS_ActiveWait; SetXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Powered_Up_Standard,ONE_FIXED,(ONE_FIXED>>2)); /* zero velocity */ LOCALASSERT(sbPtr->DynPtr); sbPtr->DynPtr->LinVelocity.vx = 0; sbPtr->DynPtr->LinVelocity.vy = 0; sbPtr->DynPtr->LinVelocity.vz = 0; if (xenoStatusPointer->soundHandle1!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->soundHandle1); } } void Xeno_Enter_TurnToFace_State(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); xenoStatusPointer->stateTimer=0; xenoStatusPointer->behaviourState=XS_TurnToFace; /* Sequence handled in the behaviour. */ if (xenoStatusPointer->soundHandle1!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->soundHandle1); } Sound_Play(SID_LOADMOVE,"del",&sbPtr->DynPtr->Position,&xenoStatusPointer->soundHandle1); /* zero velocity */ LOCALASSERT(sbPtr->DynPtr); sbPtr->DynPtr->LinVelocity.vx = 0; sbPtr->DynPtr->LinVelocity.vy = 0; sbPtr->DynPtr->LinVelocity.vz = 0; } void Xeno_Enter_Following_State(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); xenoStatusPointer->stateTimer=0; xenoStatusPointer->behaviourState=XS_Following; InitWaypointManager(&xenoStatusPointer->waypointManager); /* Sequence handled in the behaviour. */ if (xenoStatusPointer->soundHandle1!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->soundHandle1); } Sound_Play(SID_LOADMOVE,"del",&sbPtr->DynPtr->Position,&xenoStatusPointer->soundHandle1); } void Xeno_Enter_Returning_State(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); xenoStatusPointer->stateTimer=0; xenoStatusPointer->behaviourState=XS_Returning; InitWaypointManager(&xenoStatusPointer->waypointManager); /* Sequence handled in the behaviour. */ xenoStatusPointer->Target=NULL; /* Forget your target, too. */ if (xenoStatusPointer->soundHandle1!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->soundHandle1); } Sound_Play(SID_LOADMOVE,"del",&sbPtr->DynPtr->Position,&xenoStatusPointer->soundHandle1); } void Xeno_Enter_Dormant_State(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); xenoStatusPointer->stateTimer=0; xenoStatusPointer->behaviourState=XS_Inactive; SetXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Powered_Down_Standard,ONE_FIXED,(ONE_FIXED>>2)); if (xenoStatusPointer->soundHandle2!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->soundHandle2); } /* soundHandle1 might be still powering down. */ /* zero velocity */ LOCALASSERT(sbPtr->DynPtr); sbPtr->DynPtr->LinVelocity.vx = 0; sbPtr->DynPtr->LinVelocity.vy = 0; sbPtr->DynPtr->LinVelocity.vz = 0; } void Xeno_Enter_Avoidance_State(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Make sure obstruction is set! */ NPC_InitMovementData(&(xenoStatusPointer->moveData)); NPCGetAvoidanceDirection(sbPtr, &(xenoStatusPointer->moveData.avoidanceDirn),&xenoStatusPointer->obstruction); xenoStatusPointer->lastState=xenoStatusPointer->behaviourState; xenoStatusPointer->behaviourState = XS_Avoidance; xenoStatusPointer->stateTimer = NPC_AVOIDTIME; InitWaypointManager(&xenoStatusPointer->waypointManager); if (xenoStatusPointer->soundHandle1!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->soundHandle1); } Sound_Play(SID_LOADMOVE,"del",&sbPtr->DynPtr->Position,&xenoStatusPointer->soundHandle1); } void Xeno_Enter_ShootingTheRoof_State(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); xenoStatusPointer->stateTimer=0; xenoStatusPointer->behaviourState=XS_ShootingTheRoof; /* Sequence handled in the behaviour. */ if (xenoStatusPointer->soundHandle1!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->soundHandle1); } Sound_Play(SID_LOADMOVE,"del",&sbPtr->DynPtr->Position,&xenoStatusPointer->soundHandle1); /* zero velocity */ LOCALASSERT(sbPtr->DynPtr); sbPtr->DynPtr->LinVelocity.vx = 0; sbPtr->DynPtr->LinVelocity.vy = 0; sbPtr->DynPtr->LinVelocity.vz = 0; } void Xeno_CopeWithLossOfHome(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Ooh, yuck. */ xenoStatusPointer->my_module=sbPtr->containingModule->m_aimodule; xenoStatusPointer->my_spot_therin=sbPtr->DynPtr->Position; } void Execute_Xeno_PowerUp(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Wait to finish, I guess... */ if (ShowXenoStats) { PrintDebuggingText("In PowerUp.\n"); } if (!sbPtr->SBdptr) { /* We're far... do the timer! */ ProveHModel_Far(&xenoStatusPointer->HModelController,sbPtr); } xenoStatusPointer->Target=NULL; xenoStatusPointer->stateTimer+=NormalFrameTime; if (xenoStatusPointer->soundHandle2==SOUND_NOACTIVEINDEX) { if (xenoStatusPointer->stateTimer>((ONE_FIXED*5)/2)) { /* Time to start the BorgOn sound. */ Sound_Play(SID_BORGON,"del",&sbPtr->DynPtr->Position,&xenoStatusPointer->soundHandle2); } } if ((xenoStatusPointer->HModelController.Tweening==Controller_NoTweening) &&(xenoStatusPointer->HModelController.sequence_timer==(ONE_FIXED-1))) { Xeno_Enter_ActiveWait_State(sbPtr); } } void Execute_Xeno_PowerDown(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); if (ShowXenoStats) { PrintDebuggingText("In PowerDown.\n"); } EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Power_Down,ONE_FIXED,(ONE_FIXED>>2)); xenoStatusPointer->HModelController.LoopAfterTweening=0; xenoStatusPointer->HModelController.Looped=0; if (!sbPtr->SBdptr) { /* We're far... do the timer! */ ProveHModel_Far(&xenoStatusPointer->HModelController,sbPtr); } /* Wait to finish, I guess... */ xenoStatusPointer->Target=NULL; if ((xenoStatusPointer->HModelController.Tweening==Controller_NoTweening) &&(xenoStatusPointer->HModelController.sequence_timer==(ONE_FIXED-1))) { Xeno_Enter_Dormant_State(sbPtr); } } void Xeno_TurnAndTarget(STRATEGYBLOCK *sbPtr, int *ref_anglex,int *ref_angley) { XENO_STATUS_BLOCK *xenoStatusPointer; int anglex,angley; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); { SECTION_DATA *head_section; head_section=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"neck"); GLOBALASSERT(head_section); Xenoborg_GetRelativeAngles(sbPtr,&anglex,&angley,&head_section->World_Offset); } *ref_anglex=anglex; *ref_angley=angley; /* Start turning / targeting procedure. */ #if 0 if ((xenoStatusPointer->headLock) ||(anglex>((((xenoStatusPointer->Torso_Twist>>4)+XENO_HEADPAN_GIMBALL)*7)/8)) ||(anglex<((((xenoStatusPointer->Torso_Twist>>4)-XENO_HEADPAN_GIMBALL)*7)/8))) { Xeno_TorsoMovement_TrackToAngle(sbPtr,XENO_TORSO_TWIST_RATE,anglex); } #else /* Always torso twist. */ Xeno_TorsoMovement_TrackToAngle(sbPtr,XENO_TORSO_TWIST_RATE,anglex); #endif xenoStatusPointer->headLock=Xeno_HeadMovement_TrackToAngles(sbPtr,XENO_HEAD_LOCK_RATE,anglex,angley); /* Now the arm. */ if ((xenoStatusPointer->headLock) &&((anglex<XENO_LEFTARM_ACW_GIMBALL)||(anglex>-XENO_LEFTARM_CW_GIMBALL))) { SECTION_DATA *this_section; int arm_anglex,arm_angley; this_section=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"left bicep"); if (this_section) { Xenoborg_GetRelativeAngles(sbPtr,&arm_anglex,NULL,&this_section->World_Offset); } else { arm_anglex=0; } this_section=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"left forearm"); if (this_section) { Xenoborg_GetRelativeAngles(sbPtr,NULL,&arm_angley,&this_section->World_Offset); } else { arm_angley=0; } xenoStatusPointer->leftArmLock=Xeno_LeftArmMovement_TrackToAngles(sbPtr,XENO_ARM_LOCK_RATE,arm_anglex,arm_angley); } if ((xenoStatusPointer->headLock) &&((anglex<XENO_RIGHTARM_ACW_GIMBALL)||(anglex>-XENO_RIGHTARM_CW_GIMBALL))) { SECTION_DATA *this_section; int arm_anglex,arm_angley; this_section=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"right bicep"); if (this_section) { Xenoborg_GetRelativeAngles(sbPtr,&arm_anglex,NULL,&this_section->World_Offset); } else { arm_anglex=0; } this_section=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"right forearm"); if (this_section) { Xenoborg_GetRelativeAngles(sbPtr,NULL,&arm_angley,&this_section->World_Offset); } else { arm_angley=0; } xenoStatusPointer->rightArmLock=Xeno_RightArmMovement_TrackToAngles(sbPtr,XENO_ARM_LOCK_RATE,arm_anglex,arm_angley); } xenoStatusPointer->UseHeadLaser=1; } void Xeno_Limbs_ShootTheRoof(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); Xeno_TorsoMovement_Centre(sbPtr,XENO_TORSO_TWIST_RATE); Xeno_LeftArmMovement_WaveUp(sbPtr,XENO_ARM_LOCK_RATE); Xeno_LeftArmMovement_TrackLeftRight(sbPtr,XENO_ARM_LOCK_RATE); Xeno_RightArmMovement_WaveUp(sbPtr,XENO_ARM_LOCK_RATE); Xeno_RightArmMovement_TrackLeftRight(sbPtr,XENO_ARM_LOCK_RATE); #if 0 Xeno_HeadMovement_ScanLeftRight(sbPtr,XENO_HEAD_SCAN_RATE); Xeno_HeadMovement_ScanUpDown(sbPtr,XENO_HEAD_SCAN_RATE+2); #else Xeno_HeadMovement_TrackToAngles(sbPtr,XENO_HEAD_SCAN_RATE,0,XENO_HEADTILT_GIMBALL); #endif xenoStatusPointer->UseHeadLaser=0; xenoStatusPointer->UseRALaser=1; xenoStatusPointer->UseLALaser=1; xenoStatusPointer->FiringLeft=1; xenoStatusPointer->FiringRight=1; } void Execute_Xeno_ActiveWait(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; int anglex,angley,correctlyOrientated; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* What to do? Do we have a target? */ if (ShowXenoStats) { PrintDebuggingText("In ActiveWait.\n"); } if (xenoStatusPointer->Target==NULL) { /* Let's wave the head around. */ Xeno_TorsoMovement_Centre(sbPtr,XENO_TORSO_TWIST_RATE); Xeno_LeftArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); Xeno_RightArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); Xeno_HeadMovement_ScanLeftRight(sbPtr,XENO_HEAD_SCAN_RATE); Xeno_HeadMovement_ScanUpDown(sbPtr,XENO_HEAD_SCAN_RATE+2); xenoStatusPointer->UseHeadLaser=1; /* Are we at home? */ if (sbPtr->containingModule->m_aimodule!=xenoStatusPointer->my_module) { Xeno_Enter_Returning_State(sbPtr); return; } /* Are we facing the right way? */ correctlyOrientated = NPCOrientateToVector(sbPtr, &xenoStatusPointer->my_orientdir_therin,(NPC_TURNRATE>>XENO_FOOT_TURN_RATE),NULL); if (!correctlyOrientated) { SECTION_DATA *master_section; master_section=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"pelvis presley"); GLOBALASSERT(master_section); Xenoborg_GetRelativeAngles(sbPtr,&anglex,&angley,&master_section->World_Offset); if (anglex>0) { EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Turn_Right,XENO_TURNING_ANIM_SPEED,(ONE_FIXED>>2)); } else { EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Turn_Left,XENO_TURNING_ANIM_SPEED,(ONE_FIXED>>2)); } if (xenoStatusPointer->soundHandle1==SOUND_NOACTIVEINDEX) { Sound_Play(SID_LOADMOVE,"del",&sbPtr->DynPtr->Position,&xenoStatusPointer->soundHandle1); } } else { /* Otherwise just wait? */ if (xenoStatusPointer->soundHandle1!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->soundHandle1); } EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Powered_Up_Standard,ONE_FIXED,(ONE_FIXED>>2)); xenoStatusPointer->stateTimer+=NormalFrameTime; if (xenoStatusPointer->stateTimer>xenoStatusPointer->UpTime) { Xeno_Enter_PowerDown_State(sbPtr); /* Voluntary powerdown! */ xenoStatusPointer->stateTimer=XENO_POWERDOWN_TIME; } } return; } GLOBALASSERT(xenoStatusPointer->Target); xenoStatusPointer->stateTimer=0; /* Now we have a target. Can we see it? */ if (xenoStatusPointer->targetSightTest==0) { /* Can't see them. Are we out of range? */ if (GetNextModuleForLink(sbPtr->containingModule->m_aimodule, xenoStatusPointer->my_module,(xenoStatusPointer->module_range)-1,0)==NULL) { Xeno_Enter_Returning_State(sbPtr); } else { Xeno_Enter_Following_State(sbPtr); } return; } Xeno_TurnAndTarget(sbPtr,&anglex,&angley); #if 0 if ((anglex>(((XENO_HEADPAN_GIMBALL)*7)/8)) ||(anglex<-(((XENO_HEADPAN_GIMBALL)*7)/8))) { Xeno_Enter_TurnToFace_State(sbPtr); } #else /* Always turn to face too? */ Xeno_Enter_TurnToFace_State(sbPtr); #endif } void Execute_Xeno_TurnToFace(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; int correctlyOrientated; int anglex,angley; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Do we have a target? */ if (ShowXenoStats) { PrintDebuggingText("In Turn To Face.\n"); } if (xenoStatusPointer->Target==NULL) { Xeno_Enter_ActiveWait_State(sbPtr); /* Otherwise just wait? */ return; } /* Now we have a target. */ GLOBALASSERT(xenoStatusPointer->Target); /* Set up animation... Which Way? */ { SECTION_DATA *master_section; VECTORCH orientationDirn; master_section=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"pelvis presley"); GLOBALASSERT(master_section); Xenoborg_GetRelativeAngles(sbPtr,&anglex,&angley,&master_section->World_Offset); if (anglex>0) { EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Turn_Right,XENO_TURNING_ANIM_SPEED,(ONE_FIXED>>2)); } else { EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Turn_Left,XENO_TURNING_ANIM_SPEED,(ONE_FIXED>>2)); } /* Then turn to face it, of course. */ orientationDirn.vx = xenoStatusPointer->targetTrackPos.vx - sbPtr->DynPtr->Position.vx; orientationDirn.vy = 0; orientationDirn.vz = xenoStatusPointer->targetTrackPos.vz - sbPtr->DynPtr->Position.vz; correctlyOrientated = NPCOrientateToVector(sbPtr, &orientationDirn,(NPC_TURNRATE>>XENO_FOOT_TURN_RATE),NULL); } Xeno_TurnAndTarget(sbPtr,&anglex,&angley); if (angley>=XENO_HEADTILT_GIMBALL) { Xeno_Enter_ShootingTheRoof_State(sbPtr); return; } if (correctlyOrientated) { Xeno_Enter_ActiveWait_State(sbPtr); } } void Execute_Xeno_ShootTheRoof(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; int correctlyOrientated; int anglex,angley; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Do we have a target? */ if (ShowXenoStats) { PrintDebuggingText("In Shoot The Roof.\n"); } if ((xenoStatusPointer->Target==NULL)||(xenoStatusPointer->IAmFar)) { Xeno_Enter_ActiveWait_State(sbPtr); /* Otherwise just wait? */ return; } /* Now we have a target. */ GLOBALASSERT(xenoStatusPointer->Target); /* Set up animation... Which Way? Keep TurnToFace functionality? */ { SECTION_DATA *master_section; VECTORCH orientationDirn; master_section=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"pelvis presley"); GLOBALASSERT(master_section); Xenoborg_GetRelativeAngles(sbPtr,&anglex,&angley,&master_section->World_Offset); anglex=512; if (anglex>0) { EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Turn_Right,XENO_TURNING_ANIM_SPEED,(ONE_FIXED>>2)); } else { EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Turn_Left,XENO_TURNING_ANIM_SPEED,(ONE_FIXED>>2)); } #if 0 /* Then turn to face it, of course. */ orientationDirn.vx = xenoStatusPointer->targetTrackPos.vx - sbPtr->DynPtr->Position.vx; orientationDirn.vy = 0; orientationDirn.vz = xenoStatusPointer->targetTrackPos.vz - sbPtr->DynPtr->Position.vz; #else /* Synthesize a new orientationDirn. */ orientationDirn.vx=sbPtr->DynPtr->OrientMat.mat11; orientationDirn.vy=sbPtr->DynPtr->OrientMat.mat12; orientationDirn.vz=sbPtr->DynPtr->OrientMat.mat13; #endif correctlyOrientated = NPCOrientateToVector(sbPtr, &orientationDirn,(NPC_TURNRATE>>XENO_FOOT_TURN_RATE),NULL); } Xeno_Limbs_ShootTheRoof(sbPtr); if (angley<XENO_HEADTILT_GIMBALL) { Xeno_Enter_TurnToFace_State(sbPtr); return; } } void Execute_Xeno_Follow(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; VECTORCH velocityDirection = {0,0,0}; VECTORCH targetPosition; int targetIsAirduct = 0; int anglex,angley; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* In theory, we're following the target, and can't see it. */ if (ShowXenoStats) { PrintDebuggingText("In Follow.\n"); } if (xenoStatusPointer->Target==NULL) { /* Let's wave the head around. */ Xeno_HeadMovement_ScanLeftRight(sbPtr,XENO_HEAD_SCAN_RATE); /* Do we want to do this? */ Xeno_HeadMovement_ScanUpDown(sbPtr,XENO_HEAD_SCAN_RATE+2); xenoStatusPointer->UseHeadLaser=1; /* And return to my module. */ Xeno_Enter_Returning_State(sbPtr); return; } GLOBALASSERT(xenoStatusPointer->Target); /* Now we know have a target. Can we see it yet? */ if (xenoStatusPointer->targetSightTest==0) { AIMODULE *targetModule; FARENTRYPOINT *thisEp = (FARENTRYPOINT *)0; /* Can't see them. Never mind. Go to the next module? */ if (xenoStatusPointer->Target->containingModule==NULL) { /* Fall through for now. */ targetModule=NULL; } else if (GetNextModuleForLink(sbPtr->containingModule->m_aimodule, xenoStatusPointer->my_module,(xenoStatusPointer->module_range)-1,0)==NULL) { /* Too Far! */ Xeno_Enter_ActiveWait_State(sbPtr); return; } else { /* Still in range: keep going. */ targetModule=GetNextModuleForLink(sbPtr->containingModule->m_aimodule, xenoStatusPointer->Target->containingModule->m_aimodule,xenoStatusPointer->module_range,0); } if (targetModule==NULL) { /* They're way away. */ Xeno_Enter_Returning_State(sbPtr); return; } if (targetModule==sbPtr->containingModule->m_aimodule) { /* Good Grief, Penfold! He's right there, but I can't see him! */ NPCGetMovementDirection(sbPtr, &velocityDirection, &xenoStatusPointer->targetTrackPos,&xenoStatusPointer->waypointManager); NPCSetVelocity(sbPtr, &velocityDirection, XENO_NEAR_SPEED); targetPosition=xenoStatusPointer->targetTrackPos; if (ShowXenoStats) { PrintDebuggingText("Direct movement - no LOS.\n"); } /* Oh, well. Go to last known position? */ } else { thisEp=GetAIModuleEP(targetModule,sbPtr->containingModule->m_aimodule); if (!thisEp) { LOGDXFMT(("This assert is a busted adjacency!\nNo EP between %s and %s.", (*(targetModule->m_module_ptrs))->name, sbPtr->containingModule->name)); GLOBALASSERT(thisEp); } /* If that fired, there's a farped adjacency. */ xenoStatusPointer->wanderData.worldPosition=thisEp->position; xenoStatusPointer->wanderData.worldPosition.vx+=targetModule->m_world.vx; xenoStatusPointer->wanderData.worldPosition.vy+=targetModule->m_world.vy; xenoStatusPointer->wanderData.worldPosition.vz+=targetModule->m_world.vz; NPCGetMovementDirection(sbPtr, &velocityDirection, &(xenoStatusPointer->wanderData.worldPosition),&xenoStatusPointer->waypointManager); NPCSetVelocity(sbPtr, &velocityDirection, XENO_NEAR_SPEED); targetPosition=xenoStatusPointer->wanderData.worldPosition; } } else { /* Re-aquired! Get a bit closer? */ int range; if (GetNextModuleForLink(sbPtr->containingModule->m_aimodule, xenoStatusPointer->my_module,(xenoStatusPointer->module_range)-1,0)==NULL) { /* Too Far! */ Xeno_Enter_ActiveWait_State(sbPtr); return; } range=VectorDistance((&xenoStatusPointer->Target->DynPtr->Position),(&sbPtr->DynPtr->Position)); if (range>XENO_CLOSE_APPROACH_DISTANCE) { NPCGetMovementTarget(sbPtr, xenoStatusPointer->Target, &targetPosition, &targetIsAirduct, 0); NPCGetMovementDirection(sbPtr, &velocityDirection, &targetPosition,&xenoStatusPointer->waypointManager); NPCSetVelocity(sbPtr, &velocityDirection, XENO_NEAR_SPEED); if (ShowXenoStats) { PrintDebuggingText("Direct movement - LOS Okay.\n"); } } else { /* Return to ActiveWait. */ Xeno_Enter_ActiveWait_State(sbPtr); return; } } #if 0 EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Walking,XENO_WALKING_ANIM_SPEED,(ONE_FIXED>>2)); #else XenoborgHandleMovingAnimation(sbPtr); #endif if (xenoStatusPointer->targetSightTest==0) { Xeno_TorsoMovement_Centre(sbPtr,XENO_TORSO_TWIST_RATE); Xeno_LeftArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); Xeno_RightArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); Xeno_HeadMovement_ScanLeftRight(sbPtr,XENO_HEAD_SCAN_RATE); xenoStatusPointer->UseHeadLaser=1; } else { Xeno_TurnAndTarget(sbPtr,&anglex,&angley); } /* test here for impeding collisions, and not being able to reach target... */ { STRATEGYBLOCK *destructableObject = NULL; NPC_IsObstructed(sbPtr,&(xenoStatusPointer->moveData),&xenoStatusPointer->obstruction,&destructableObject); #if 1 if(xenoStatusPointer->obstruction.environment) { /* go to avoidance */ Xeno_Enter_Avoidance_State(sbPtr); return; } #endif if(xenoStatusPointer->obstruction.destructableObject) { LOCALASSERT(destructableObject); CauseDamageToObject(destructableObject,&TemplateAmmo[AMMO_NPC_OBSTACLE_CLEAR].MaxDamage[AvP.Difficulty], ONE_FIXED,NULL); } } if(NPC_CannotReachTarget(&(xenoStatusPointer->moveData), &targetPosition, &velocityDirection)) { xenoStatusPointer->obstruction.environment=1; xenoStatusPointer->obstruction.destructableObject=0; xenoStatusPointer->obstruction.otherCharacter=0; xenoStatusPointer->obstruction.anySingleObstruction=0; Xeno_Enter_Avoidance_State(sbPtr); return; } } void Execute_Xeno_Return(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; VECTORCH velocityDirection = {0,0,0}; VECTORCH *targetPosition=NULL; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* In theory, we're following the target, and can't see it. */ if (ShowXenoStats) { PrintDebuggingText("In Return.\n"); } if (xenoStatusPointer->Target!=NULL) { /* Saw something! */ /* Go to active wait. */ Xeno_Enter_ActiveWait_State(sbPtr); return; } GLOBALASSERT(xenoStatusPointer->Target==NULL); /* Find our way home. */ { AIMODULE *targetModule; FARENTRYPOINT *thisEp = (FARENTRYPOINT *)0; /* Go to the next module. */ targetModule=GetNextModuleForLink(sbPtr->containingModule->m_aimodule, xenoStatusPointer->my_module,xenoStatusPointer->module_range+2,0); /* Just to be on the safe side. */ if (targetModule==NULL) { /* Emergency! */ targetModule=GetNextModuleForLink(sbPtr->containingModule->m_aimodule, xenoStatusPointer->my_module,xenoStatusPointer->module_range+5,0); if (targetModule==NULL) { /* Totally broken. Stay here. */ Xeno_CopeWithLossOfHome(sbPtr); return; } } if (targetModule!=sbPtr->containingModule->m_aimodule) { thisEp=GetAIModuleEP(targetModule,sbPtr->containingModule->m_aimodule); if (!thisEp) { LOGDXFMT(("This assert is a busted adjacency!\nNo EP between %s and %s.", (*(targetModule->m_module_ptrs))->name, sbPtr->containingModule->name)); GLOBALASSERT(thisEp); } /* If that fired, there's a farped adjacency. */ xenoStatusPointer->wanderData.worldPosition=thisEp->position; xenoStatusPointer->wanderData.worldPosition.vx+=targetModule->m_world.vx; xenoStatusPointer->wanderData.worldPosition.vy+=targetModule->m_world.vy; xenoStatusPointer->wanderData.worldPosition.vz+=targetModule->m_world.vz; NPCGetMovementDirection(sbPtr, &velocityDirection, &(xenoStatusPointer->wanderData.worldPosition),&xenoStatusPointer->waypointManager); NPCSetVelocity(sbPtr, &velocityDirection, XENO_NEAR_SPEED); targetPosition=&(xenoStatusPointer->wanderData.worldPosition); } else { VECTORCH offset; int dist; /* In our own home module! */ offset.vx=sbPtr->DynPtr->Position.vx-xenoStatusPointer->my_spot_therin.vx; offset.vy=sbPtr->DynPtr->Position.vy-xenoStatusPointer->my_spot_therin.vy; offset.vz=sbPtr->DynPtr->Position.vz-xenoStatusPointer->my_spot_therin.vz; /* Fix for midair start points, grrrr. */ offset.vy>>=2; /* Find distance off spot. */ dist=Approximate3dMagnitude(&offset); if (dist<XENO_SENTRY_SENSITIVITY) { Xeno_Enter_ActiveWait_State(sbPtr); return; } else { NPCGetMovementDirection(sbPtr, &velocityDirection, &(xenoStatusPointer->my_spot_therin),&xenoStatusPointer->waypointManager); NPCSetVelocity(sbPtr, &velocityDirection, XENO_NEAR_SPEED); targetPosition=&(xenoStatusPointer->my_spot_therin); } } } #if 0 EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Walking,XENO_WALKING_ANIM_SPEED,(ONE_FIXED>>2)); #else XenoborgHandleMovingAnimation(sbPtr); #endif Xeno_TorsoMovement_Centre(sbPtr,XENO_TORSO_TWIST_RATE); Xeno_LeftArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); Xeno_RightArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); Xeno_HeadMovement_ScanLeftRight(sbPtr,XENO_HEAD_SCAN_RATE); xenoStatusPointer->UseHeadLaser=1; /* test here for impeding collisions, and not being able to reach target... */ { STRATEGYBLOCK *destructableObject = NULL; NPC_IsObstructed(sbPtr,&(xenoStatusPointer->moveData),&xenoStatusPointer->obstruction,&destructableObject); #if 1 if(xenoStatusPointer->obstruction.environment) { /* go to avoidance */ Xeno_Enter_Avoidance_State(sbPtr); return; } #endif if(xenoStatusPointer->obstruction.destructableObject) { LOCALASSERT(destructableObject); CauseDamageToObject(destructableObject,&TemplateAmmo[AMMO_NPC_OBSTACLE_CLEAR].MaxDamage[AvP.Difficulty], ONE_FIXED,NULL); } } if(NPC_CannotReachTarget(&(xenoStatusPointer->moveData), targetPosition, &velocityDirection)) { xenoStatusPointer->obstruction.environment=1; xenoStatusPointer->obstruction.destructableObject=0; xenoStatusPointer->obstruction.otherCharacter=0; xenoStatusPointer->obstruction.anySingleObstruction=0; Xeno_Enter_Avoidance_State(sbPtr); return; } } void Execute_Xeno_Avoidance(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; int terminateState = 0; int anglex,angley; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); if (ShowXenoStats) { PrintDebuggingText("In Avoidance.\n"); } /* Sequences... */ #if 0 EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Walking,XENO_WALKING_ANIM_SPEED,(ONE_FIXED>>2)); #else XenoborgHandleMovingAnimation(sbPtr); #endif if (xenoStatusPointer->targetSightTest==0) { Xeno_TorsoMovement_Centre(sbPtr,XENO_TORSO_TWIST_RATE); Xeno_LeftArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); Xeno_RightArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); Xeno_HeadMovement_ScanLeftRight(sbPtr,XENO_HEAD_SCAN_RATE); xenoStatusPointer->UseHeadLaser=1; } else { Xeno_TurnAndTarget(sbPtr,&anglex,&angley); } /* set velocity */ LOCALASSERT((xenoStatusPointer->moveData.avoidanceDirn.vx!=0)|| (xenoStatusPointer->moveData.avoidanceDirn.vy!=0)|| (xenoStatusPointer->moveData.avoidanceDirn.vz!=0)); NPCSetVelocity(sbPtr, &(xenoStatusPointer->moveData.avoidanceDirn), (XENO_NEAR_SPEED)); /* decrement state timer */ xenoStatusPointer->stateTimer -= NormalFrameTime; if(xenoStatusPointer->stateTimer <= 0) terminateState = 1; { STRATEGYBLOCK *destructableObject = NULL; NPC_OBSTRUCTIONREPORT obstruction; NPC_IsObstructed(sbPtr,&(xenoStatusPointer->moveData),&obstruction,&destructableObject); if(obstruction.anySingleObstruction) { terminateState = 1; } } if(terminateState) { /* go to an appropriate state */ switch (xenoStatusPointer->lastState) { case XS_Returning: Xeno_Enter_Returning_State(sbPtr); return; break; case XS_Following: Xeno_Enter_Following_State(sbPtr); return; break; default: Xeno_Enter_ActiveWait_State(sbPtr); return; break; } /* Still here? */ return; } return; } int Xenoborg_TargetFilter(STRATEGYBLOCK *candidate) { /* Let's face it, Xenos shoot everything but other xenos. */ switch (candidate->I_SBtype) { case I_BehaviourMarinePlayer: case I_BehaviourAlienPlayer: case I_BehaviourPredatorPlayer: { if (Observer) { return(0); } switch(AvP.PlayerType) { case I_Alien: case I_Predator: case I_Marine: return(1); break; default: GLOBALASSERT(0); return(0); break; } break; } case I_BehaviourDummy: { DUMMY_STATUS_BLOCK *dummyStatusPointer; dummyStatusPointer = (DUMMY_STATUS_BLOCK *)(candidate->SBdataptr); LOCALASSERT(dummyStatusPointer); switch (dummyStatusPointer->PlayerType) { case I_Marine: case I_Predator: case I_Alien: return(1); break; default: GLOBALASSERT(0); return(0); break; } break; } case I_BehaviourAlien: { if (NPC_IsDead(candidate)) { return(0); } else { /* Are we inactive? */ ALIEN_STATUS_BLOCK *asb=(ALIEN_STATUS_BLOCK *)candidate->SBdataptr; GLOBALASSERT(asb); if (asb->BehaviourState==ABS_Dormant) { return(0); } else { return(1); } } break; } case I_BehaviourQueenAlien: case I_BehaviourFaceHugger: case I_BehaviourPredator: case I_BehaviourSeal: case I_BehaviourPredatorAlien: case I_BehaviourMarine: { if (NPC_IsDead(candidate)) { return(0); } else { return(1); } break; } case I_BehaviourXenoborg: return(0); break; case I_BehaviourNetGhost: { NETGHOSTDATABLOCK *dataptr = static_cast<NETGHOSTDATABLOCK*>(candidate->SBdataptr); switch (dataptr->type) { case I_BehaviourMarinePlayer: case I_BehaviourAlienPlayer: case I_BehaviourPredatorPlayer: return(1); break; default: return(1); break; } } break; default: return(0); break; } } STRATEGYBLOCK *Xenoborg_GetNewTarget(VECTORCH *xenopos, STRATEGYBLOCK *me) { int neardist; STRATEGYBLOCK *nearest; int a; STRATEGYBLOCK *candidate; MODULE *dmod; dmod=ModuleFromPosition(xenopos,playerPherModule); LOCALASSERT(dmod); nearest=NULL; neardist=ONE_FIXED; for (a=0; a<NumActiveStBlocks; a++) { candidate=ActiveStBlockList[a]; if (candidate!=me) { if (candidate->DynPtr) { if (Xenoborg_TargetFilter(candidate)) { VECTORCH offset; int dist; offset.vx=xenopos->vx-candidate->DynPtr->Position.vx; offset.vy=xenopos->vy-candidate->DynPtr->Position.vy; offset.vz=xenopos->vz-candidate->DynPtr->Position.vz; dist=Approximate3dMagnitude(&offset); if (dist<neardist) { /* Check visibility? */ if (NPCCanSeeTarget(me,candidate,XENO_NEAR_VIEW_WIDTH)) { if (!NPC_IsDead(candidate)) { if ((IsModuleVisibleFromModule(dmod,candidate->containingModule))) { nearest=candidate; } } } } } } } } #if 0 if (nearest==NULL) { if (Xenoborg_TargetFilter(Player->ObStrategyBlock)) { nearest=Player->ObStrategyBlock; } else { nearest=NULL; /* Erk! */ } } #endif return(nearest); } static void ComputeDeltaValues(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; int angle; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Interpret all status block values, and apply to deltas. */ /* Head Pan first. */ angle=xenoStatusPointer->Head_Pan>>4; if (angle>=3072) angle-=4096; if (angle>=2048) angle=angle-4096; /* Now, we have an angle. */ if (angle>XENO_HEADPAN_GIMBALL) { angle=XENO_HEADPAN_GIMBALL; } else if (angle<-XENO_HEADPAN_GIMBALL) { angle=-XENO_HEADPAN_GIMBALL; } #if 0 angle=angle*2; GLOBALASSERT(xenoStatusPointer->head_pan); { int fake_timer; fake_timer=1024-angle; fake_timer<<=5; if (fake_timer==65536) fake_timer=65535; #else GLOBALASSERT(xenoStatusPointer->head_pan); { int fake_timer; fake_timer=DIV_FIXED(angle,(XENO_HEADPAN_GIMBALL<<1)); fake_timer+=32767; fake_timer=65536-fake_timer; if (fake_timer>=65536) fake_timer=65535; if (fake_timer<=0) fake_timer=0; #endif GLOBALASSERT(fake_timer>=0); GLOBALASSERT(fake_timer<65536); xenoStatusPointer->head_pan->timer=fake_timer; } /* Head tilt next. */ angle=xenoStatusPointer->Head_Tilt>>4; if (angle>=3072) angle-=4096; if (angle>=2048) angle=angle-3072; if (angle> 1024) angle=2048-angle; /* Now, we have an angle. */ if (angle>XENO_HEADTILT_GIMBALL) { angle=XENO_HEADTILT_GIMBALL; } else if (angle<-XENO_HEADTILT_GIMBALL) { angle=-XENO_HEADTILT_GIMBALL; } angle=angle*2; GLOBALASSERT(angle>=-1024); GLOBALASSERT(angle<=1024); GLOBALASSERT(xenoStatusPointer->head_tilt); { int fake_timer; fake_timer=1024-angle; fake_timer<<=5; if (fake_timer==65536) fake_timer=65535; GLOBALASSERT(fake_timer>=0); GLOBALASSERT(fake_timer<65536); xenoStatusPointer->head_tilt->timer=fake_timer; } /* Left Arm Pan now. */ angle=xenoStatusPointer->Left_Arm_Pan>>4; if (angle>=3072) angle-=4096; if (angle>=2048) angle=angle-4096; GLOBALASSERT(xenoStatusPointer->left_arm_pan); /* Now, we have an angle. */ if (angle>XENO_LEFTARM_ACW_GIMBALL) { angle=XENO_LEFTARM_ACW_GIMBALL; } else if (angle<-XENO_LEFTARM_CW_GIMBALL) { angle=-XENO_LEFTARM_CW_GIMBALL; } { int fake_timer; if (angle>0) { fake_timer=DIV_FIXED(angle,(XENO_LEFTARM_ACW_GIMBALL<<1)); fake_timer+=32767; fake_timer=65536-fake_timer; if (fake_timer>=65536) fake_timer=65535; if (fake_timer<=0) fake_timer=0; } else { fake_timer=DIV_FIXED(angle,(XENO_LEFTARM_CW_GIMBALL<<1)); fake_timer+=32767; fake_timer=65536-fake_timer; if (fake_timer>=65536) fake_timer=65535; if (fake_timer<=0) fake_timer=0; } GLOBALASSERT(fake_timer>=0); GLOBALASSERT(fake_timer<65536); xenoStatusPointer->left_arm_pan->timer=fake_timer; } /* Left Arm Tilt... */ angle=xenoStatusPointer->Left_Arm_Tilt>>4; if (angle>=3072) angle-=4096; if (angle>=2048) angle=angle-3072; if (angle> 1024) angle=2048-angle; GLOBALASSERT(xenoStatusPointer->left_arm_tilt); /* Now, we have an angle. */ if (angle>XENO_ARM_PITCH_GIMBALL) { angle=XENO_ARM_PITCH_GIMBALL; } else if (angle<-XENO_ARM_PITCH_GIMBALL) { angle=-XENO_ARM_PITCH_GIMBALL; } GLOBALASSERT(angle>=-1024); GLOBALASSERT(angle<=1024); { int fake_timer; fake_timer=1024-angle; fake_timer<<=5; if (fake_timer==65536) fake_timer=65535; GLOBALASSERT(fake_timer>=0); GLOBALASSERT(fake_timer<65536); xenoStatusPointer->left_arm_tilt->timer=fake_timer; } /* Right Arm Pan now. */ angle=xenoStatusPointer->Right_Arm_Pan>>4; if (angle>=3072) angle-=4096; if (angle>=2048) angle=angle-4096; GLOBALASSERT(xenoStatusPointer->right_arm_pan); /* Now, we have an angle. */ if (angle>XENO_RIGHTARM_ACW_GIMBALL) { angle=XENO_RIGHTARM_ACW_GIMBALL; } else if (angle<-XENO_RIGHTARM_CW_GIMBALL) { angle=-XENO_RIGHTARM_CW_GIMBALL; } { int fake_timer; if (angle>0) { fake_timer=DIV_FIXED(angle,(XENO_RIGHTARM_ACW_GIMBALL<<1)); fake_timer+=32767; if (fake_timer>=65536) fake_timer=65535; } else { fake_timer=DIV_FIXED(angle,(XENO_RIGHTARM_CW_GIMBALL<<1)); fake_timer+=32767; if (fake_timer<=0) fake_timer=0; } GLOBALASSERT(fake_timer>=0); GLOBALASSERT(fake_timer<65536); xenoStatusPointer->right_arm_pan->timer=fake_timer; } /* Right Arm Tilt... */ angle=xenoStatusPointer->Right_Arm_Tilt>>4; if (angle>=3072) angle-=4096; if (angle>=2048) angle=angle-3072; if (angle> 1024) angle=2048-angle; GLOBALASSERT(xenoStatusPointer->right_arm_pan); /* Now, we have an angle. */ if (angle>XENO_ARM_PITCH_GIMBALL) { angle=XENO_ARM_PITCH_GIMBALL; } else if (angle<-XENO_ARM_PITCH_GIMBALL) { angle=-XENO_ARM_PITCH_GIMBALL; } GLOBALASSERT(angle>=-1024); GLOBALASSERT(angle<=1024); { int fake_timer; fake_timer=1024-angle; fake_timer<<=5; if (fake_timer==65536) fake_timer=65535; GLOBALASSERT(fake_timer>=0); GLOBALASSERT(fake_timer<65536); xenoStatusPointer->right_arm_tilt->timer=fake_timer; } /* ... and Torso Twist. */ angle=xenoStatusPointer->Torso_Twist>>4; if (angle>=3072) angle-=4096; if (angle>=2048) angle=angle-4096; GLOBALASSERT(xenoStatusPointer->torso_twist); /* Now, we have an angle. */ if (angle>XENO_TORSO_GIMBALL) { angle=XENO_TORSO_GIMBALL; } else if (angle<-XENO_TORSO_GIMBALL) { angle=-XENO_TORSO_GIMBALL; } { int fake_timer; if (angle>0) { fake_timer=DIV_FIXED(angle,(XENO_TORSO_GIMBALL<<1)); fake_timer+=32767; if (fake_timer>=65536) fake_timer=65535; } else { fake_timer=DIV_FIXED(angle,(XENO_TORSO_GIMBALL<<1)); fake_timer+=32767; if (fake_timer<=0) fake_timer=0; } GLOBALASSERT(fake_timer>=0); GLOBALASSERT(fake_timer<65536); xenoStatusPointer->torso_twist->timer=fake_timer; } } void Xeno_HeadMovement_ScanLeftRight(STRATEGYBLOCK *sbPtr,int rate) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Let's wave the head around. */ if (xenoStatusPointer->headpandir) { xenoStatusPointer->Head_Pan+=(NormalFrameTime>>rate); if (xenoStatusPointer->Head_Pan>(XENO_HEADPAN_GIMBALL<<4)) { xenoStatusPointer->Head_Pan=(XENO_HEADPAN_GIMBALL<<4); xenoStatusPointer->headpandir=0; } else { xenoStatusPointer->head_moving=1; } } else { xenoStatusPointer->Head_Pan-=(NormalFrameTime>>rate); if (xenoStatusPointer->Head_Pan<-(XENO_HEADPAN_GIMBALL<<4)) { xenoStatusPointer->Head_Pan=-(XENO_HEADPAN_GIMBALL<<4); xenoStatusPointer->headpandir=1; } else { xenoStatusPointer->head_moving=1; } } if (xenoStatusPointer->head_pan) { xenoStatusPointer->head_pan->Active=1; } } void Xeno_HeadMovement_ScanUpDown(STRATEGYBLOCK *sbPtr,int rate) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Let's wave the head around. */ if (xenoStatusPointer->headtiltdir) { xenoStatusPointer->Head_Tilt+=(NormalFrameTime>>rate); if (xenoStatusPointer->Head_Tilt>(XENO_HEADTILT_GIMBALL<<4)) { xenoStatusPointer->Head_Tilt=(XENO_HEADTILT_GIMBALL<<4); xenoStatusPointer->headtiltdir=0; } else { xenoStatusPointer->head_moving=1; } } else { xenoStatusPointer->Head_Tilt-=(NormalFrameTime>>rate); if (xenoStatusPointer->Head_Tilt<-(XENO_HEADTILT_GIMBALL<<4)) { xenoStatusPointer->Head_Tilt=-(XENO_HEADTILT_GIMBALL<<4); xenoStatusPointer->headtiltdir=1; } else { xenoStatusPointer->head_moving=1; } } if (xenoStatusPointer->head_tilt) { xenoStatusPointer->head_tilt->Active=1; } } void Xeno_LeftArmMovement_TrackLeftRight(STRATEGYBLOCK *sbPtr,int rate) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Let's wave the left arm around. */ if (xenoStatusPointer->leftarmpandir) { xenoStatusPointer->Left_Arm_Pan+=(NormalFrameTime>>rate); if (xenoStatusPointer->Left_Arm_Pan>(XENO_LEFTARM_ACW_GIMBALL<<4)) { xenoStatusPointer->Left_Arm_Pan=(XENO_LEFTARM_ACW_GIMBALL<<4); xenoStatusPointer->leftarmpandir=0; } else { xenoStatusPointer->la_moving=1; } } else { xenoStatusPointer->Left_Arm_Pan-=(NormalFrameTime>>rate); if (xenoStatusPointer->Left_Arm_Pan<-(XENO_LEFTARM_CW_GIMBALL<<4)) { xenoStatusPointer->Left_Arm_Pan=-(XENO_LEFTARM_CW_GIMBALL<<4); xenoStatusPointer->leftarmpandir=1; } else { xenoStatusPointer->la_moving=1; } } if (xenoStatusPointer->left_arm_pan) { xenoStatusPointer->left_arm_pan->Active=1; } } void Xeno_LeftArmMovement_TrackUpDown(STRATEGYBLOCK *sbPtr,int rate) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Let's wave the left arm around. */ if (xenoStatusPointer->leftarmtiltdir) { xenoStatusPointer->Left_Arm_Tilt+=(NormalFrameTime>>rate); if (xenoStatusPointer->Left_Arm_Tilt>(XENO_ARM_PITCH_GIMBALL<<4)) { xenoStatusPointer->Left_Arm_Tilt=(XENO_ARM_PITCH_GIMBALL<<4); xenoStatusPointer->leftarmtiltdir=0; } else { xenoStatusPointer->la_moving=1; } } else { xenoStatusPointer->Left_Arm_Tilt-=(NormalFrameTime>>rate); if (xenoStatusPointer->Left_Arm_Tilt<-(XENO_ARM_PITCH_GIMBALL<<4)) { xenoStatusPointer->Left_Arm_Tilt=-(XENO_ARM_PITCH_GIMBALL<<4); xenoStatusPointer->leftarmtiltdir=1; } else { xenoStatusPointer->la_moving=1; } } if (xenoStatusPointer->left_arm_tilt) { xenoStatusPointer->left_arm_tilt->Active=1; } } void Xeno_LeftArmMovement_WaveUp(STRATEGYBLOCK *sbPtr,int rate) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Let's wave the left arm around. */ if (xenoStatusPointer->leftarmtiltdir) { xenoStatusPointer->Left_Arm_Tilt+=(NormalFrameTime>>rate); if (xenoStatusPointer->Left_Arm_Tilt>-(XENO_HEADTILT_GIMBALL<<4)) { xenoStatusPointer->Left_Arm_Tilt=-(XENO_HEADTILT_GIMBALL<<4); xenoStatusPointer->leftarmtiltdir=0; } else { xenoStatusPointer->la_moving=1; } } else { xenoStatusPointer->Left_Arm_Tilt-=(NormalFrameTime>>rate); if (xenoStatusPointer->Left_Arm_Tilt<-(XENO_ARM_PITCH_GIMBALL<<4)) { xenoStatusPointer->Left_Arm_Tilt=-(XENO_ARM_PITCH_GIMBALL<<4); xenoStatusPointer->leftarmtiltdir=1; } else { xenoStatusPointer->la_moving=1; } } if (xenoStatusPointer->left_arm_tilt) { xenoStatusPointer->left_arm_tilt->Active=1; } } void Xeno_RightArmMovement_TrackLeftRight(STRATEGYBLOCK *sbPtr,int rate) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Let's wave the Right arm around. */ if (xenoStatusPointer->rightarmpandir) { xenoStatusPointer->Right_Arm_Pan+=(NormalFrameTime>>rate); if (xenoStatusPointer->Right_Arm_Pan>(XENO_RIGHTARM_ACW_GIMBALL<<4)) { xenoStatusPointer->Right_Arm_Pan=(XENO_RIGHTARM_ACW_GIMBALL<<4); xenoStatusPointer->rightarmpandir=0; } else { xenoStatusPointer->ra_moving=1; } } else { xenoStatusPointer->Right_Arm_Pan-=(NormalFrameTime>>rate); if (xenoStatusPointer->Right_Arm_Pan<-(XENO_RIGHTARM_CW_GIMBALL<<4)) { xenoStatusPointer->Right_Arm_Pan=-(XENO_RIGHTARM_CW_GIMBALL<<4); xenoStatusPointer->rightarmpandir=1; } else { xenoStatusPointer->ra_moving=1; } } if (xenoStatusPointer->right_arm_pan) { xenoStatusPointer->right_arm_pan->Active=1; } } void Xeno_RightArmMovement_TrackUpDown(STRATEGYBLOCK *sbPtr,int rate) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Let's wave the Right arm around. */ if (xenoStatusPointer->rightarmtiltdir) { xenoStatusPointer->Right_Arm_Tilt+=(NormalFrameTime>>rate); if (xenoStatusPointer->Right_Arm_Tilt>(XENO_ARM_PITCH_GIMBALL<<4)) { xenoStatusPointer->Right_Arm_Tilt=(XENO_ARM_PITCH_GIMBALL<<4); xenoStatusPointer->rightarmtiltdir=0; } else { xenoStatusPointer->ra_moving=1; } } else { xenoStatusPointer->Right_Arm_Tilt-=(NormalFrameTime>>rate); if (xenoStatusPointer->Right_Arm_Tilt<-(XENO_ARM_PITCH_GIMBALL<<4)) { xenoStatusPointer->Right_Arm_Tilt=-(XENO_ARM_PITCH_GIMBALL<<4); xenoStatusPointer->rightarmtiltdir=1; } else { xenoStatusPointer->ra_moving=1; } } if (xenoStatusPointer->right_arm_tilt) { xenoStatusPointer->right_arm_tilt->Active=1; } } void Xeno_RightArmMovement_WaveUp(STRATEGYBLOCK *sbPtr,int rate) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Let's wave the Right arm around. */ if (xenoStatusPointer->rightarmtiltdir) { xenoStatusPointer->Right_Arm_Tilt+=(NormalFrameTime>>rate); if (xenoStatusPointer->Right_Arm_Tilt>-(XENO_HEADTILT_GIMBALL<<4)) { xenoStatusPointer->Right_Arm_Tilt=-(XENO_HEADTILT_GIMBALL<<4); xenoStatusPointer->rightarmtiltdir=0; } else { xenoStatusPointer->ra_moving=1; } } else { xenoStatusPointer->Right_Arm_Tilt-=(NormalFrameTime>>rate); if (xenoStatusPointer->Right_Arm_Tilt<-(XENO_ARM_PITCH_GIMBALL<<4)) { xenoStatusPointer->Right_Arm_Tilt=-(XENO_ARM_PITCH_GIMBALL<<4); xenoStatusPointer->rightarmtiltdir=1; } else { xenoStatusPointer->ra_moving=1; } } if (xenoStatusPointer->right_arm_tilt) { xenoStatusPointer->right_arm_tilt->Active=1; } } void Xeno_TorsoMovement_TrackLeftRight(STRATEGYBLOCK *sbPtr,int rate) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Let's twist the torso. */ if (xenoStatusPointer->torsotwistdir) { xenoStatusPointer->Torso_Twist+=(NormalFrameTime>>rate); if (xenoStatusPointer->Torso_Twist>(XENO_TORSO_GIMBALL<<4)) { xenoStatusPointer->Torso_Twist=(XENO_TORSO_GIMBALL<<4); xenoStatusPointer->torsotwistdir=0; } else { xenoStatusPointer->torso_moving=1; } } else { xenoStatusPointer->Torso_Twist-=(NormalFrameTime>>rate); if (xenoStatusPointer->Torso_Twist<-(XENO_TORSO_GIMBALL<<4)) { xenoStatusPointer->Torso_Twist=-(XENO_TORSO_GIMBALL<<4); xenoStatusPointer->torsotwistdir=1; } else { xenoStatusPointer->torso_moving=1; } } if (xenoStatusPointer->right_arm_tilt) { xenoStatusPointer->right_arm_tilt->Active=1; } } int Xeno_HeadMovement_TrackToAngles(STRATEGYBLOCK *sbPtr,int rate,int in_anglex,int in_angley) { XENO_STATUS_BLOCK *xenoStatusPointer; int real_anglex,angley,online; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Turn the head to face a certain way. */ real_anglex=in_anglex-(xenoStatusPointer->Torso_Twist>>4); angley=in_angley; online=0; /* Now fix multiples. */ while ((real_anglex>4095)||(real_anglex<0)) { if (real_anglex<0) { real_anglex+=4096; } else if (real_anglex>4095) { real_anglex-=4096; } } if (real_anglex>=3072) real_anglex-=4096; if (real_anglex>=2048) real_anglex=real_anglex-3072; if (real_anglex> 1024) real_anglex=2048-real_anglex; if (angley>=3072) angley-=4096; if (angley>=2048) angley=angley-3072; if (angley> 1024) angley=2048-angley; GLOBALASSERT((real_anglex<=1024)&&(real_anglex>=-1024)); GLOBALASSERT((angley<=1024)&&(angley>=-1024)); if (ShowXenoStats) { PrintDebuggingText("Target head angles: %d %d\n",real_anglex,angley); } real_anglex<<=4; angley<<=4; if (xenoStatusPointer->Head_Pan<real_anglex) { xenoStatusPointer->Head_Pan+=(NormalFrameTime>>rate); if (xenoStatusPointer->Head_Pan>(XENO_HEADPAN_GIMBALL<<4)) { xenoStatusPointer->Head_Pan=(XENO_HEADPAN_GIMBALL<<4); } else if (xenoStatusPointer->Head_Pan>real_anglex) { xenoStatusPointer->Head_Pan=real_anglex; online++; } } else if (xenoStatusPointer->Head_Pan>real_anglex) { xenoStatusPointer->Head_Pan-=(NormalFrameTime>>rate); if (xenoStatusPointer->Head_Pan<-(XENO_HEADPAN_GIMBALL<<4)) { xenoStatusPointer->Head_Pan=-(XENO_HEADPAN_GIMBALL<<4); } else if (xenoStatusPointer->Head_Pan<real_anglex) { xenoStatusPointer->Head_Pan=real_anglex; online++; } } else { online++; } if (xenoStatusPointer->head_pan) { xenoStatusPointer->head_pan->Active=1; } /* Now y. */ angley=-angley; /* Oops. */ if (xenoStatusPointer->Head_Tilt<angley) { xenoStatusPointer->Head_Tilt+=(NormalFrameTime>>rate); if (xenoStatusPointer->Head_Tilt>(XENO_HEADTILT_GIMBALL<<4)) { xenoStatusPointer->Head_Tilt=(XENO_HEADTILT_GIMBALL<<4); } else if (xenoStatusPointer->Head_Tilt>angley) { xenoStatusPointer->Head_Tilt=angley; online++; } } else if (xenoStatusPointer->Head_Tilt>angley) { xenoStatusPointer->Head_Tilt-=(NormalFrameTime>>rate); if (xenoStatusPointer->Head_Tilt<-(XENO_HEADTILT_GIMBALL<<4)) { xenoStatusPointer->Head_Tilt=-(XENO_HEADTILT_GIMBALL<<4); } else if (xenoStatusPointer->Head_Tilt<angley) { xenoStatusPointer->Head_Tilt=angley; online++; } } else { online++; } if (xenoStatusPointer->head_tilt) { xenoStatusPointer->head_tilt->Active=1; } if (online<=1) { /* Still moving! */ xenoStatusPointer->head_moving=1; } if (xenoStatusPointer->HeadLaserOnTarget) { online=2; } if (online>1) { return(1); } else { return(0); } } void Xeno_TorsoMovement_TrackToAngle(STRATEGYBLOCK *sbPtr,int rate,int in_anglex) { XENO_STATUS_BLOCK *xenoStatusPointer; int anglex; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Turn the torso to face a certain way. No angley here. */ anglex=in_anglex; if (anglex>=3072) anglex-=4096; if (anglex>=2048) anglex=anglex-3072; if (anglex> 1024) anglex=2048-anglex; anglex<<=4; if (xenoStatusPointer->Torso_Twist<anglex) { xenoStatusPointer->Torso_Twist+=(NormalFrameTime>>rate); if (xenoStatusPointer->Torso_Twist>(XENO_TORSO_GIMBALL<<4)) { xenoStatusPointer->Torso_Twist=(XENO_TORSO_GIMBALL<<4); } else if (xenoStatusPointer->Torso_Twist>anglex) { xenoStatusPointer->Torso_Twist=anglex; } else { xenoStatusPointer->torso_moving=1; } } else if (xenoStatusPointer->Torso_Twist>anglex) { xenoStatusPointer->Torso_Twist-=(NormalFrameTime>>rate); if (xenoStatusPointer->Torso_Twist<-(XENO_TORSO_GIMBALL<<4)) { xenoStatusPointer->Torso_Twist=-(XENO_TORSO_GIMBALL<<4); } else if (xenoStatusPointer->Torso_Twist<anglex) { xenoStatusPointer->Torso_Twist=anglex; } else { xenoStatusPointer->torso_moving=1; } } if (xenoStatusPointer->torso_twist) { xenoStatusPointer->torso_twist->Active=1; } } void Xeno_TorsoMovement_Centre(STRATEGYBLOCK *sbPtr,int rate) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Turn the torso to face a certain way. No angley here. */ if (xenoStatusPointer->Torso_Twist<0) { xenoStatusPointer->Torso_Twist+=(NormalFrameTime>>rate); if (xenoStatusPointer->Torso_Twist>(XENO_TORSO_GIMBALL<<4)) { xenoStatusPointer->Torso_Twist=(XENO_TORSO_GIMBALL<<4); } else if (xenoStatusPointer->Torso_Twist>0) { xenoStatusPointer->Torso_Twist=0; } else { xenoStatusPointer->torso_moving=1; } } else if (xenoStatusPointer->Torso_Twist>0) { xenoStatusPointer->Torso_Twist-=(NormalFrameTime>>rate); if (xenoStatusPointer->Torso_Twist<-(XENO_TORSO_GIMBALL<<4)) { xenoStatusPointer->Torso_Twist=-(XENO_TORSO_GIMBALL<<4); } else if (xenoStatusPointer->Torso_Twist<0) { xenoStatusPointer->Torso_Twist=0; } else { xenoStatusPointer->torso_moving=1; } } if (xenoStatusPointer->torso_twist) { xenoStatusPointer->torso_twist->Active=1; } } int Xeno_LeftArmMovement_TrackToAngles(STRATEGYBLOCK *sbPtr,int rate,int in_anglex,int in_angley) { XENO_STATUS_BLOCK *xenoStatusPointer; int real_anglex,angley,online; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Aim the Left Arm at a point. */ real_anglex=in_anglex-(xenoStatusPointer->Torso_Twist>>4); angley=in_angley; online=0; /* Now fix multiples. */ while ((real_anglex>4095)||(real_anglex<0)) { if (real_anglex<0) { real_anglex+=4096; } else if (real_anglex>4095) { real_anglex-=4096; } } if (real_anglex>=3072) real_anglex-=4096; if (real_anglex>=2048) real_anglex=real_anglex-3072; if (real_anglex> 1024) real_anglex=2048-real_anglex; if (angley>=3072) angley-=4096; if (angley>=2048) angley=angley-3072; if (angley> 1024) angley=2048-angley; real_anglex<<=4; angley<<=4; if (xenoStatusPointer->Left_Arm_Pan<real_anglex) { xenoStatusPointer->Left_Arm_Pan+=(NormalFrameTime>>rate); if (xenoStatusPointer->Left_Arm_Pan>(XENO_LEFTARM_ACW_GIMBALL<<4)) { xenoStatusPointer->Left_Arm_Pan=(XENO_LEFTARM_ACW_GIMBALL<<4); } else if (xenoStatusPointer->Left_Arm_Pan>real_anglex) { xenoStatusPointer->Left_Arm_Pan=real_anglex; online++; } } else if (xenoStatusPointer->Left_Arm_Pan>real_anglex) { xenoStatusPointer->Left_Arm_Pan-=(NormalFrameTime>>rate); if (xenoStatusPointer->Left_Arm_Pan<-(XENO_LEFTARM_CW_GIMBALL<<4)) { xenoStatusPointer->Left_Arm_Pan=-(XENO_LEFTARM_CW_GIMBALL<<4); } else if (xenoStatusPointer->Left_Arm_Pan<real_anglex) { xenoStatusPointer->Left_Arm_Pan=real_anglex; online++; } } else { online++; } if (xenoStatusPointer->left_arm_pan) { xenoStatusPointer->left_arm_pan->Active=1; } /* Now y. */ angley=-angley; /* Oops. */ if (xenoStatusPointer->Left_Arm_Tilt<angley) { xenoStatusPointer->Left_Arm_Tilt+=(NormalFrameTime>>rate); if (xenoStatusPointer->Left_Arm_Tilt>(XENO_ARM_PITCH_GIMBALL<<4)) { xenoStatusPointer->Left_Arm_Tilt=(XENO_ARM_PITCH_GIMBALL<<4); } else if (xenoStatusPointer->Left_Arm_Tilt>angley) { xenoStatusPointer->Left_Arm_Tilt=angley; online++; } } else if (xenoStatusPointer->Left_Arm_Tilt>angley) { xenoStatusPointer->Left_Arm_Tilt-=(NormalFrameTime>>rate); if (xenoStatusPointer->Left_Arm_Tilt<-(XENO_ARM_PITCH_GIMBALL<<4)) { xenoStatusPointer->Left_Arm_Tilt=-(XENO_ARM_PITCH_GIMBALL<<4); } else if (xenoStatusPointer->Left_Arm_Tilt<angley) { xenoStatusPointer->Left_Arm_Tilt=angley; online++; } } else { online++; } if (xenoStatusPointer->left_arm_tilt) { xenoStatusPointer->left_arm_tilt->Active=1; } if (online<=1) { /* Still going! */ xenoStatusPointer->la_moving=1; } if (xenoStatusPointer->HeadLaserOnTarget) { xenoStatusPointer->UseLALaser=1; } if (xenoStatusPointer->LALaserOnTarget) { online=2; } if (online>1) { if (xenoStatusPointer->Target) { /* What the heck! */ xenoStatusPointer->FiringLeft=1; } return(1); } else { return(0); } } void Xeno_LeftArmMovement_Centre(STRATEGYBLOCK *sbPtr,int rate) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Centre the Left Arm. */ if (xenoStatusPointer->Left_Arm_Pan<0) { xenoStatusPointer->Left_Arm_Pan+=(NormalFrameTime>>rate); if (xenoStatusPointer->Left_Arm_Pan>(XENO_LEFTARM_ACW_GIMBALL<<4)) { xenoStatusPointer->Left_Arm_Pan=(XENO_LEFTARM_ACW_GIMBALL<<4); } else if (xenoStatusPointer->Left_Arm_Pan>0) { xenoStatusPointer->Left_Arm_Pan=0; } else { xenoStatusPointer->la_moving=1; } } else if (xenoStatusPointer->Left_Arm_Pan>0) { xenoStatusPointer->Left_Arm_Pan-=(NormalFrameTime>>rate); if (xenoStatusPointer->Left_Arm_Pan<-(XENO_LEFTARM_CW_GIMBALL<<4)) { xenoStatusPointer->Left_Arm_Pan=-(XENO_LEFTARM_CW_GIMBALL<<4); } else if (xenoStatusPointer->Left_Arm_Pan<0) { xenoStatusPointer->Left_Arm_Pan=0; } else { xenoStatusPointer->la_moving=1; } } if (xenoStatusPointer->left_arm_pan) { xenoStatusPointer->left_arm_pan->Active=1; } /* Now y. */ if (xenoStatusPointer->Left_Arm_Tilt<0) { xenoStatusPointer->Left_Arm_Tilt+=(NormalFrameTime>>rate); if (xenoStatusPointer->Left_Arm_Tilt>(XENO_ARM_PITCH_GIMBALL<<4)) { xenoStatusPointer->Left_Arm_Tilt=(XENO_ARM_PITCH_GIMBALL<<4); } else if (xenoStatusPointer->Left_Arm_Tilt>0) { xenoStatusPointer->Left_Arm_Tilt=0; } else { xenoStatusPointer->la_moving=1; } } else if (xenoStatusPointer->Left_Arm_Tilt>0) { xenoStatusPointer->Left_Arm_Tilt-=(NormalFrameTime>>rate); if (xenoStatusPointer->Left_Arm_Tilt<-(XENO_ARM_PITCH_GIMBALL<<4)) { xenoStatusPointer->Left_Arm_Tilt=-(XENO_ARM_PITCH_GIMBALL<<4); } else if (xenoStatusPointer->Left_Arm_Tilt<0) { xenoStatusPointer->Left_Arm_Tilt=0; } else { xenoStatusPointer->la_moving=1; } } if (xenoStatusPointer->left_arm_tilt) { xenoStatusPointer->left_arm_tilt->Active=1; } return; } int Xeno_RightArmMovement_TrackToAngles(STRATEGYBLOCK *sbPtr,int rate,int in_anglex,int in_angley) { XENO_STATUS_BLOCK *xenoStatusPointer; int real_anglex,angley,online; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Aim the Right Arm at a point. */ real_anglex=in_anglex-(xenoStatusPointer->Torso_Twist>>4)+RATweak; angley=in_angley; online=0; /* Now fix multiples. */ while ((real_anglex>4095)||(real_anglex<0)) { if (real_anglex<0) { real_anglex+=4096; } else if (real_anglex>4095) { real_anglex-=4096; } } if (real_anglex>=3072) real_anglex-=4096; if (real_anglex>=2048) real_anglex=real_anglex-3072; if (real_anglex> 1024) real_anglex=2048-real_anglex; if (angley>=3072) angley-=4096; if (angley>=2048) angley=angley-3072; if (angley> 1024) angley=2048-angley; real_anglex<<=4; angley<<=4; if (xenoStatusPointer->Right_Arm_Pan<real_anglex) { xenoStatusPointer->Right_Arm_Pan+=(NormalFrameTime>>rate); if (xenoStatusPointer->Right_Arm_Pan>(XENO_RIGHTARM_ACW_GIMBALL<<4)) { xenoStatusPointer->Right_Arm_Pan=(XENO_RIGHTARM_ACW_GIMBALL<<4); } else if (xenoStatusPointer->Right_Arm_Pan>real_anglex) { xenoStatusPointer->Right_Arm_Pan=real_anglex; online++; } } else if (xenoStatusPointer->Right_Arm_Pan>real_anglex) { xenoStatusPointer->Right_Arm_Pan-=(NormalFrameTime>>rate); if (xenoStatusPointer->Right_Arm_Pan<-(XENO_RIGHTARM_CW_GIMBALL<<4)) { xenoStatusPointer->Right_Arm_Pan=-(XENO_RIGHTARM_CW_GIMBALL<<4); } else if (xenoStatusPointer->Right_Arm_Pan<real_anglex) { xenoStatusPointer->Right_Arm_Pan=real_anglex; online++; } } else { online++; } if (xenoStatusPointer->right_arm_pan) { xenoStatusPointer->right_arm_pan->Active=1; } /* Now y. */ angley=-angley; /* Oops. */ if (xenoStatusPointer->Right_Arm_Tilt<angley) { xenoStatusPointer->Right_Arm_Tilt+=(NormalFrameTime>>rate); if (xenoStatusPointer->Right_Arm_Tilt>(XENO_ARM_PITCH_GIMBALL<<4)) { xenoStatusPointer->Right_Arm_Tilt=(XENO_ARM_PITCH_GIMBALL<<4); } else if (xenoStatusPointer->Right_Arm_Tilt>angley) { xenoStatusPointer->Right_Arm_Tilt=angley; online++; } } else if (xenoStatusPointer->Right_Arm_Tilt>angley) { xenoStatusPointer->Right_Arm_Tilt-=(NormalFrameTime>>rate); if (xenoStatusPointer->Right_Arm_Tilt<-(XENO_ARM_PITCH_GIMBALL<<4)) { xenoStatusPointer->Right_Arm_Tilt=-(XENO_ARM_PITCH_GIMBALL<<4); } else if (xenoStatusPointer->Right_Arm_Tilt<angley) { xenoStatusPointer->Right_Arm_Tilt=angley; online++; } } else { online++; } if (xenoStatusPointer->right_arm_tilt) { xenoStatusPointer->right_arm_tilt->Active=1; } if (online<=1) { /* Still moving! */ xenoStatusPointer->ra_moving=1; } if (xenoStatusPointer->HeadLaserOnTarget) { xenoStatusPointer->UseRALaser=1; } if (xenoStatusPointer->RALaserOnTarget) { online=2; } if (online>1) { if (xenoStatusPointer->Target) { /* What the heck! */ xenoStatusPointer->FiringRight=1; } return(1); } else { return(0); } } void Xeno_RightArmMovement_Centre(STRATEGYBLOCK *sbPtr,int rate) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Centre the Right Arm. */ if (xenoStatusPointer->Right_Arm_Pan<0) { xenoStatusPointer->Right_Arm_Pan+=(NormalFrameTime>>rate); if (xenoStatusPointer->Right_Arm_Pan>(XENO_RIGHTARM_ACW_GIMBALL<<4)) { xenoStatusPointer->Right_Arm_Pan=(XENO_RIGHTARM_ACW_GIMBALL<<4); } else if (xenoStatusPointer->Right_Arm_Pan>0) { xenoStatusPointer->Right_Arm_Pan=0; } else { xenoStatusPointer->ra_moving=1; } } else if (xenoStatusPointer->Right_Arm_Pan>0) { xenoStatusPointer->Right_Arm_Pan-=(NormalFrameTime>>rate); if (xenoStatusPointer->Right_Arm_Pan<-(XENO_RIGHTARM_CW_GIMBALL<<4)) { xenoStatusPointer->Right_Arm_Pan=-(XENO_RIGHTARM_CW_GIMBALL<<4); } else if (xenoStatusPointer->Right_Arm_Pan<0) { xenoStatusPointer->Right_Arm_Pan=0; } else { xenoStatusPointer->ra_moving=1; } } if (xenoStatusPointer->right_arm_pan) { xenoStatusPointer->right_arm_pan->Active=1; } /* Now y. */ if (xenoStatusPointer->Right_Arm_Tilt<0) { xenoStatusPointer->Right_Arm_Tilt+=(NormalFrameTime>>rate); if (xenoStatusPointer->Right_Arm_Tilt>(XENO_ARM_PITCH_GIMBALL<<4)) { xenoStatusPointer->Right_Arm_Tilt=(XENO_ARM_PITCH_GIMBALL<<4); } else if (xenoStatusPointer->Right_Arm_Tilt>0) { xenoStatusPointer->Right_Arm_Tilt=0; } else { xenoStatusPointer->ra_moving=1; } } else if (xenoStatusPointer->Right_Arm_Tilt>0) { xenoStatusPointer->Right_Arm_Tilt-=(NormalFrameTime>>rate); if (xenoStatusPointer->Right_Arm_Tilt<-(XENO_ARM_PITCH_GIMBALL<<4)) { xenoStatusPointer->Right_Arm_Tilt=-(XENO_ARM_PITCH_GIMBALL<<4); } else if (xenoStatusPointer->Right_Arm_Tilt<0) { xenoStatusPointer->Right_Arm_Tilt=0; } else { xenoStatusPointer->ra_moving=1; } } if (xenoStatusPointer->right_arm_tilt) { xenoStatusPointer->right_arm_tilt->Active=1; } return; } int XenoActivation_FrustumReject(VECTORCH *localOffset) { if ( (localOffset->vz <0) && (localOffset->vz < localOffset->vx) && (localOffset->vz < -localOffset->vx) && (localOffset->vz < localOffset->vy) && (localOffset->vz < -localOffset->vy) ) { /* 90 horizontal, 90 vertical. */ return(1); } else { return(0); } } int XenoSight_FrustumReject(STRATEGYBLOCK *sbPtr,VECTORCH *localOffset) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); if ( (localOffset->vx>0) ) { /* 180 horizontal, 180 vertical. */ return(1); } else { if ((xenoStatusPointer->Target)||(xenoStatusPointer->ShotThisFrame)) { return(1); } else { return(0); } } } void Xeno_UpdateTargetTrackPos(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); if (xenoStatusPointer->Target==NULL) { xenoStatusPointer->targetTrackPos.vx=0; xenoStatusPointer->targetTrackPos.vy=0; xenoStatusPointer->targetTrackPos.vz=0; return; } GetTargetingPointOfObject_Far(xenoStatusPointer->Target,&xenoStatusPointer->targetTrackPos); } static void ProcessFarXenoborgTargetModule(STRATEGYBLOCK *sbPtr, AIMODULE* targetModule) { NPC_TARGETMODULESTATUS targetStatus; XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); LOCALASSERT(targetModule); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); targetStatus = GetTargetAIModuleStatus(sbPtr, targetModule, 0); switch(targetStatus) { case(NPCTM_NoEntryPoint): { /* do nothing */ FarNpc_FlipAround(sbPtr); break; } case(NPCTM_NormalRoom): { /* locate to target */ LocateFarNPCInAIModule(sbPtr, targetModule); break; } case(NPCTM_AirDuct): { /* loacate to target */ LocateFarNPCInAIModule(sbPtr, targetModule); break; } case(NPCTM_LiftTeleport): { /* do nothing */ FarNpc_FlipAround(sbPtr); break; } case(NPCTM_ProxDoorOpen): { LocateFarNPCInAIModule(sbPtr, targetModule); break; } case(NPCTM_ProxDoorNotOpen): { MODULE *renderModule; renderModule=*(targetModule->m_module_ptrs); /* trigger the door, and set timer to quick so we can catch the door when it's open */ ((PROXDOOR_BEHAV_BLOCK *)renderModule->m_sbptr->SBdataptr)->alienTrigger = 1; break; } case(NPCTM_LiftDoorOpen): { /* do nothing - can't use lifts */ //FarNpc_FlipAround(sbPtr); /* What the hell!!! */ LocateFarNPCInAIModule(sbPtr, targetModule); break; } case(NPCTM_LiftDoorNotOpen): { /* do nothing - can't open lift doors */ FarNpc_FlipAround(sbPtr); break; } case(NPCTM_SecurityDoorOpen): { /* locate to target, and move thro' quick as we can't retrigger */ LocateFarNPCInAIModule(sbPtr, targetModule); break; } case(NPCTM_SecurityDoorNotOpen): { MODULE *renderModule; renderModule=*(targetModule->m_module_ptrs); /* do some door opening stuff here. Door should stay open for long enough for us to catch it open next time */ RequestState((renderModule->m_sbptr),1,0); break; } default: { LOCALASSERT(1==0); } } } void Execute_Xeno_ActiveWait_Far(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; int anglex,angley,correctlyOrientated; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* What to do? Do we have a target? */ if (ShowXenoStats) { PrintDebuggingText("In ActiveWait Far.\n"); } EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Powered_Up_Standard,ONE_FIXED,(ONE_FIXED>>2)); if (xenoStatusPointer->Target==NULL) { #if FAR_XENO_ACTIVITY /* Let's wave the head around. */ Xeno_TorsoMovement_Centre(sbPtr,XENO_TORSO_TWIST_RATE); Xeno_LeftArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); Xeno_RightArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); Xeno_HeadMovement_ScanLeftRight(sbPtr,XENO_HEAD_SCAN_RATE); Xeno_HeadMovement_ScanUpDown(sbPtr,XENO_HEAD_SCAN_RATE+2); #endif if (sbPtr->containingModule->m_aimodule!=xenoStatusPointer->my_module) { Xeno_Enter_Returning_State(sbPtr); return; } xenoStatusPointer->stateTimer+=NormalFrameTime; if (xenoStatusPointer->stateTimer>xenoStatusPointer->UpTime) { Xeno_Enter_PowerDown_State(sbPtr); } /* Are we at home? */ if (sbPtr->containingModule->m_aimodule!=xenoStatusPointer->my_module) { Xeno_Enter_Returning_State(sbPtr); return; } /* Are we facing the right way? */ correctlyOrientated = NPCOrientateToVector(sbPtr, &xenoStatusPointer->my_orientdir_therin,ONE_FIXED,NULL); if (!correctlyOrientated) { SECTION_DATA *master_section; master_section=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"pelvis presley"); GLOBALASSERT(master_section); Xenoborg_GetRelativeAngles(sbPtr,&anglex,&angley,&master_section->World_Offset); if (anglex>0) { EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Turn_Right,XENO_TURNING_ANIM_SPEED,(ONE_FIXED>>2)); } else { EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Turn_Left,XENO_TURNING_ANIM_SPEED,(ONE_FIXED>>2)); } #if FAR_XENO_ACTIVITY if (xenoStatusPointer->soundHandle1==SOUND_NOACTIVEINDEX) { Sound_Play(SID_LOADMOVE,"del",&sbPtr->DynPtr->Position,&xenoStatusPointer->soundHandle1); } #endif } else { /* Otherwise just wait? */ if (xenoStatusPointer->soundHandle1!=SOUND_NOACTIVEINDEX) { /* Well, it shouldn't be! */ Sound_Stop(xenoStatusPointer->soundHandle1); } EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Powered_Up_Standard,ONE_FIXED,(ONE_FIXED>>2)); xenoStatusPointer->stateTimer+=NormalFrameTime; if (xenoStatusPointer->stateTimer>xenoStatusPointer->UpTime) { Xeno_Enter_PowerDown_State(sbPtr); } } return; } GLOBALASSERT(xenoStatusPointer->Target); /* Now we have a target. Can we see it? */ if (xenoStatusPointer->targetSightTest==0) { /* Can't see them. Are we out of range? */ if (GetNextModuleForLink(sbPtr->containingModule->m_aimodule, xenoStatusPointer->my_module,(xenoStatusPointer->module_range)-1,0)==NULL) { Xeno_Enter_Returning_State(sbPtr); } else { Xeno_Enter_Following_State(sbPtr); } return; } #if FAR_XENO_ACTIVITY Xeno_TurnAndTarget(sbPtr,&anglex,&angley); if ((anglex>(((XENO_HEADPAN_GIMBALL)*7)/8)) ||(anglex<-(((XENO_HEADPAN_GIMBALL)*7)/8))) { Xeno_Enter_TurnToFace_State(sbPtr); } #endif if (ShowXenoStats) { PrintDebuggingText("Targets in module....\n"); } } void Execute_Xeno_TurnToFace_Far(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; int correctlyOrientated; int anglex,angley; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* Do we have a target? */ if (ShowXenoStats) { PrintDebuggingText("In Turn To Face Far.\n"); } if (xenoStatusPointer->Target==NULL) { Xeno_Enter_ActiveWait_State(sbPtr); /* Otherwise just wait? */ return; } /* Now we have a target. */ GLOBALASSERT(xenoStatusPointer->Target); /* Set up animation... Which Way? */ { SECTION_DATA *master_section; VECTORCH orientationDirn; master_section=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"pelvis presley"); GLOBALASSERT(master_section); Xenoborg_GetRelativeAngles(sbPtr,&anglex,&angley,&master_section->World_Offset); if (anglex<2048) { EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Turn_Right,XENO_TURNING_ANIM_SPEED,(ONE_FIXED>>2)); } else { EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Turn_Left,XENO_TURNING_ANIM_SPEED,(ONE_FIXED>>2)); } /* Then turn to face it, of course. */ orientationDirn.vx = xenoStatusPointer->targetTrackPos.vx - sbPtr->DynPtr->Position.vx; orientationDirn.vy = 0; orientationDirn.vz = xenoStatusPointer->targetTrackPos.vz - sbPtr->DynPtr->Position.vz; correctlyOrientated = NPCOrientateToVector(sbPtr, &orientationDirn,ONE_FIXED,NULL); /* Spin FAST. */ } #if FAR_XENO_ACTIVITY Xeno_TurnAndTarget(sbPtr,&anglex,&angley); #endif if (correctlyOrientated) { Xeno_Enter_ActiveWait_State(sbPtr); } } void Execute_Xeno_Follow_Far(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; #if FAR_XENO_ACTIVITY int anglex,angley; #endif LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* In theory, we're following the target, and can't see it. */ if (ShowXenoStats) { PrintDebuggingText("In Follow Far.\n"); } if (xenoStatusPointer->Target==NULL) { /* Let's wave the head around. */ #if FAR_XENO_ACTIVITY Xeno_HeadMovement_ScanLeftRight(sbPtr,XENO_HEAD_SCAN_RATE); Xeno_HeadMovement_ScanUpDown(sbPtr,XENO_HEAD_SCAN_RATE+2); #endif /* And return to my module. */ Xeno_Enter_Returning_State(sbPtr); return; } /* Increment the Far state timer */ xenoStatusPointer->stateTimer += NormalFrameTime; /* check if far state timer has timed-out. If so, it is time to do something. Otherwise just return. */ if(xenoStatusPointer->stateTimer < XENO_FAR_MOVE_TIME) { #if FAR_XENO_ACTIVITY Xeno_TurnAndTarget(sbPtr,&anglex,&angley); #endif return; } GLOBALASSERT(xenoStatusPointer->Target); /* Now we know have a target. Can we see it yet? */ if (xenoStatusPointer->targetSightTest==0) { AIMODULE *targetModule; /* Can't see them. Never mind. Go to the next module? */ if (xenoStatusPointer->Target->containingModule==NULL) { /* Fall through for now. */ targetModule=NULL; } else if (GetNextModuleForLink(sbPtr->containingModule->m_aimodule, xenoStatusPointer->my_module,(xenoStatusPointer->module_range)-1,0)==NULL) { /* Too Far! */ Xeno_Enter_ActiveWait_State(sbPtr); return; } else { /* Still in range: keep going. */ targetModule=GetNextModuleForLink(sbPtr->containingModule->m_aimodule, xenoStatusPointer->Target->containingModule->m_aimodule,xenoStatusPointer->module_range,0); } if (targetModule==NULL) { /* They're way away. */ Xeno_Enter_Returning_State(sbPtr); return; } if (targetModule!=xenoStatusPointer->Target->containingModule->m_aimodule) { GLOBALASSERT(targetModule); ProcessFarXenoborgTargetModule(sbPtr,targetModule); } else { /* In our target's module! */ Xeno_Enter_ActiveWait_State(sbPtr); } } else { /* Re-aquired! */ Xeno_Enter_ActiveWait_State(sbPtr); return; } xenoStatusPointer->stateTimer=0; #if 0 EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Walking,XENO_WALKING_ANIM_SPEED,(ONE_FIXED>>2)); #else XenoborgHandleMovingAnimation(sbPtr); #endif #if FAR_XENO_ACTIVITY if (xenoStatusPointer->targetSightTest==0) { Xeno_TorsoMovement_Centre(sbPtr,XENO_TORSO_TWIST_RATE); Xeno_LeftArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); Xeno_RightArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); Xeno_HeadMovement_ScanLeftRight(sbPtr,XENO_HEAD_SCAN_RATE); } else { Xeno_TurnAndTarget(sbPtr,&anglex,&angley); } #endif } void Execute_Xeno_Return_Far(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* In theory, we're following the target, and can't see it. */ if (ShowXenoStats) { PrintDebuggingText("In Return Far.\n"); } if (xenoStatusPointer->Target!=NULL) { /* Saw something! */ /* Go to active wait. */ Xeno_Enter_ActiveWait_State(sbPtr); return; } /* Increment the Far state timer */ xenoStatusPointer->stateTimer += NormalFrameTime; /* check if far state timer has timed-out. If so, it is time to do something. Otherwise just return. */ if(xenoStatusPointer->stateTimer < XENO_FAR_MOVE_TIME) { #if FAR_XENO_ACTIVITY Xeno_HeadMovement_ScanLeftRight(sbPtr,XENO_HEAD_SCAN_RATE); Xeno_TorsoMovement_Centre(sbPtr,XENO_TORSO_TWIST_RATE); Xeno_LeftArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); Xeno_RightArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); #endif return; } GLOBALASSERT(xenoStatusPointer->Target==NULL); /* Find our way home. */ { AIMODULE *targetModule; /* Go to the next module. */ targetModule=GetNextModuleForLink(sbPtr->containingModule->m_aimodule, xenoStatusPointer->my_module,xenoStatusPointer->module_range+2,0); /* Just to be on the safe side. */ if (targetModule==NULL) { /* Emergency! */ targetModule=GetNextModuleForLink(sbPtr->containingModule->m_aimodule, xenoStatusPointer->my_module,xenoStatusPointer->module_range+5,0); if (targetModule==NULL) { /* Totally broken. Stay here. */ Xeno_CopeWithLossOfHome(sbPtr); return; } } if (targetModule!=sbPtr->containingModule->m_aimodule) { GLOBALASSERT(targetModule); ProcessFarXenoborgTargetModule(sbPtr,targetModule); } else { /* In our own home module! */ sbPtr->DynPtr->Position=xenoStatusPointer->my_spot_therin; Xeno_Enter_ActiveWait_State(sbPtr); } } xenoStatusPointer->stateTimer=0; #if 0 EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Walking,XENO_WALKING_ANIM_SPEED,(ONE_FIXED>>2)); #else XenoborgHandleMovingAnimation(sbPtr); #endif #if FAR_XENO_ACTIVITY Xeno_TorsoMovement_Centre(sbPtr,XENO_TORSO_TWIST_RATE); Xeno_LeftArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); Xeno_RightArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); Xeno_HeadMovement_ScanLeftRight(sbPtr,XENO_HEAD_SCAN_RATE); #endif } void Execute_Xeno_Avoidance_Far(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); if (ShowXenoStats) { PrintDebuggingText("In Avoidance Far.\n"); } /* Sequences... */ #if 0 EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Walking,XENO_WALKING_ANIM_SPEED,(ONE_FIXED>>2)); #else XenoborgHandleMovingAnimation(sbPtr); #endif #if FAR_XENO_ACTIVITY if (xenoStatusPointer->targetSightTest==0) { Xeno_TorsoMovement_Centre(sbPtr,XENO_TORSO_TWIST_RATE); Xeno_LeftArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); Xeno_RightArmMovement_Centre(sbPtr,XENO_ARM_LOCK_RATE); Xeno_HeadMovement_ScanLeftRight(sbPtr,XENO_HEAD_SCAN_RATE); } else { Xeno_TurnAndTarget(sbPtr,&anglex,&angley); } #endif { /* go to an appropriate state */ switch (xenoStatusPointer->lastState) { case XS_Returning: Xeno_Enter_Returning_State(sbPtr); return; break; case XS_Following: Xeno_Enter_Following_State(sbPtr); return; break; default: Xeno_Enter_ActiveWait_State(sbPtr); return; break; } /* Still here? */ return; } return; } #define FIRING_RATE_LEFT 25 void Xenoborg_MaintainLeftGun(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; SECTION_DATA *left_dum; VECTORCH alpha; VECTORCH beta; int multiple; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); left_dum=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"flash dummy A"); if (xenoStatusPointer->Wounds&section_flag_left_hand) { xenoStatusPointer->FiringLeft=0; } if ((xenoStatusPointer->FiringLeft==0)||(left_dum==NULL)||(xenoStatusPointer->IAmFar)) { /* Not firing, go away. */ xenoStatusPointer->LeftMainBeam.BeamIsOn = 0; return; } /* Okay, must be firing. Did we get anyone? */ multiple=FIRING_RATE_LEFT*NormalFrameTime; #if 0 LOS_Lambda = NPC_MAX_VIEWRANGE; LOS_ObjectHitPtr = 0; LOS_HModel_Section=NULL; { extern int NumActiveBlocks; extern DISPLAYBLOCK* ActiveBlockList[]; int numberOfObjects = NumActiveBlocks; while (numberOfObjects--) { DISPLAYBLOCK* objectPtr = ActiveBlockList[numberOfObjects]; alpha = left_dum->World_Offset; beta.vx=left_dum->SecMat.mat31; beta.vy=left_dum->SecMat.mat32; beta.vz=left_dum->SecMat.mat33; GLOBALASSERT(objectPtr); if (objectPtr!=sbPtr->SBdptr) { /* Can't hit self. */ CheckForVectorIntersectionWith3dObject(objectPtr, &alpha, &beta,1); } } } #else { alpha = left_dum->World_Offset; beta.vx=left_dum->SecMat.mat31; beta.vy=left_dum->SecMat.mat32; beta.vz=left_dum->SecMat.mat33; FindPolygonInLineOfSight(&beta,&alpha,0,sbPtr->SBdptr); } #endif /* Now deal with LOS_ObjectHitPtr. */ if (LOS_ObjectHitPtr) { if (LOS_HModel_Section) { if (LOS_ObjectHitPtr->ObStrategyBlock) { if (LOS_ObjectHitPtr->ObStrategyBlock->SBdptr) { GLOBALASSERT(LOS_ObjectHitPtr->ObStrategyBlock->SBdptr->HModelControlBlock==LOS_HModel_Section->my_controller); } } } /* this fn needs updating to take amount of damage into account etc. */ HandleWeaponImpact(&LOS_Point,LOS_ObjectHitPtr->ObStrategyBlock,AMMO_XENOBORG,&beta, multiple, LOS_HModel_Section); } /* Cheat for killing far targets? */ if (xenoStatusPointer->Target) { if (xenoStatusPointer->Target->SBdptr==NULL) { HandleWeaponImpact(&xenoStatusPointer->Target->DynPtr->Position,xenoStatusPointer->Target,AMMO_XENOBORG,&beta, multiple, NULL); } } /* update beam SFX data */ xenoStatusPointer->LeftMainBeam.BeamIsOn = 1; xenoStatusPointer->LeftMainBeam.SourcePosition = left_dum->World_Offset; if (LOS_ObjectHitPtr) { xenoStatusPointer->LeftMainBeam.TargetPosition = LOS_Point; } else { /* Must be hitting nothing... */ xenoStatusPointer->LeftMainBeam.TargetPosition=alpha; xenoStatusPointer->LeftMainBeam.TargetPosition.vx+=(beta.vx>>3); xenoStatusPointer->LeftMainBeam.TargetPosition.vy+=(beta.vy>>3); xenoStatusPointer->LeftMainBeam.TargetPosition.vz+=(beta.vz>>3); } if (LOS_ObjectHitPtr==Player) { xenoStatusPointer->LeftMainBeam.BeamHasHitPlayer = 1; } else { xenoStatusPointer->LeftMainBeam.BeamHasHitPlayer = 0; } } #define FIRING_RATE_RIGHT 25 void Xenoborg_MaintainRightGun(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; SECTION_DATA *right_dum; VECTORCH alpha; VECTORCH beta; int multiple; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); right_dum=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"flash dummy B"); if (xenoStatusPointer->Wounds&section_flag_right_hand) { xenoStatusPointer->FiringRight=0; } if ((xenoStatusPointer->FiringRight==0)||(right_dum==NULL)||(xenoStatusPointer->IAmFar)) { /* Not firing, go away. */ xenoStatusPointer->RightMainBeam.BeamIsOn = 0; return; } /* Okay, must be firing. Did we get anyone? */ multiple=FIRING_RATE_RIGHT*NormalFrameTime; #if 0 LOS_Lambda = NPC_MAX_VIEWRANGE; LOS_ObjectHitPtr = 0; LOS_HModel_Section=NULL; { extern int NumActiveBlocks; extern DISPLAYBLOCK* ActiveBlockList[]; int numberOfObjects = NumActiveBlocks; while (numberOfObjects--) { DISPLAYBLOCK* objectPtr = ActiveBlockList[numberOfObjects]; alpha = right_dum->World_Offset; beta.vx=right_dum->SecMat.mat31; beta.vy=right_dum->SecMat.mat32; beta.vz=right_dum->SecMat.mat33; GLOBALASSERT(objectPtr); if (objectPtr!=sbPtr->SBdptr) { /* Can't hit self. */ CheckForVectorIntersectionWith3dObject(objectPtr, &alpha, &beta,1); } } } #else { alpha = right_dum->World_Offset; beta.vx=right_dum->SecMat.mat31; beta.vy=right_dum->SecMat.mat32; beta.vz=right_dum->SecMat.mat33; FindPolygonInLineOfSight(&beta,&alpha,0,sbPtr->SBdptr); } #endif /* Now deal with LOS_ObjectHitPtr. */ if (LOS_ObjectHitPtr) { if (LOS_HModel_Section) { if (LOS_ObjectHitPtr->ObStrategyBlock) { if (LOS_ObjectHitPtr->ObStrategyBlock->SBdptr) { GLOBALASSERT(LOS_ObjectHitPtr->ObStrategyBlock->SBdptr->HModelControlBlock==LOS_HModel_Section->my_controller); } } } /* this fn needs updating to take amount of damage into account etc. */ HandleWeaponImpact(&LOS_Point,LOS_ObjectHitPtr->ObStrategyBlock,AMMO_XENOBORG,&beta, multiple, LOS_HModel_Section); } /* Cheat for killing far targets? */ if (xenoStatusPointer->Target) { if (xenoStatusPointer->Target->SBdptr==NULL) { HandleWeaponImpact(&xenoStatusPointer->Target->DynPtr->Position,xenoStatusPointer->Target,AMMO_XENOBORG,&beta, multiple, NULL); } } /* update beam SFX data */ xenoStatusPointer->RightMainBeam.BeamIsOn = 1; xenoStatusPointer->RightMainBeam.SourcePosition = right_dum->World_Offset; if (LOS_ObjectHitPtr) { xenoStatusPointer->RightMainBeam.TargetPosition = LOS_Point; } else { /* Must be hitting nothing... */ xenoStatusPointer->RightMainBeam.TargetPosition=alpha; xenoStatusPointer->RightMainBeam.TargetPosition.vx+=(beta.vx>>3); xenoStatusPointer->RightMainBeam.TargetPosition.vy+=(beta.vy>>3); xenoStatusPointer->RightMainBeam.TargetPosition.vz+=(beta.vz>>3); } if (LOS_ObjectHitPtr==Player) { xenoStatusPointer->RightMainBeam.BeamHasHitPlayer = 1; } else { xenoStatusPointer->RightMainBeam.BeamHasHitPlayer = 0; } } int Xeno_Activation_Test(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; STRATEGYBLOCK *candidate; MATRIXCH WtoL; int a; MODULE *dmod; dmod=ModuleFromPosition(&sbPtr->DynPtr->Position,playerPherModule); LOCALASSERT(dmod); LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); WtoL=sbPtr->DynPtr->OrientMat; TransposeMatrixCH(&WtoL); for (a=0; a<NumActiveStBlocks; a++) { candidate=ActiveStBlockList[a]; if (candidate!=sbPtr) { if (candidate->DynPtr) { if (Xenoborg_TargetFilter(candidate)) { VECTORCH offset; offset.vx=sbPtr->DynPtr->Position.vx-candidate->DynPtr->Position.vx; offset.vy=sbPtr->DynPtr->Position.vy-candidate->DynPtr->Position.vy; offset.vz=sbPtr->DynPtr->Position.vz-candidate->DynPtr->Position.vz; RotateVector(&offset,&WtoL); if (XenoActivation_FrustumReject(&offset)) { /* Check visibility? */ if (NPCCanSeeTarget(sbPtr,candidate,XENO_NEAR_VIEW_WIDTH)) { if (!NPC_IsDead(candidate)) { if ((IsModuleVisibleFromModule(dmod,candidate->containingModule))) { return(1); } } } } } } } } return(0); } void Xeno_MaintainLasers(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; SECTION_DATA *dum; VECTORCH alpha; VECTORCH beta; int a,uselaser; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); xenoStatusPointer->HeadLaserOnTarget=0; xenoStatusPointer->LALaserOnTarget=0; xenoStatusPointer->RALaserOnTarget=0; #if (FAR_XENO_ACTIVITY==0) if (xenoStatusPointer->IAmFar) { xenoStatusPointer->TargetingLaser[0].BeamIsOn=0; xenoStatusPointer->TargetingLaser[1].BeamIsOn=0; xenoStatusPointer->TargetingLaser[2].BeamIsOn=0; return; } #endif for (a=0; a<3; a++) { xenoStatusPointer->TargetingLaser[a].BeamIsOn=0; switch (a) { case 0: dum=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"flash dummyZ"); if (xenoStatusPointer->UseHeadLaser) { uselaser=1; } else { uselaser=0; } if (dum==NULL) { uselaser=0; } break; case 1: dum=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"flash dummy C"); if (xenoStatusPointer->UseLALaser) { uselaser=1; } else { uselaser=0; } if (dum==NULL) { uselaser=0; } break; case 2: dum=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"flash dummy D"); if (xenoStatusPointer->UseRALaser) { uselaser=1; } else { uselaser=0; } if (dum==NULL) { uselaser=0; } break; default: GLOBALASSERT(0); break; } if (uselaser) { alpha = dum->World_Offset; beta.vx=dum->SecMat.mat31; beta.vy=dum->SecMat.mat32; beta.vz=dum->SecMat.mat33; FindPolygonInLineOfSight(&beta,&alpha,0,sbPtr->SBdptr); /* Now deal with LOS_ObjectHitPtr. */ if (LOS_ObjectHitPtr==Player) { xenoStatusPointer->TargetingLaser[a].BeamHasHitPlayer=1; } else { xenoStatusPointer->TargetingLaser[a].BeamHasHitPlayer=0; } xenoStatusPointer->TargetingLaser[a].SourcePosition=alpha; if (LOS_ObjectHitPtr) { xenoStatusPointer->TargetingLaser[a].TargetPosition=LOS_Point; } else { /* Must be hitting nothing... */ xenoStatusPointer->TargetingLaser[a].TargetPosition=alpha; xenoStatusPointer->TargetingLaser[a].TargetPosition.vx+=(beta.vx>>3); xenoStatusPointer->TargetingLaser[a].TargetPosition.vy+=(beta.vy>>3); xenoStatusPointer->TargetingLaser[a].TargetPosition.vz+=(beta.vz>>3); } xenoStatusPointer->TargetingLaser[a].BeamIsOn=1; if (LOS_ObjectHitPtr) { if (LOS_ObjectHitPtr->ObStrategyBlock==xenoStatusPointer->Target) { switch (a) { case 0: xenoStatusPointer->HeadLaserOnTarget=1; break; case 1: xenoStatusPointer->LALaserOnTarget=1; break; case 2: xenoStatusPointer->RALaserOnTarget=1; break; default: GLOBALASSERT(0); break; } } } } } } void Xeno_SwitchLED(STRATEGYBLOCK *sbPtr,int state) { XENO_STATUS_BLOCK *xenoStatusPointer; SECTION_DATA *led; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); led=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"led"); if (led) { if (led->tac_ptr) { led->tac_ptr->tac_sequence = state ; led->tac_ptr->tac_txah_s = GetTxAnimHeaderFromShape(led->tac_ptr, led->ShapeNum); } } } void Xeno_Stomp(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; SECTION_DATA *foot; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); foot=NULL; if (xenoStatusPointer->HModelController.keyframe_flags&4) { foot=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"right foot"); } else if (xenoStatusPointer->HModelController.keyframe_flags&8) { foot=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"left foot"); } if (foot) { Sound_Play(SID_STOMP,"d",&foot->World_Offset); } } void Xeno_MaintainSounds(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; SECTION_DATA *sec; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); /* First, the two big system sounds. */ if (xenoStatusPointer->soundHandle1!=SOUND_NOACTIVEINDEX) { Sound_Update3d(xenoStatusPointer->soundHandle1,&sbPtr->DynPtr->Position); } if (xenoStatusPointer->soundHandle2!=SOUND_NOACTIVEINDEX) { Sound_Update3d(xenoStatusPointer->soundHandle2,&sbPtr->DynPtr->Position); } /* Now, all the lesser sounds: */ /* Head. */ sec=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"head"); if (sec==NULL) { /* No sound. */ if (xenoStatusPointer->head_whirr!=SOUND_NOACTIVEINDEX) { Sound_Stop(xenoStatusPointer->head_whirr); } } else { if (xenoStatusPointer->head_moving==0) { /* Stationary. */ if (xenoStatusPointer->head_whirr!=SOUND_NOACTIVEINDEX) { Sound_Stop(xenoStatusPointer->head_whirr); Sound_Play(SID_ARMEND,"d",&sec->World_Offset); } } else { /* Moving! */ if (xenoStatusPointer->head_whirr==SOUND_NOACTIVEINDEX) { Sound_Play(SID_ARMSTART,"d",&sec->World_Offset); Sound_Play(SID_ARMMID,"del",&sec->World_Offset,&xenoStatusPointer->head_whirr); } else { Sound_Update3d(xenoStatusPointer->head_whirr,&sec->World_Offset); } } } /* Left Arm. */ sec=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"left bicep"); if (sec==NULL) { /* No sound. */ if (xenoStatusPointer->left_arm_whirr!=SOUND_NOACTIVEINDEX) { Sound_Stop(xenoStatusPointer->left_arm_whirr); } } else { if (xenoStatusPointer->la_moving==0) { /* Stationary. */ if (xenoStatusPointer->left_arm_whirr!=SOUND_NOACTIVEINDEX) { Sound_Stop(xenoStatusPointer->left_arm_whirr); Sound_Play(SID_ARMEND,"d",&sec->World_Offset); } } else { /* Moving! */ if (xenoStatusPointer->left_arm_whirr==SOUND_NOACTIVEINDEX) { Sound_Play(SID_ARMSTART,"d",&sec->World_Offset); Sound_Play(SID_ARMMID,"del",&sec->World_Offset,&xenoStatusPointer->left_arm_whirr); } else { Sound_Update3d(xenoStatusPointer->left_arm_whirr,&sec->World_Offset); } } } /* Right Arm. */ sec=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"right bicep"); if (sec==NULL) { /* No sound. */ if (xenoStatusPointer->right_arm_whirr!=SOUND_NOACTIVEINDEX) { Sound_Stop(xenoStatusPointer->right_arm_whirr); } } else { if (xenoStatusPointer->ra_moving==0) { /* Stationary. */ if (xenoStatusPointer->right_arm_whirr!=SOUND_NOACTIVEINDEX) { Sound_Stop(xenoStatusPointer->right_arm_whirr); Sound_Play(SID_ARMEND,"d",&sec->World_Offset); } } else { /* Moving! */ if (xenoStatusPointer->right_arm_whirr==SOUND_NOACTIVEINDEX) { Sound_Play(SID_ARMSTART,"d",&sec->World_Offset); Sound_Play(SID_ARMMID,"del",&sec->World_Offset,&xenoStatusPointer->right_arm_whirr); } else { Sound_Update3d(xenoStatusPointer->right_arm_whirr,&sec->World_Offset); } } } /* Torso Twist. */ sec=GetThisSectionData(xenoStatusPointer->HModelController.section_data,"chest"); if (sec==NULL) { /* No sound. */ if (xenoStatusPointer->torso_whirr!=SOUND_NOACTIVEINDEX) { Sound_Stop(xenoStatusPointer->torso_whirr); } } else { if (xenoStatusPointer->torso_moving==0) { /* Stationary. */ if (xenoStatusPointer->torso_whirr!=SOUND_NOACTIVEINDEX) { Sound_Stop(xenoStatusPointer->torso_whirr); Sound_Play(SID_ARMEND,"d",&sec->World_Offset); } } else { /* Moving! */ if (xenoStatusPointer->torso_whirr==SOUND_NOACTIVEINDEX) { Sound_Play(SID_ARMSTART,"d",&sec->World_Offset); Sound_Play(SID_ARMMID,"del",&sec->World_Offset,&xenoStatusPointer->torso_whirr); } else { Sound_Update3d(xenoStatusPointer->torso_whirr,&sec->World_Offset); } } } } void XenoborgHandleMovingAnimation(STRATEGYBLOCK *sbPtr) { XENO_STATUS_BLOCK *xenoStatusPointer; VECTORCH offset; int speed,animfactor; LOCALASSERT(sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(xenoStatusPointer); offset.vx=sbPtr->DynPtr->Position.vx-sbPtr->DynPtr->PrevPosition.vx; offset.vy=sbPtr->DynPtr->Position.vy-sbPtr->DynPtr->PrevPosition.vy; offset.vz=sbPtr->DynPtr->Position.vz-sbPtr->DynPtr->PrevPosition.vz; /* ...compute speed factor... */ speed=Magnitude(&offset); if (speed<(MUL_FIXED(NormalFrameTime,50))) { /* Not moving much, are we? Be stationary! */ if (ShowXenoStats) { PrintDebuggingText("Forced stationary animation!\n"); } EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Powered_Up_Standard,ONE_FIXED,(ONE_FIXED>>2)); return; } speed=DIV_FIXED(speed,NormalFrameTime); if (speed==0) { animfactor=ONE_FIXED; } else { animfactor=DIV_FIXED(625,speed); // Was 512! Difference to correct for rounding down... } GLOBALASSERT(animfactor>0); if (ShowXenoStats) { PrintDebuggingText("Anim Factor %d, Tweening %d\n",animfactor,xenoStatusPointer->HModelController.Tweening); } /* Start animation. */ EnforceXenoborgShapeAnimSequence_Core(sbPtr,HMSQT_Xenoborg,XBSS_Walking,XENO_WALKING_ANIM_SPEED,(ONE_FIXED>>2)); if (xenoStatusPointer->HModelController.Tweening==0) { HModel_SetToolsRelativeSpeed(&xenoStatusPointer->HModelController,animfactor); } } /*--------------------** ** Loading and Saving ** **--------------------*/ #include "savegame.h" typedef struct xenoborg_save_block { SAVE_BLOCK_STRATEGY_HEADER header; //behaviour block stuff signed int health; XENO_BHSTATE behaviourState; XENO_BHSTATE lastState; int stateTimer; NPC_WANDERDATA wanderData; NPC_OBSTRUCTIONREPORT obstruction; VECTORCH my_spot_therin; VECTORCH my_orientdir_therin; int module_range; int UpTime; int GibbFactor; int Wounds; VECTORCH targetTrackPos; int Head_Pan; int Head_Tilt; int Left_Arm_Pan; int Left_Arm_Tilt; int Right_Arm_Pan; int Right_Arm_Tilt; int Torso_Twist; int Old_Head_Pan; int Old_Head_Tilt; int Old_Left_Arm_Pan; int Old_Left_Arm_Tilt; int Old_Right_Arm_Pan; int Old_Right_Arm_Tilt; int Old_Torso_Twist; LASER_BEAM_DESC LeftMainBeam; LASER_BEAM_DESC RightMainBeam; LASER_BEAM_DESC TargetingLaser[3]; unsigned int headpandir :1; unsigned int headtiltdir :1; unsigned int leftarmpandir :1; unsigned int leftarmtiltdir :1; unsigned int rightarmpandir :1; unsigned int rightarmtiltdir :1; unsigned int torsotwistdir :1; unsigned int headLock :1; unsigned int leftArmLock :1; unsigned int rightArmLock :1; unsigned int targetSightTest :1; unsigned int IAmFar :1; unsigned int ShotThisFrame :1; unsigned int FiringLeft :1; unsigned int FiringRight :1; unsigned int UseHeadLaser :1; unsigned int UseLALaser :1; unsigned int UseRALaser :1; unsigned int HeadLaserOnTarget :1; unsigned int LALaserOnTarget :1; unsigned int RALaserOnTarget :1; unsigned int head_moving :1; unsigned int la_moving :1; unsigned int ra_moving :1; unsigned int torso_moving :1; int incidentFlag; int incidentTimer; int head_whirr; int left_arm_whirr; int right_arm_whirr; int torso_whirr; //annoying pointer related things int my_module_index; char Target_SBname[SB_NAME_LENGTH]; //strategyblock stuff int integrity; DAMAGEBLOCK SBDamageBlock; DYNAMICSBLOCK dynamics; }XENOBORG_SAVE_BLOCK; //defines for load/save macros #define SAVELOAD_BLOCK block #define SAVELOAD_BEHAV xenoStatusPointer void LoadStrategy_Xenoborg(SAVE_BLOCK_STRATEGY_HEADER* header) { int i; STRATEGYBLOCK* sbPtr; XENO_STATUS_BLOCK* xenoStatusPointer; XENOBORG_SAVE_BLOCK* block = (XENOBORG_SAVE_BLOCK*) header; //check the size of the save block if(header->size!=sizeof(*block)) return; //find the existing strategy block sbPtr = FindSBWithName(header->SBname); if(!sbPtr) return; //make sure the strategy found is of the right type if(sbPtr->I_SBtype != I_BehaviourXenoborg) return; xenoStatusPointer =(XENO_STATUS_BLOCK*) sbPtr->SBdataptr; //start copying stuff COPYELEMENT_LOAD(health) COPYELEMENT_LOAD(behaviourState) COPYELEMENT_LOAD(lastState) COPYELEMENT_LOAD(stateTimer) COPYELEMENT_LOAD(wanderData) COPYELEMENT_LOAD(obstruction) COPYELEMENT_LOAD(my_spot_therin) COPYELEMENT_LOAD(my_orientdir_therin) COPYELEMENT_LOAD(module_range) COPYELEMENT_LOAD(UpTime) COPYELEMENT_LOAD(GibbFactor) COPYELEMENT_LOAD(Wounds) COPYELEMENT_LOAD(targetTrackPos) COPYELEMENT_LOAD(Head_Pan) COPYELEMENT_LOAD(Head_Tilt) COPYELEMENT_LOAD(Left_Arm_Pan) COPYELEMENT_LOAD(Left_Arm_Tilt) COPYELEMENT_LOAD(Right_Arm_Pan) COPYELEMENT_LOAD(Right_Arm_Tilt) COPYELEMENT_LOAD(Torso_Twist) COPYELEMENT_LOAD(Old_Head_Pan) COPYELEMENT_LOAD(Old_Head_Tilt) COPYELEMENT_LOAD(Old_Left_Arm_Pan) COPYELEMENT_LOAD(Old_Left_Arm_Tilt) COPYELEMENT_LOAD(Old_Right_Arm_Pan) COPYELEMENT_LOAD(Old_Right_Arm_Tilt) COPYELEMENT_LOAD(Old_Torso_Twist) COPYELEMENT_LOAD(LeftMainBeam) COPYELEMENT_LOAD(RightMainBeam) COPYELEMENT_LOAD(headpandir) COPYELEMENT_LOAD(headtiltdir) COPYELEMENT_LOAD(leftarmpandir) COPYELEMENT_LOAD(leftarmtiltdir) COPYELEMENT_LOAD(rightarmpandir) COPYELEMENT_LOAD(rightarmtiltdir) COPYELEMENT_LOAD(torsotwistdir) COPYELEMENT_LOAD(headLock) COPYELEMENT_LOAD(leftArmLock) COPYELEMENT_LOAD(rightArmLock) COPYELEMENT_LOAD(targetSightTest) COPYELEMENT_LOAD(IAmFar) COPYELEMENT_LOAD(ShotThisFrame) COPYELEMENT_LOAD(FiringLeft) COPYELEMENT_LOAD(FiringRight) COPYELEMENT_LOAD(UseHeadLaser) COPYELEMENT_LOAD(UseLALaser) COPYELEMENT_LOAD(UseRALaser) COPYELEMENT_LOAD(HeadLaserOnTarget) COPYELEMENT_LOAD(LALaserOnTarget) COPYELEMENT_LOAD(RALaserOnTarget) COPYELEMENT_LOAD(head_moving) COPYELEMENT_LOAD(la_moving) COPYELEMENT_LOAD(ra_moving) COPYELEMENT_LOAD(torso_moving) COPYELEMENT_LOAD(incidentFlag) COPYELEMENT_LOAD(incidentTimer) COPYELEMENT_LOAD(head_whirr) COPYELEMENT_LOAD(left_arm_whirr) COPYELEMENT_LOAD(right_arm_whirr) COPYELEMENT_LOAD(torso_whirr) for(i=0;i<3;i++) { COPYELEMENT_LOAD(TargetingLaser[i]) } //load ai module pointers xenoStatusPointer->my_module = GetPointerFromAIModuleIndex(block->my_module_index); //load target COPY_NAME(xenoStatusPointer->Target_SBname,block->Target_SBname); xenoStatusPointer->Target = FindSBWithName(xenoStatusPointer->Target_SBname); //copy strategy block stuff *sbPtr->DynPtr = block->dynamics; sbPtr->integrity = block->integrity; sbPtr->SBDamageBlock = block->SBDamageBlock; //load hierarchy { SAVE_BLOCK_HEADER* hier_header = GetNextBlockIfOfType(SaveBlock_Hierarchy); if(hier_header) { LoadHierarchy(hier_header,&xenoStatusPointer->HModelController); } } //finally get the delta controller pointers VerifyDeltaControllers(sbPtr); Load_SoundState(&xenoStatusPointer->soundHandle1); Load_SoundState(&xenoStatusPointer->soundHandle2); } void SaveStrategy_Xenoborg(STRATEGYBLOCK* sbPtr) { int i; XENO_STATUS_BLOCK* xenoStatusPointer; XENOBORG_SAVE_BLOCK* block; GET_STRATEGY_SAVE_BLOCK(XENOBORG_SAVE_BLOCK,block,sbPtr); xenoStatusPointer = (XENO_STATUS_BLOCK*) sbPtr->SBdataptr; //start copying stuff COPYELEMENT_SAVE(health) COPYELEMENT_SAVE(behaviourState) COPYELEMENT_SAVE(lastState) COPYELEMENT_SAVE(stateTimer) COPYELEMENT_SAVE(wanderData) COPYELEMENT_SAVE(obstruction) COPYELEMENT_SAVE(my_spot_therin) COPYELEMENT_SAVE(my_orientdir_therin) COPYELEMENT_SAVE(module_range) COPYELEMENT_SAVE(UpTime) COPYELEMENT_SAVE(GibbFactor) COPYELEMENT_SAVE(Wounds) COPYELEMENT_SAVE(targetTrackPos) COPYELEMENT_SAVE(Head_Pan) COPYELEMENT_SAVE(Head_Tilt) COPYELEMENT_SAVE(Left_Arm_Pan) COPYELEMENT_SAVE(Left_Arm_Tilt) COPYELEMENT_SAVE(Right_Arm_Pan) COPYELEMENT_SAVE(Right_Arm_Tilt) COPYELEMENT_SAVE(Torso_Twist) COPYELEMENT_SAVE(Old_Head_Pan) COPYELEMENT_SAVE(Old_Head_Tilt) COPYELEMENT_SAVE(Old_Left_Arm_Pan) COPYELEMENT_SAVE(Old_Left_Arm_Tilt) COPYELEMENT_SAVE(Old_Right_Arm_Pan) COPYELEMENT_SAVE(Old_Right_Arm_Tilt) COPYELEMENT_SAVE(Old_Torso_Twist) COPYELEMENT_SAVE(LeftMainBeam) COPYELEMENT_SAVE(RightMainBeam) COPYELEMENT_SAVE(headpandir) COPYELEMENT_SAVE(headtiltdir) COPYELEMENT_SAVE(leftarmpandir) COPYELEMENT_SAVE(leftarmtiltdir) COPYELEMENT_SAVE(rightarmpandir) COPYELEMENT_SAVE(rightarmtiltdir) COPYELEMENT_SAVE(torsotwistdir) COPYELEMENT_SAVE(headLock) COPYELEMENT_SAVE(leftArmLock) COPYELEMENT_SAVE(rightArmLock) COPYELEMENT_SAVE(targetSightTest) COPYELEMENT_SAVE(IAmFar) COPYELEMENT_SAVE(ShotThisFrame) COPYELEMENT_SAVE(FiringLeft) COPYELEMENT_SAVE(FiringRight) COPYELEMENT_SAVE(UseHeadLaser) COPYELEMENT_SAVE(UseLALaser) COPYELEMENT_SAVE(UseRALaser) COPYELEMENT_SAVE(HeadLaserOnTarget) COPYELEMENT_SAVE(LALaserOnTarget) COPYELEMENT_SAVE(RALaserOnTarget) COPYELEMENT_SAVE(head_moving) COPYELEMENT_SAVE(la_moving) COPYELEMENT_SAVE(ra_moving) COPYELEMENT_SAVE(torso_moving) COPYELEMENT_SAVE(incidentFlag) COPYELEMENT_SAVE(incidentTimer) COPYELEMENT_SAVE(head_whirr) COPYELEMENT_SAVE(left_arm_whirr) COPYELEMENT_SAVE(right_arm_whirr) COPYELEMENT_SAVE(torso_whirr) for(i=0;i<3;i++) { COPYELEMENT_SAVE(TargetingLaser[i]) } //load ai module pointers block->my_module_index = GetIndexFromAIModulePointer(xenoStatusPointer->my_module); //save target COPY_NAME(block->Target_SBname,xenoStatusPointer->Target_SBname); //save strategy block stuff block->dynamics = *sbPtr->DynPtr; block->dynamics.CollisionReportPtr=0; block->integrity = sbPtr->integrity; block->SBDamageBlock = sbPtr->SBDamageBlock; //save the hierarchy SaveHierarchy(&xenoStatusPointer->HModelController); Save_SoundState(&xenoStatusPointer->soundHandle1); Save_SoundState(&xenoStatusPointer->soundHandle2); }
28.043183
166
0.752806
Melanikus
4e6220cfa508875e63e5e6140234b91f352abe56
789
cpp
C++
core/connections/wim/permit_info.cpp
ERPShuen/ICQ1
f319a72ad60aae4809eef0e4eb362f4d69292296
[ "Apache-2.0" ]
1
2019-12-02T08:37:10.000Z
2019-12-02T08:37:10.000Z
core/connections/wim/permit_info.cpp
ERPShuen/ICQ1
f319a72ad60aae4809eef0e4eb362f4d69292296
[ "Apache-2.0" ]
null
null
null
core/connections/wim/permit_info.cpp
ERPShuen/ICQ1
f319a72ad60aae4809eef0e4eb362f4d69292296
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #include "permit_info.h" #include "wim_packet.h" using namespace core; using namespace wim; permit_info::permit_info() { } permit_info::~permit_info() { } int32_t permit_info::parse_response_data(const rapidjson::Value& _node_results) { auto ignores = _node_results.FindMember("ignores"); if (ignores == _node_results.MemberEnd() || !ignores->value.IsArray()) return wpie_http_parse_response; ignore_aimid_list_.reserve(ignores->value.Size()); for (auto iter = ignores->value.Begin(); iter != ignores->value.End(); ++iter) { std::string aimid = iter->GetString(); ignore_aimid_list_.emplace(aimid); } return 0; } const ignorelist_cache& permit_info::get_ignore_list() const { return ignore_aimid_list_; }
21.324324
82
0.69962
ERPShuen
4e69635cdd132fd4b2df0caf51a98f1148ed9c3c
421
cpp
C++
c_plus_plus/white_belt/week3/incognizable.cpp
raventid/coursera_learning
115a03f08d30d8ba49f02c9692c289cbfb242358
[ "MIT" ]
1
2019-11-28T09:26:00.000Z
2019-11-28T09:26:00.000Z
c_plus_plus/white_belt/week3/incognizable.cpp
raventid/coursera_learning
115a03f08d30d8ba49f02c9692c289cbfb242358
[ "MIT" ]
null
null
null
c_plus_plus/white_belt/week3/incognizable.cpp
raventid/coursera_learning
115a03f08d30d8ba49f02c9692c289cbfb242358
[ "MIT" ]
null
null
null
class Incognizable { public: Incognizable() { } Incognizable(int a) { } Incognizable(int a, int b) { } }; // The best solution to just make main compile is this one: // struct Incognizable { // int x = 0; // int y = 0; // }; // int main() { // Incognizable a; // Incognizable b = {}; // Incognizable c = {0}; // Incognizable d = {0, 1}; // return 0; // } acbd acbd acbdced abcedabcedf
11.694444
59
0.567696
raventid
4e6c2ba5b251c48712f88c5a41221ba4dc8f3212
781
hpp
C++
thread_pool/thread_pool_interface.hpp
arjangupta/CPP_Diary
3ed1f8b3a32e2ea238aa4df926e97d5fb885cdbc
[ "Unlicense" ]
null
null
null
thread_pool/thread_pool_interface.hpp
arjangupta/CPP_Diary
3ed1f8b3a32e2ea238aa4df926e97d5fb885cdbc
[ "Unlicense" ]
3
2018-01-24T17:19:40.000Z
2018-09-07T19:57:42.000Z
thread_pool/thread_pool_interface.hpp
arjangupta/CPP_Diary
3ed1f8b3a32e2ea238aa4df926e97d5fb885cdbc
[ "Unlicense" ]
null
null
null
#ifndef _THREAD_POOL_INTERFACE_HPP_ #define _THREAD_POOL_INTERFACE_HPP_ #include "ThreadPool/ThreadPool.h" namespace thread_pool_example { class GenericThreadUser; typedef void (GenericThreadUser::*generic_thread_user_function_ptr_t)(); class SpecificThreadUser; typedef void (SpecificThreadUser::*specific_thread_user_function_ptr_t)(); class ThreadPoolInterface final { public: ThreadPoolInterface() = delete; ThreadPoolInterface(int); ~ThreadPoolInterface(); void sendGenericThreadUserJob(GenericThreadUser*, generic_thread_user_function_ptr_t); void sendSpecificThreadUserJob(SpecificThreadUser*, specific_thread_user_function_ptr_t); private: ::ThreadPool _thread_pool; }; } // namespace thread_pool_example #endif // _THREAD_POOL_INTERFACE_HPP_
26.931034
93
0.824584
arjangupta
4e6f950bf3bd939285fa33b1c1a95a39beb21b07
487
hpp
C++
src/PixelFPSDemo2/Collider.hpp
zmcj1/PixelFPS
2957fe7cdaf0e269665f2e3a7adcccc7e44c5799
[ "MIT" ]
1
2022-02-08T06:26:32.000Z
2022-02-08T06:26:32.000Z
src/PixelFPSDemo2/Collider.hpp
zmcj1/PixelFPS
2957fe7cdaf0e269665f2e3a7adcccc7e44c5799
[ "MIT" ]
null
null
null
src/PixelFPSDemo2/Collider.hpp
zmcj1/PixelFPS
2957fe7cdaf0e269665f2e3a7adcccc7e44c5799
[ "MIT" ]
null
null
null
#pragma once #include "Component.hpp" #include "olcPixelGameEngine.h" using namespace olc; class Collider : public Component { CLASS_DECLARATION(Collider) public: Collider() : Component() { } //碰撞半径 Collision radius of object float radius = 0.5f; //是否与其他Collider发生碰撞 bool collideWithObjects = false; //是否与墙面发生碰撞 bool collideWithScenery = false; //是否可以被其他碰撞体移动 bool canBeMoved = false; //是否是触发器: bool isTrigger = false; };
15.709677
37
0.665298
zmcj1
4e77b18620853c407ca226c8f7c819b9e3dbf702
2,944
cpp
C++
CS535_Assign 1/CS535_Assign 1/FrameBuffer.cpp
HarryPyc/Purdue_CS535_Assigns
4ab5a039cb0c73dd5d271f20a2850cb1cc51af20
[ "MIT" ]
null
null
null
CS535_Assign 1/CS535_Assign 1/FrameBuffer.cpp
HarryPyc/Purdue_CS535_Assigns
4ab5a039cb0c73dd5d271f20a2850cb1cc51af20
[ "MIT" ]
null
null
null
CS535_Assign 1/CS535_Assign 1/FrameBuffer.cpp
HarryPyc/Purdue_CS535_Assigns
4ab5a039cb0c73dd5d271f20a2850cb1cc51af20
[ "MIT" ]
null
null
null
#include "FrameBuffer.h" #include <libtiff/tiffio.h> #include <omp.h> FrameBuffer::FrameBuffer(int _width, int _height) { w = _width; h = _height; pixels = new unsigned int[w * h]; Clear(fvec4(0.f, 0.f, 0.f, 0.f)); } void FrameBuffer::Clear(fvec4 color) { const uint c = convVec4ToRGBA8(color); #ifdef MULTI_PROCESS #pragma omp parallel for #endif for (int i = 0; i < w * h; i++) *(pixels + i) = c; } void FrameBuffer::SetPixel(int x, int y, fvec4 color) { const int index = y*w + x; if (x < 0 || y < 0 || x >= w || y >= h) { //cout << "Index out of range of Pixels" << endl; return; } *(pixels + index) = convVec4ToRGBA8(color); } void FrameBuffer::Draw2DSegements(float a[2], float b[2], fvec4 color) { float Dx = fabsf(a[0] - b[0]), Dy = fabsf(a[1] - b[1]); const int steps = int(Dx > Dy ? Dx : Dy) + 1; #ifdef MULTI_PROCESS #pragma omp parallel for #endif for (int i = 0; i <= steps; i++) { float x = a[0] + (b[0] - a[0]) / float(steps) * float(i); float y = a[1] + (b[1] - a[1]) / float(steps) * float(i); SetPixel(int(x), int(y), color); } } void FrameBuffer::DrawMesh(Camera* cam, Mesh* mesh) { const int n = mesh->GetSize(); vector<float[2]> Vertices = vector<float[2]>(n); #ifdef MULTI_PROCESS #pragma omp parallel for #endif for (int i = 0; i < n; i++) { fvec4 screenVert = cam->P * cam->V * mesh->T * mesh->R * mesh->S * mesh->GetVertex(i); //Perspective devision screenVert = screenVert / screenVert.w; Vertices[i][0] = (screenVert.x + 1.f) / 2.f * w; Vertices[i][1] = (screenVert.y + 1.f) / 2.f * h; } for (int i = 0; i < n - 1; i++) { Draw2DSegements(Vertices[i], Vertices[i + 1], mesh->material.color); } glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels); } void FrameBuffer::LoadTiff(const char* fname) { TIFF* in = TIFFOpen(fname, "r"); if (in == NULL) { cerr << fname << " could not be opened" << endl; return; } int width, height; TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width); TIFFGetField(in, TIFFTAG_IMAGELENGTH, &height); if (w != width || h != height) { w = width; h = height; delete[] pixels; pixels = new unsigned int[w * h]; glFlush(); } if (TIFFReadRGBAImage(in, w, h, pixels, 0) == 0) { cerr << "failed to load " << fname << endl; } TIFFClose(in); } void FrameBuffer::SaveAsTiff(const char* fname) { TIFF* out = TIFFOpen(fname, "w"); if (out == NULL) { cerr << fname << " could not be opened" << endl; return; } TIFFSetField(out, TIFFTAG_IMAGEWIDTH, w); TIFFSetField(out, TIFFTAG_IMAGELENGTH, h); TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 4); TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 8); TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT); TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); for (uint32 row = 0; row < (unsigned int)h; row++) { TIFFWriteScanline(out, &pixels[(h - row - 1) * w], row); } TIFFClose(out); }
24.739496
88
0.632473
HarryPyc
4e77ebdccaf9d89c7bee36650e2800479ce6ab94
566
hpp
C++
engine/event/include/universe/engine/event/sdl_custom_event.hpp
insufficientchocolate/MyUniverse
d0fe18c23bdabfe0815c9297239df702dd9a55a3
[ "MIT" ]
1
2019-02-12T07:43:06.000Z
2019-02-12T07:43:06.000Z
engine/event/include/universe/engine/event/sdl_custom_event.hpp
insufficientchocolate/MyUniverse
d0fe18c23bdabfe0815c9297239df702dd9a55a3
[ "MIT" ]
null
null
null
engine/event/include/universe/engine/event/sdl_custom_event.hpp
insufficientchocolate/MyUniverse
d0fe18c23bdabfe0815c9297239df702dd9a55a3
[ "MIT" ]
null
null
null
#ifndef _UNIVERSE_EVENT_SDL_CUSTOM_EVENT_H_ #define _UNIVERSE_EVENT_SDL_CUSTOM_EVENT_H_ #include "event.hpp" #include "sdl_custom_event_type_assigner.hpp" namespace Universe::Event { template <class D, class Assigner = SDLCustomEventTypeAssigner> class SDLCustomEvent : public Event<Uint32> { public: Uint32 getType() const { return D::getSDLType(); } static Uint32 getSDLType() { static Assigner* eventType; if (eventType == nullptr) { eventType = new Assigner(); } return eventType->type; }; }; }; // namespace Universe::Event #endif
28.3
63
0.738516
insufficientchocolate
4e7a58d3f78cb89bcf33079885e6f284a9bd6cb2
129
cc
C++
Pods/FirebaseFirestore/Firestore/core/src/firebase/firestore/remote/grpc_streaming_reader.cc
MrsTrier/RememberArt
90314d1f05a1d63b9885ebb17d37bab5134a24f3
[ "MIT" ]
null
null
null
Pods/FirebaseFirestore/Firestore/core/src/firebase/firestore/remote/grpc_streaming_reader.cc
MrsTrier/RememberArt
90314d1f05a1d63b9885ebb17d37bab5134a24f3
[ "MIT" ]
null
null
null
Pods/FirebaseFirestore/Firestore/core/src/firebase/firestore/remote/grpc_streaming_reader.cc
MrsTrier/RememberArt
90314d1f05a1d63b9885ebb17d37bab5134a24f3
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:b7589849e7cd9f7325a0650ff6ab730096f145a859a86f30438486b77fcf91e1 size 2795
32.25
75
0.883721
MrsTrier
4e7d7624abab5b6e320104a752250f27d9be4ea9
22,754
cpp
C++
src/engine/primitive/primitivemanager.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
2
2019-06-22T23:29:44.000Z
2019-07-07T18:34:04.000Z
src/engine/primitive/primitivemanager.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
src/engine/primitive/primitivemanager.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
/** * @file primitivemanager.cpp * @brief * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) * @date 2001-12-25 * @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved. * @details */ #include "o3d/engine/precompiled.h" #include "o3d/engine/primitive/primitivemanager.h" #include "o3d/engine/object/geometrydata.h" #include "o3d/engine/shader/shadermanager.h" #include "o3d/engine/scene/scene.h" #include "o3d/engine/context.h" #include "o3d/engine/drawinfo.h" #include "o3d/engine/primitive/cube.h" #include "o3d/engine/primitive/sphere.h" #include "o3d/engine/primitive/cylinder.h" using namespace o3d; O3D_IMPLEMENT_DYNAMIC_CLASS1(PrimitiveManager, ENGINE_PRIMITIVE_MANAGER, SceneEntity) // Default constructor. PrimitiveAccess::PrimitiveAccess(PrimitiveManager *manager, const DrawInfo &drawInfo) : m_manager(manager) { O3D_ASSERT(manager); m_manager->bind(drawInfo); } // Destructor. PrimitiveAccess::~PrimitiveAccess() { m_manager->unbind(); } // Default constructor. PrimitiveManager::PrimitiveManager(BaseObject *parent) : SceneEntity(parent), m_pickableId(0), m_numUsage(0), m_vertices(1024*3, 1024*3), m_colors(1024*4, 1024*4), m_verticesVbo(getScene()->getContext()), m_colorsVbo(getScene()->getContext()), m_quadVertices(getScene()->getContext()), m_quadTexCoords(getScene()->getContext()), m_quadColors(getScene()->getContext()) { m_primitives.resize(SOLID_CUBE1+1); // @todo remplacer avec des VBO plus globaux createPrimitive(WIRE_CYLINDER1, new Cylinder(1.f, 1.f, 1.f, 12, 1, Primitive::WIRED_MODE)); createPrimitive(WIRE_CYLINDER2, new Cylinder(1.f, 1.f, 1.f, 8, 1, Primitive::WIRED_MODE)); createPrimitive(SOLID_CYLINDER1, new Cylinder(1.f, 1.f, 1.f, 8, 1, Primitive::FILLED_MODE)); createPrimitive(WIRE_CONE1, new Cylinder(1.f, 0.f, 1.f, 8, 1, Primitive::WIRED_MODE)); createPrimitive(SOLID_CONE1, new Cylinder(1.f, 0.f, 1.f, 12, 1, Primitive::FILLED_MODE)); createPrimitive(WIRE_SPHERE1, new Sphere(1.f, 12, 8, Primitive::WIRED_MODE)); createPrimitive(WIRE_SPHERE2, new Sphere(1.f, 8, 6, Primitive::WIRED_MODE)); createPrimitive(SOLID_SPHERE1, new Sphere(1.f, 12, 8, Primitive::FILLED_MODE)); createPrimitive(WIRE_CUBE1, new Cube(1.f, 0, Cube::GRID_CUBE/*WIRED_MODE*/)); createPrimitive(SOLID_CUBE1, new Cube(1.f, 0, Primitive::FILLED_MODE)); // // create a simple uniform color shader // Shader *shader = getScene()->getShaderManager()->addShader("primitiveShader"); shader->buildInstance(m_colorShader.instance); m_colorShader.instance.assign("vertexColor", "vertexColor", "", Shader::BUILD_COMPILE_AND_LINK); m_colorShader.u_modelViewProjectionMatrix = m_colorShader.instance.getUniformLocation("u_modelViewProjectionMatrix"); m_colorShader.u_color = m_colorShader.instance.getUniformLocation("u_color"); m_colorShader.u_scale = m_colorShader.instance.getUniformLocation("u_scale"); m_colorShader.a_vertex = m_colorShader.instance.getAttributeLocation("a_vertex"); m_colorShader.a_color = m_colorShader.instance.getAttributeLocation("a_color"); if (!m_colorShader.instance.isOperational()) { O3D_ERROR(E_InvalidResult("Primitive rendering color shader is not operational")); } // // and a simple shader for the picking mode // shader = getScene()->getShaderManager()->addShader("primitiveShader"); shader->buildInstance(m_pickingShader.instance); m_pickingShader.instance.assign("vertexPicking", "vertexPicking", "", Shader::BUILD_COMPILE_AND_LINK); m_pickingShader.u_modelViewProjectionMatrix = m_pickingShader.instance.getUniformLocation("u_modelViewProjectionMatrix"); m_pickingShader.u_picking = m_pickingShader.instance.getUniformLocation("u_picking"); m_pickingShader.u_scale = m_pickingShader.instance.getUniformLocation("u_scale"); m_pickingShader.a_vertex = m_pickingShader.instance.getAttributeLocation("a_vertex"); // m_pickingShader.a_picking = m_pickingShader.instance.getAttributeLocation("a_picking"); if (!m_pickingShader.instance.isOperational()) { O3D_ERROR(E_InvalidResult("Primitive rendering picking shader is not operational")); } // // setup the vertex data // m_verticesVbo.create(1024*3, VertexBuffer::STREAMED); m_colorsVbo.create(1024*4, VertexBuffer::STREAMED); m_objects.resize(XYZ_AXIS_LINES+1); // Y axis aligned quad { const Float vertices[] = { 0,0,0, 0,0,1, 1,0,1, 1,0,0 }; const Float colors[] = { 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, }; Object *object = new Object(getScene()->getContext()); object->format = P_POINTS; object->vertices.create(4*3, VertexBuffer::STATIC, vertices); object->colors.create(4*4, VertexBuffer::STATIC, colors); m_objects[Y_AXIS_ALIGNED_QUAD] = object; } // AXIS lines { const Float vertices[] = { 0,0,0, 1,0,0, 0,0,0, 0,1,0, 0,0,0, 0,0,1 }; const Float colors[] = { 1,0,0,1, 1,0,0,1, 0,0.6,0,1, 0,0.6,0,1, 0,0,1,1, 0,0,1,1 }; Object *object = new Object(getScene()->getContext()); object->format = P_LINES; object->vertices.create(6*3, VertexBuffer::STATIC, vertices); object->colors.create(6*4, VertexBuffer::STATIC, colors); m_objects[XYZ_AXIS_LINES] = object; } { const Float vertices[12] = { 1, -1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0 }; const Float texCoords[8] = { 1.f, 0.f, 0.0f, 0.f, 1.f, 1.f, 0.f, 1.f }; const Float colors[12] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; m_quadVertices.create(12, VertexBuffer::STATIC, vertices); m_quadTexCoords.create(8, VertexBuffer::STATIC, texCoords); m_quadColors.create(12, VertexBuffer::STATIC, colors); } } // Virtual destructor. PrimitiveManager::~PrimitiveManager() { // delete primitives for (IT_GeometryVector it = m_primitives.begin(); it != m_primitives.end(); ++it) { deletePtr(*it); } // delete objects for (IT_ObjectVector it = m_objects.begin(); it != m_objects.end(); ++it) { deletePtr(*it); } // delete registered objects for (IT_ObjectVector it = m_registeredObjects.begin(); it != m_registeredObjects.end(); ++it) { deletePtr(*it); } } // Setup before draw any primitives. void PrimitiveManager::bind(const DrawInfo &drawInfo) { if (drawInfo.pass == DrawInfo::AMBIENT_PASS) { if (m_pickingShader.instance.isInUse()) { O3D_ERROR(E_InvalidOperation("Inconsistency of binding draw mode")); } // bind the shader if (!m_colorShader.instance.isInUse()) { getScene()->getContext()->simpleDrawMode(); m_colorShader.instance.bindShader(); getScene()->getContext()->bindDefaultVertexArray(); getScene()->getContext()->enableVertexAttribArray(m_colorShader.a_vertex); getScene()->getContext()->enableVertexAttribArray(m_colorShader.a_color); } } else if (drawInfo.pass == DrawInfo::PICKING_PASS) { if (m_colorShader.instance.isInUse()) { O3D_ERROR(E_InvalidOperation("Inconsistency of binding draw mode")); } // bind the shader if (!m_pickingShader.instance.isInUse()) { getScene()->getContext()->simpleDrawMode(); m_pickingShader.instance.bindShader(); getScene()->getContext()->bindDefaultVertexArray(); getScene()->getContext()->enableVertexAttribArray(m_pickingShader.a_vertex); } } ++m_numUsage; } // Always restore after draw. void PrimitiveManager::unbind() { if (m_numUsage <= 0) { O3D_ERROR(E_InvalidOperation("Attempt to unbind the primitive manager whereas it was not previously bound")); } // unbound the shader if (m_numUsage == 1) { if (m_colorShader.instance.isInUse()) { getScene()->getContext()->normalDrawMode(); getScene()->getContext()->disableVertexAttribArray(m_colorShader.a_vertex); getScene()->getContext()->disableVertexAttribArray(m_colorShader.a_color); m_colorShader.instance.unbindShader(); } else if (m_pickingShader.instance.isInUse()) { getScene()->getContext()->normalDrawMode(); getScene()->getContext()->disableVertexAttribArray(m_pickingShader.a_vertex); // getScene()->getContext()->disableVertexAttribArray(m_pickingShader.a_picking); m_pickingShader.instance.unbindShader(); } } --m_numUsage; } void PrimitiveManager::createPrimitive(PrimitiveManager::Primitives type, Primitive *primitive) { GeometryData *geometry = new GeometryData(this, *primitive); SmartArrayFloat colorArray(primitive->getNumVertices()*4); for (UInt32 i = 0; i < colorArray.getNumElt(); ++i) { colorArray.getData()[i] = 1.0f; } geometry->createElement(V_COLOR_ARRAY, colorArray); geometry->create(); geometry->bindFaceArray(0); m_primitives[type] = geometry; delete primitive; } // Register a user object. UInt32 PrimitiveManager::registerObject( PrimitiveFormat format, const ArrayFloat &vertices, const ArrayFloat &colors) { Object *object = new Object(getScene()->getContext()); object->format = format; object->vertices.create(vertices.getSize(), VertexBuffer::STATIC, vertices.getData()); object->colors.create(colors.getSize(), VertexBuffer::STATIC, colors.getData()); m_registeredObjects.push_back(object); return m_registeredObjects.size() - 1; } // Set the color to use to draw. void PrimitiveManager::setColor(Float r, Float g, Float b, Float a) { m_color.set(r,g,b,a); if (m_colorShader.instance.isInUse()) { m_colorShader.instance.setConstColor(m_colorShader.u_color, m_color); } } void PrimitiveManager::setColor(const Color &color) { m_color = color; if (m_colorShader.instance.isInUse()) { m_colorShader.instance.setConstColor(m_colorShader.u_color, m_color); } } void PrimitiveManager::setPickableId(UInt32 id) { m_pickableId = id; if (m_pickingShader.instance.isInUse()) { m_pickingShader.instance.setConstUInt(m_pickingShader.u_picking, m_pickableId); } } // Define the modelview*projection matrix using the GLContext current projection*modelview. void PrimitiveManager::setModelviewProjection() { if (m_colorShader.instance.isInUse()) { m_colorShader.instance.setConstMatrix4( m_colorShader.u_modelViewProjectionMatrix, False, getScene()->getContext()->modelViewProjection()); } else if (m_pickingShader.instance.isInUse()) { m_pickingShader.instance.setConstMatrix4( m_pickingShader.u_modelViewProjectionMatrix, False, getScene()->getContext()->modelViewProjection()); } } // Define the modelview*projection matrix before draw. void PrimitiveManager::setModelviewProjection(const Matrix4 &matrix) { if (m_colorShader.instance.isInUse()) { m_colorShader.instance.setConstMatrix4( m_colorShader.u_modelViewProjectionMatrix, False, matrix); } else if (m_pickingShader.instance.isInUse()) { m_pickingShader.instance.setConstMatrix4( m_pickingShader.u_modelViewProjectionMatrix, False, matrix); } } // Draw the triplet of local axis void PrimitiveManager::drawLocalAxis() { Context *glContext = getScene()->getContext(); setModelviewProjection(); if (m_colorShader.instance.isInUse()) { setColor(1.0f, 1.0f, 1.0f); drawXYZAxis(Vector3(1,1,1)); // return; // Matrix4 x(glContext->modelView().get()),y,z; // Matrix4 m; // m.Translate(0.8, 0, 0); // x *= m; // m.Identity(); m.RotateZ(o3d::toRadian(-90.f)); // x *= m; glContext->modelView().push(); //glContext->ModelView().set(x); glContext->modelView().translate(Vector3(0.8f, 0, 0)); glContext->modelView().rotateZ(o3d::toRadian(-90.f)); setColor(0.8f, 0.f, 0.f); draw(SOLID_CONE1, Vector3(0.1f, 0.2f, 0.1f)); glContext->modelView().pop(); glContext->modelView().push(); glContext->modelView().translate(Vector3(0, 0.8f, 0)); setColor(0.f, 0.6f, 0.f); draw(SOLID_CONE1, Vector3(0.1f,0.2f,0.1f)); glContext->modelView().pop(); glContext->modelView().push(); glContext->modelView().translate(Vector3(0, 0, 0.8f)); glContext->modelView().rotateX(o3d::toRadian(90.f)); setColor(0.f, 0.f, 0.6f); draw(SOLID_CONE1, Vector3(0.1f, 0.2f, 0.1f)); glContext->modelView().pop(); } else if (m_pickingShader.instance.isInUse()) { drawXYZAxis(Vector3(1,1,1)); glContext->modelView().push(); glContext->modelView().translate(Vector3(0.8f, 0, 0)); glContext->modelView().rotateZ(o3d::toRadian(-90.f)); draw(SOLID_CONE1, Vector3(0.1f, 0.2f, 0.1f)); glContext->modelView().pop(); glContext->modelView().push(); glContext->modelView().translate(Vector3(0, 0.8f, 0)); draw(SOLID_CONE1, Vector3(0.1f, 0.2f, 0.1f)); glContext->modelView().pop(); glContext->modelView().push(); glContext->modelView().translate(Vector3(0, 0, 0.8f)); glContext->modelView().rotateX(o3d::toRadian(90.f)); draw(SOLID_CONE1, Vector3(0.1f, 0.2f, 0.1f)); glContext->modelView().pop(); } } // Draw a wire bounding box void PrimitiveManager::boundingBox(const AABBox &bbox, const Color &color) { if (m_colorShader.instance.isInUse()) { setColor(color); } Context *glContext = getScene()->getContext(); glContext->modelView().push(); glContext->modelView().translate(bbox.getCenter()); draw(WIRE_CUBE1, bbox.getHalfSize() * 2.0f); glContext->modelView().pop(); } // Draw a wire bounding box extended void PrimitiveManager::boundingBox(const AABBoxExt &bbox, const Color &color) { if (m_colorShader.instance.isInUse()) { setColor(color); } Context *glContext = getScene()->getContext(); glContext->modelView().push(); glContext->modelView().translate(bbox.getCenter()); draw(WIRE_CUBE1, bbox.getHalfSize() * 2.0f); glContext->modelView().pop(); glContext->modelView().push(); glContext->modelView().translate(bbox.getCenter()); draw(WIRE_SPHERE2, Vector3(bbox.getRadius(),bbox.getRadius(),bbox.getRadius())); glContext->modelView().pop(); } // Draw a wire bounding sphere void PrimitiveManager::boundingSphere(const BSphere &bsphere, const Color &color) { if (m_colorShader.instance.isInUse()) { setColor(color); } Context *glContext = getScene()->getContext(); glContext->modelView().push(); glContext->modelView().translate(bsphere.getCenter()); draw(WIRE_SPHERE2, Vector3(bsphere.getRadius(),bsphere.getRadius(),bsphere.getRadius())); glContext->modelView().pop(); } // Draw an Y axis aligned quad. void PrimitiveManager::drawYAxisAlignedQuad(PrimitiveFormat format, const Vector3 &scale) { Object *object = m_objects[Y_AXIS_ALIGNED_QUAD]; drawArray(format, object->vertices, object->colors, scale); } // Draw an XYZ axis lines. void PrimitiveManager::drawXYZAxis(const Vector3 &scale) { Object *object = m_objects[XYZ_AXIS_LINES]; drawArray(P_LINES, object->vertices, object->colors, scale); } // Draw an object. void PrimitiveManager::drawObject(UInt32 objectId, const Vector3 &scale) { if (objectId >= m_registeredObjects.size()) { O3D_ERROR(E_InvalidParameter("Unregistered object identifier")); } Object *object = m_registeredObjects[objectId]; if (!object) { O3D_ERROR(E_InvalidParameter("Null object")); } drawArray(object->format, object->vertices, object->colors, scale); } void PrimitiveManager::setScale(const Vector3 &scale) { if (m_colorShader.instance.isInUse()) { m_colorShader.instance.setConstVector3(m_colorShader.u_scale, scale); } else if (m_pickingShader.instance.isInUse()) { m_pickingShader.instance.setConstVector3(m_pickingShader.u_scale, scale); } } // Access to the ModelView matrix. ModelViewMatrix& PrimitiveManager::modelView() { return getScene()->getContext()->modelView(); } // Access to the ModelView matrix (read only). const ModelViewMatrix& PrimitiveManager::modelView() const { return getScene()->getContext()->modelView(); } // Access to the Projection matrix. ProjectionMatrix& PrimitiveManager::projection() { return getScene()->getContext()->projection(); } // Access to the Projection matrix (read only). const ProjectionMatrix& PrimitiveManager::projection() const { return getScene()->getContext()->projection(); } void PrimitiveManager::draw(PrimitiveManager::Primitives type, const Vector3 &scale) { GeometryData *geometry = m_primitives[type]; setModelviewProjection(); if (m_colorShader.instance.isInUse()) { m_colorShader.instance.setConstVector3(m_colorShader.u_scale, scale); geometry->attribute(V_VERTICES_ARRAY, m_colorShader.a_vertex); geometry->attribute(V_COLOR_ARRAY, m_colorShader.a_color); geometry->draw(); getScene()->getContext()->disableVertexAttribArray(m_colorShader.a_vertex); getScene()->getContext()->disableVertexAttribArray(m_colorShader.a_color); } else if (m_pickingShader.instance.isInUse()) { m_pickingShader.instance.setConstVector3(m_pickingShader.u_scale, scale); geometry->attribute(V_VERTICES_ARRAY, m_pickingShader.a_vertex); geometry->draw(); getScene()->getContext()->disableVertexAttribArray(m_pickingShader.a_vertex); } } // Draw a set of VBO (need vertex(XYZ) and color(RGBA). void PrimitiveManager::drawArray( PrimitiveFormat format, const ArrayBufferf &vertices, const ArrayBufferf &colors, const Vector3 &scale) { if (m_colorShader.instance.isInUse()) { m_colorShader.instance.setConstVector3(m_colorShader.u_scale, scale); // vertices vertices.bindBuffer(); getScene()->getContext()->vertexAttribArray(m_colorShader.a_vertex, 3, 0, 0); // colors colors.bindBuffer(); getScene()->getContext()->vertexAttribArray(m_colorShader.a_color, 4, 0, 0); // and draw getScene()->drawArrays(format, 0, vertices.getCount() / 3); getScene()->getContext()->disableVertexAttribArray(m_colorShader.a_vertex); getScene()->getContext()->disableVertexAttribArray(m_colorShader.a_color); } else if (m_pickingShader.instance.isInUse()) { m_pickingShader.instance.setConstVector3(m_pickingShader.u_scale, scale); // vertices vertices.bindBuffer(); getScene()->getContext()->vertexAttribArray(m_pickingShader.a_vertex, 3, 0, 0); // and draw getScene()->drawArrays(format, 0, vertices.getCount() / 3); getScene()->getContext()->disableVertexAttribArray(m_pickingShader.a_vertex); } } // Start a draw list. void PrimitiveManager::beginDraw(PrimitiveFormat format) { m_format = format; m_vertices.forceSize(0); m_colors.forceSize(0); } // End a draw list, called after using BeginDraw. void PrimitiveManager::endDraw() { if ((m_vertices.getNumElt() == 0) || (m_colors.getNumElt() == 0)) { return; } setModelviewProjection(); if (m_colorShader.instance.isInUse()) { m_colorShader.instance.setConstVector3(m_colorShader.u_scale, Vector3(1,1,1)); // vertices if ((UInt32)m_vertices.getSize() <= m_verticesVbo.getCount()) m_verticesVbo.update(m_vertices.getData(), 0, m_vertices.getSize()); else m_verticesVbo.create( m_vertices.getSize(), VertexBuffer::STREAMED, m_vertices.getData(), True); getScene()->getContext()->vertexAttribArray(m_colorShader.a_vertex, 3, 0, 0); // colors if ((UInt32)m_colors.getSize() <= m_colorsVbo.getCount()) m_colorsVbo.update(m_colors.getData(), 0, m_colors.getSize()); else m_colorsVbo.create( m_colors.getSize(), VertexBuffer::STREAMED, m_colors.getData(), True); getScene()->getContext()->vertexAttribArray(m_colorShader.a_color, 4, 0, 0); // and draw getScene()->drawArrays(m_format, 0, m_vertices.getNumElt() / 3); getScene()->getContext()->disableVertexAttribArray(m_colorShader.a_vertex); getScene()->getContext()->disableVertexAttribArray(m_colorShader.a_color); } else if (m_pickingShader.instance.isInUse()) { m_pickingShader.instance.setConstVector3(m_pickingShader.u_scale, Vector3(1,1,1)); // vertices if ((UInt32)m_vertices.getSize() <= m_verticesVbo.getCount()) m_verticesVbo.update(m_vertices.getData(), 0, m_vertices.getSize()); else m_verticesVbo.create( m_vertices.getSize(), VertexBuffer::STREAMED, m_vertices.getData(), True); getScene()->getContext()->vertexAttribArray(m_pickingShader.a_vertex, 3, 0, 0); // and draw getScene()->drawArrays(m_format, 0, m_vertices.getNumElt() / 3); getScene()->getContext()->disableVertexAttribArray(m_pickingShader.a_vertex); } } // Add a vertex with a color into the draw list. void PrimitiveManager::addVertex(const Float *vertex) { static Float whiteColor[4] = { 1.f, 1.f, 1.f, 1.f }; m_vertices.pushArray(vertex, 3); m_colors.pushArray(whiteColor, 4); } // Add a vertex with a color into the draw list. void PrimitiveManager::addVertex(const Vector3 &vertex) { static Float whiteColor[4] = { 1.f, 1.f, 1.f, 1.f }; m_vertices.pushArray(vertex.getData(), 3); m_colors.pushArray(whiteColor, 4); } // Add a vertex into the draw list. void PrimitiveManager::addVertex(const Vector3 &vertex, const Color &color) { m_vertices.pushArray(vertex.getData(), 3); m_colors.pushArray(color.getData(), 4); } // Add a vertex into the draw list. void PrimitiveManager::addVertex(const Float *vertex, const Color &color) { m_vertices.pushArray(vertex, 3); m_colors.pushArray(color.getData(), 4); } // Add a vertex into the draw list. void PrimitiveManager::addVertex(const Float *vertex, const Float *color) { m_vertices.pushArray(vertex, 3); m_colors.pushArray(color, 4); }
33.024673
125
0.668498
dream-overflow
4e7e566bcb2e39faa1c6fbb506dfaf11f7ee398e
12,402
cpp
C++
src/prod/src/ServiceModel/HealthEvaluationBase.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
1
2018-03-15T02:09:21.000Z
2018-03-15T02:09:21.000Z
src/prod/src/ServiceModel/HealthEvaluationBase.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
null
null
null
src/prod/src/ServiceModel/HealthEvaluationBase.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
null
null
null
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace ServiceModel; INITIALIZE_BASE_DYNAMIC_SIZE_ESTIMATION(HealthEvaluationBase) StringLiteral const TraceSource("HealthEvaluationBase"); HealthEvaluationBase::HealthEvaluationBase() : kind_(FABRIC_HEALTH_EVALUATION_KIND_INVALID) , description_() , aggregatedHealthState_(FABRIC_HEALTH_STATE_INVALID) { } HealthEvaluationBase::HealthEvaluationBase(FABRIC_HEALTH_EVALUATION_KIND kind) : kind_(kind) , description_() , aggregatedHealthState_(FABRIC_HEALTH_STATE_INVALID) { } HealthEvaluationBase::HealthEvaluationBase( FABRIC_HEALTH_EVALUATION_KIND kind, FABRIC_HEALTH_STATE aggregatedHealthState) : kind_(kind) , description_() , aggregatedHealthState_(aggregatedHealthState) { } HealthEvaluationBase::~HealthEvaluationBase() { } void HealthEvaluationBase::SetDescription() { Assert::CodingError("SetDescription: Should be handled by derived classes"); } void HealthEvaluationBase::GenerateDescription() { this->SetDescription(); } Common::ErrorCode HealthEvaluationBase::GenerateDescriptionAndTrimIfNeeded(size_t maxAllowedSize, __inout size_t & currentSize) { this->SetDescription(); return this->TryAdd(maxAllowedSize, currentSize); } // Generate the description text and update currentSize with the string size. // If the total size doesn't respect maxAllowedSize, return error. Common::ErrorCode HealthEvaluationBase::TryAdd( size_t maxAllowedSize, __inout size_t & currentSize) { currentSize += EstimateSize(); if (currentSize >= maxAllowedSize) { // No need to generate a message, the caller uses the information to generate one Trace.WriteInfo( TraceSource, "Error adding description for evaluation. Description='{0}', maxSize={1}, currentSize={2}", description_, maxAllowedSize, currentSize); return ErrorCode(ErrorCodeValue::EntryTooLarge); } return ErrorCode::Success(); } ErrorCode HealthEvaluationBase::ToPublicApi( __in Common::ScopedHeap & heap, __out FABRIC_HEALTH_EVALUATION & publicHealthEvaluation) const { UNREFERENCED_PARAMETER(heap); publicHealthEvaluation.Kind = FABRIC_HEALTH_EVALUATION_KIND_INVALID; publicHealthEvaluation.Value = NULL; return ErrorCode::Success(); } ErrorCode HealthEvaluationBase::FromPublicApi( FABRIC_HEALTH_EVALUATION const & publicHealthEvaluation) { UNREFERENCED_PARAMETER(publicHealthEvaluation); kind_ = FABRIC_HEALTH_EVALUATION_KIND_INVALID; return ErrorCode(ErrorCodeValue::InvalidArgument); } int HealthEvaluationBase::GetUnhealthyPercent(size_t unhealthyCount, ULONG totalCount) { if (totalCount == 0) { return 0; } return static_cast<int>(static_cast<float>(unhealthyCount) * 100.0f / static_cast<float>(totalCount)); } Serialization::IFabricSerializable * HealthEvaluationBase::FabricSerializerActivator( Serialization::FabricTypeInformation typeInformation) { if (typeInformation.buffer == nullptr || typeInformation.length != sizeof(FABRIC_HEALTH_EVALUATION_KIND)) { return nullptr; } FABRIC_HEALTH_EVALUATION_KIND kind = *(reinterpret_cast<FABRIC_HEALTH_EVALUATION_KIND const *>(typeInformation.buffer)); return CreateNew(kind); } HealthEvaluationBase * HealthEvaluationBase::CreateNew(FABRIC_HEALTH_EVALUATION_KIND kind) { switch (kind) { case FABRIC_HEALTH_EVALUATION_KIND_EVENT: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_EVENT>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_REPLICAS: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_REPLICAS>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_PARTITIONS: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_PARTITIONS>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_SERVICE_PACKAGES: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_SERVICE_PACKAGES>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_APPLICATIONS: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_APPLICATIONS>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_SERVICES: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_SERVICES>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_NODES: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_NODES>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_APPLICATIONS: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_APPLICATIONS>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_APPLICATION_TYPE_APPLICATIONS: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_APPLICATION_TYPE_APPLICATIONS>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_SYSTEM_APPLICATION: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_SYSTEM_APPLICATION>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_NODES: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_NODES>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_DEPLOYED_APPLICATIONS: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_DEPLOYED_APPLICATIONS>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_REPLICA: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_REPLICA>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_PARTITION: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_PARTITION>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_SERVICE_PACKAGE: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_SERVICE_PACKAGE>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_APPLICATION: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_APPLICATION>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_SERVICE: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_SERVICE>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_NODE: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_NODE>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_APPLICATION: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_APPLICATION>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_DELTA_NODES_CHECK: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_DELTA_NODES_CHECK>::CreateNew(); case FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_DELTA_NODES_CHECK: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_DELTA_NODES_CHECK>::CreateNew(); default: return new HealthEvaluationBase(FABRIC_HEALTH_EVALUATION_KIND_INVALID); } } HealthEvaluationBaseSPtr HealthEvaluationBase::CreateSPtr(FABRIC_HEALTH_EVALUATION_KIND kind) { switch (kind) { case FABRIC_HEALTH_EVALUATION_KIND_EVENT: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_EVENT>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_REPLICAS: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_REPLICAS>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_PARTITIONS: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_PARTITIONS>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_SERVICE_PACKAGES: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_SERVICE_PACKAGES>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_APPLICATIONS: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_APPLICATIONS>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_SERVICES: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_SERVICES>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_NODES: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_NODES>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_APPLICATIONS: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_APPLICATIONS>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_APPLICATION_TYPE_APPLICATIONS: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_APPLICATION_TYPE_APPLICATIONS>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_SYSTEM_APPLICATION: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_SYSTEM_APPLICATION>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_NODES: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_NODES>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_DEPLOYED_APPLICATIONS: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_DEPLOYED_APPLICATIONS>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_REPLICA: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_REPLICA>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_PARTITION: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_PARTITION>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_SERVICE_PACKAGE: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_SERVICE_PACKAGE>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_APPLICATION: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_APPLICATION>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_SERVICE: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_SERVICE>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_NODE: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_NODE>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_APPLICATION: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_APPLICATION>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_DELTA_NODES_CHECK: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_DELTA_NODES_CHECK>::CreateSPtr(); case FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_DELTA_NODES_CHECK: return HealthEvaluationSerializationTypeActivator<FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_DELTA_NODES_CHECK>::CreateSPtr(); default: return make_shared<HealthEvaluationBase>(FABRIC_HEALTH_EVALUATION_KIND_INVALID); } } NTSTATUS HealthEvaluationBase::GetTypeInformation( __out Serialization::FabricTypeInformation & typeInformation) const { typeInformation.buffer = reinterpret_cast<UCHAR const *>(&kind_); typeInformation.length = sizeof(kind_); return STATUS_SUCCESS; } void HealthEvaluationBase::WriteTo(__in TextWriter& writer, FormatOptions const &) const { writer.WriteLine(); writer.Write("{0}: {1}: [{2}]", kind_, aggregatedHealthState_, description_); } void HealthEvaluationBase::WriteToEtw(uint16 contextSequenceId) const { ServiceModel::ServiceModelEventSource::Trace->HealthEvaluationBaseTrace( contextSequenceId, wformatString(kind_), wformatString(aggregatedHealthState_), description_); } wstring HealthEvaluationBase::ToString() const { wstring result; StringWriter(result).Write(*this); return result; }
48.826772
140
0.812127
AnthonyM
4e84368ec2095abd3990d4f6df10bedd054939ea
54
hpp
C++
src/boost_mpl_aux__preprocessed_bcc_bitxor.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_mpl_aux__preprocessed_bcc_bitxor.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_mpl_aux__preprocessed_bcc_bitxor.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/mpl/aux_/preprocessed/bcc/bitxor.hpp>
27
53
0.796296
miathedev
4e876611541bd44740b0cb74a8eda89e6568f757
3,326
cpp
C++
tests/gl/pngwrite.cpp
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
15
2017-10-18T05:08:16.000Z
2022-02-02T11:01:46.000Z
tests/gl/pngwrite.cpp
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
null
null
null
tests/gl/pngwrite.cpp
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
1
2018-11-10T03:12:57.000Z
2018-11-10T03:12:57.000Z
// SPDX-License-Identifier: MIT // Copyright contributors to the gecko project. #include <base/cmd_line.h> #include <base/unit_test.h> #include <gl/api.h> #include <gl/check.h> #include <gl/framebuffer.h> #include <gl/png_image.h> #include <gl/texture.h> #include <platform/platform.h> namespace { int safemain( int argc, char *argv[] ) { base::cmd_line options( argv[0] ); base::unit_test test( "info" ); test.setup( options ); options.add_help(); options.parse( argc, argv ); if ( options["help"] ) { std::cerr << options << std::endl; return -1; } // Create a window auto sys = platform::platform::common().create(); auto win = sys->new_window(); win->set_title( "Triangle" ); win->acquire(); // OpenGL initialization gl::api ogl; // ogl.enable( gl::capability::DEPTH_TEST ); // ogl.depth_func( gl::depth_test::LESS ); // Create the geometry for the triangle auto vbo_points = ogl.new_array_buffer<float>( { 0.0F, 0.5F, 0.0F, 0.5F, -0.5F, 0.0F, -0.5F, -0.5F, 0.0F } ); auto vbo_colors = ogl.new_array_buffer<float>( { 1.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 1.0F } ); auto vao = ogl.new_vertex_array(); { auto tmp = vao->bind(); tmp.attrib_pointer( 0, vbo_points, 3 ); tmp.attrib_pointer( 1, vbo_colors, 3 ); } // The shaders and program for the triangle auto vshader = ogl.new_shader( gl::shader::type::VERTEX, R"SHADER( #version 410 layout(location = 0) in vec3 vertex_position; layout(location = 1) in vec3 vertex_colour; out vec3 colour; void main() { colour = vertex_colour; gl_Position = vec4( vertex_position, 1.0 ); } )SHADER" ); auto fshader = ogl.new_shader( gl::shader::type::FRAGMENT, R"SHADER( #version 410 in vec3 colour; out vec4 frag_colour; void main() { frag_colour = vec4( colour, 1.0 ); } )SHADER" ); auto prog = ogl.new_program( vshader, fshader ); checkgl(); gl::texture txt; gl::framebuffer fb; auto bfb = fb.bind(); { auto bound = txt.bind( gl::texture::target::TEXTURE_RECTANGLE ); bound.image_2d_rgb( gl::format::RGB, 200, 200, gl::image_type::UNSIGNED_BYTE, nullptr ); checkgl(); checkgl(); bfb.attach( txt ); checkgl(); } test["png_write"] = [&]( void ) { checkgl(); ogl.clear( gl::buffer_bit::COLOR_BUFFER_BIT ); checkgl(); ogl.viewport( 0, 0, static_cast<size_t>( 200 ), static_cast<size_t>( 200 ) ); checkgl(); prog->use(); checkgl(); auto triangle = vao->bind(); triangle.draw( gl::primitive::TRIANGLES, 0, 3 ); checkgl(); gl::png_write( "/tmp/test.png", 200, 200, 3 ); checkgl(); win->release(); }; test.run( options ); test.clean(); return -static_cast<int>( test.failure_count() ); } } // namespace //////////////////////////////////////// int main( int argc, char *argv[] ) { int ret = -1; try { ret = safemain( argc, argv ); } catch ( std::exception &e ) { base::print_exception( std::cerr, e ); } return ret; } ////////////////////////////////////////
21.184713
80
0.555622
kdt3rd
4e87c07a80e60273a4e449b8b295be5c4bd921f2
4,367
cpp
C++
src/engine/components/LuaBehavior.cpp
xCocoDev/Sealed
637946ccb1c8af2e95033533cb2a84dd3b5e22af
[ "Apache-2.0" ]
null
null
null
src/engine/components/LuaBehavior.cpp
xCocoDev/Sealed
637946ccb1c8af2e95033533cb2a84dd3b5e22af
[ "Apache-2.0" ]
null
null
null
src/engine/components/LuaBehavior.cpp
xCocoDev/Sealed
637946ccb1c8af2e95033533cb2a84dd3b5e22af
[ "Apache-2.0" ]
null
null
null
// // Created by xCocoDev on 2019-01-31. // #include "LuaBehavior.h" using namespace en; LuaReference makeLuaBehaviorFromScriptFile(LuaState& lua, const std::string& name) { // Load and run the file, expect it to return a factory function if (!lua.doFile(name, 1)) return {}; if (!lua_isfunction(lua, -1)) { lua_pop(lua, 1); return {}; } // Call the factory function if (!lua.pcall(0, 1)) return {}; if (!lua_istable(lua, -1)) { lua_pop(lua, 1); return {}; } // Ref the created object and return the reference wrapper. return LuaReference(lua); } LuaReference getFunctionFromTable(lua_State* L, const std::string& name) { lua_getfield(L, -1, name.c_str()); if (lua_isfunction(L, -1)) { return lua::LuaReference(L); } else { lua_pop(L, 1); return {}; } } int LuaBehavior::indexFunction(lua_State* L) { // stack: // 1 ComponentReference to behavior // 2 key LuaBehavior& behavior = lua::check<ComponentReference<LuaBehavior>>(L, 1); if (!behavior.m_self) return 0; behavior.m_self.push(); lua_pushvalue(L, 2); lua_gettable(L, -2); return 1; } int LuaBehavior::newindexFunction(lua_State* L) { // stack: // 1 behavior // 2 key // 3 value LuaBehavior& behavior = lua::check<ComponentReference<LuaBehavior>>(L, 1); if (!behavior.m_self) return 0; behavior.m_self.push(); lua_pushvalue(L, 2); lua_pushvalue(L, 3); lua_settable(L, -3); return 0; } LuaBehavior& LuaBehavior::addFromLua(Actor& actor, LuaState& lua) { int typeId = lua_type(lua, -1); if (typeId == LUA_TTABLE) { lua_pushvalue(lua, -1); return actor.add<LuaBehavior>(LuaReference(lua)); } if (typeId == LUA_TSTRING) { LuaReference ref = makeLuaBehaviorFromScriptFile(lua, lua.to<std::string>()); if (ref) return actor.add<LuaBehavior>(std::move(ref)); } return actor.add<LuaBehavior>(); } void LuaBehavior::initializeMetatable(LuaState& lua) { lua.setField("__index", &indexFunction); lua.setField("__newindex", &newindexFunction); } LuaBehavior::LuaBehavior(en::Actor actor) : Behavior(actor) {} LuaBehavior::LuaBehavior(Actor actor, LuaReference&& table) : LuaBehavior(actor) { m_self = std::move(table); LuaState lua = m_self.getLuaState(); m_self.push(); auto popSelf = lua::PopperOnDestruct(lua); m_start = getFunctionFromTable(lua, "start"); m_update = getFunctionFromTable(lua, "update"); m_onCollision = getFunctionFromTable(lua, "onCollision"); m_onMouseEnter = getFunctionFromTable(lua, "onMouseEnter"); m_onMouseOver = getFunctionFromTable(lua, "onMouseOver" ); m_onMouseLeave = getFunctionFromTable(lua, "onMouseLeave"); m_onMouseDown = getFunctionFromTable(lua, "onMouseDown" ); m_onMouseHold = getFunctionFromTable(lua, "onMouseHold" ); m_onMouseUp = getFunctionFromTable(lua, "onMouseUp" ); lua.setField("actor", actor); } template<typename... Args> void callCallbackFunction(const LuaReference& self, const LuaReference& func, Args&&... args) { if (!self || !func) return; LuaState lua = func.getLuaState(); assert(lua == self.getLuaState()); func.push(); self.push(); (lua.push(std::forward<Args>(args)), ...); lua.pcall(1 + sizeof...(Args), 0); } void LuaBehavior::start() { callCallbackFunction(m_self, m_start); } void LuaBehavior::update(float dt) { callCallbackFunction(m_self, m_update, dt); } void LuaBehavior::onCollision(Entity other) { callCallbackFunction(m_self, m_onCollision, m_engine->actor(other)); } void LuaBehavior::on(const MouseEnter& enter) { callCallbackFunction(m_self, m_onMouseEnter); } void LuaBehavior::on(const MouseOver& over) { callCallbackFunction(m_self, m_onMouseOver); } void LuaBehavior::on(const MouseLeave& leave) { callCallbackFunction(m_self, m_onMouseLeave); } void LuaBehavior::on(const MouseDown& down) { callCallbackFunction(m_self, m_onMouseDown, down.button); } void LuaBehavior::on(const MouseHold& hold) { callCallbackFunction(m_self, m_onMouseHold, hold.button); } void LuaBehavior::on(const MouseUp& up) { callCallbackFunction(m_self, m_onMouseUp, up.button); }
24.8125
95
0.65995
xCocoDev
4e8c92ad8163af8ff90943241ae20bfda8f50d35
4,910
cpp
C++
src/test/FileEncDecTest.cpp
ronys/pwsafe
39f9525a9f14cc5fe46214367cf714c5770283ef
[ "Artistic-2.0" ]
578
2015-08-18T19:43:05.000Z
2022-03-27T11:57:07.000Z
src/test/FileEncDecTest.cpp
ronys/pwsafe
39f9525a9f14cc5fe46214367cf714c5770283ef
[ "Artistic-2.0" ]
521
2015-08-27T18:39:33.000Z
2022-03-24T09:48:00.000Z
src/test/FileEncDecTest.cpp
ronys/pwsafe
39f9525a9f14cc5fe46214367cf714c5770283ef
[ "Artistic-2.0" ]
160
2015-08-18T19:46:09.000Z
2022-01-31T12:08:24.000Z
/* * Copyright (c) 2003-2021 Rony Shapiro <ronys@pwsafe.org>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ // FileEncDecTest.cpp: Unit test for file encryption/decryption #ifdef WIN32 #include "../ui/Windows/stdafx.h" #endif #include "core/PWSfile.h" #include "os/file.h" #include "os/dir.h" #include "gtest/gtest.h" // A fixture for factoring common code across tests class FileEncDecTest : public ::testing::Test { protected: FileEncDecTest(); // to init members void SetUp(); void TearDown(); const StringX passphrase; stringT fname; stringT errmes; static const stringT suffix; void TestFile(const stringT& testfile); // encrypt, decrypt and compare against original }; const stringT FileEncDecTest::suffix = L".PSF"; FileEncDecTest::FileEncDecTest() : passphrase(_T("strawberry_phasers")), fname(_T("text1.txt")), errmes(L"") {} void FileEncDecTest::SetUp() { // tests require writable data dir with text1.txt file ASSERT_TRUE(pws_os::chdir(L"data")); } void FileEncDecTest::TearDown() { ASSERT_TRUE(pws_os::chdir(L"..")); } // And now the tests... TEST_F(FileEncDecTest, NoFile) { EXPECT_FALSE(PWSfile::Encrypt(L"nosuchfile", passphrase, errmes)); EXPECT_FALSE(errmes.empty()); errmes = L""; EXPECT_FALSE(PWSfile::Decrypt(L"nosuchfile", passphrase, errmes)); EXPECT_FALSE(errmes.empty()); } TEST_F(FileEncDecTest, EmptyFile) { const stringT emptyFile(L"anEmptyFile"); const stringT emptyCipherFile = emptyFile + suffix; // create an empty file auto fp = pws_os::FOpen(emptyFile, L"w"); ASSERT_TRUE(fp != nullptr); auto res = pws_os::FClose(fp, true); ASSERT_TRUE(res == 0); // decrypting an empty file should fail (too small) errmes = L""; EXPECT_FALSE(PWSfile::Decrypt(emptyCipherFile, emptyFile.c_str(), errmes)); EXPECT_FALSE(errmes.empty()); errmes = L""; EXPECT_TRUE(PWSfile::Encrypt(emptyFile, passphrase, errmes)); EXPECT_TRUE(errmes.empty()); ASSERT_TRUE(pws_os::FileExists(emptyCipherFile)); // try decrypting with wrong passphrase errmes = L""; EXPECT_FALSE(PWSfile::Decrypt(emptyCipherFile, emptyFile.c_str(), errmes)); EXPECT_FALSE(errmes.empty()); // now with the correct passphrase errmes = L""; EXPECT_TRUE(PWSfile::Decrypt(emptyCipherFile, passphrase, errmes)); EXPECT_TRUE(errmes.empty()); // check decrypted file fp = pws_os::FOpen(emptyFile, L"r"); ASSERT_TRUE(fp != nullptr); EXPECT_EQ(pws_os::fileLength(fp), 0); res = pws_os::FClose(fp, true); ASSERT_TRUE(res == 0); // cleanup ASSERT_TRUE(pws_os::DeleteAFile(emptyFile)); ASSERT_TRUE(pws_os::DeleteAFile(emptyCipherFile)); } TEST_F(FileEncDecTest, RegularFile) { // test files are part of source tree TestFile(L"text1.txt"); TestFile(L"image1.jpg"); } TEST_F(FileEncDecTest, BigFile) { // fake big file by changing definition of "big" auto oldThreshold = PWSfile::fileThresholdSize; PWSfile::fileThresholdSize = 100000; // smaller than image1.jpg TestFile(L"image1.jpg"); PWSfile::fileThresholdSize = oldThreshold; } void FileEncDecTest::TestFile(const stringT& testfile) { const stringT originalTestFile = testfile; const stringT workTestFile = L"EncDecTest"; const stringT workCipherFile = workTestFile + suffix; ASSERT_TRUE(pws_os::FileExists(originalTestFile)); // create a copy const stringT curdir = pws_os::getcwd() + L"/"; ASSERT_TRUE(pws_os::CopyAFile(curdir + originalTestFile, curdir + workTestFile)); errmes = L""; EXPECT_TRUE(PWSfile::Encrypt(workTestFile, passphrase, errmes)); EXPECT_TRUE(errmes.empty()); ASSERT_TRUE(pws_os::FileExists(workCipherFile)); // try decrypting with wrong passphrase errmes = L""; EXPECT_FALSE(PWSfile::Decrypt(workCipherFile, originalTestFile.c_str(), errmes)); EXPECT_FALSE(errmes.empty()); // now with the correct passphrase errmes = L""; EXPECT_TRUE(PWSfile::Decrypt(workCipherFile, passphrase, errmes)); EXPECT_TRUE(errmes.empty()); // check decrypted file auto fp = pws_os::FOpen(originalTestFile, L"rb"); ASSERT_TRUE(fp != nullptr); auto len1 = pws_os::fileLength(fp); auto origBuf = new char[len1]; ASSERT_EQ(len1, fread(origBuf, 1, len1, fp)); auto res = pws_os::FClose(fp, true); ASSERT_TRUE(res == 0); fp = pws_os::FOpen(workTestFile, L"rb"); ASSERT_TRUE(fp != nullptr); auto len2 = pws_os::fileLength(fp); EXPECT_EQ(len1, len2); auto workBuf = new char[len2]; ASSERT_EQ(len2, fread(workBuf, 1, len2, fp)); res = pws_os::FClose(fp, true); ASSERT_TRUE(res == 0); ASSERT_EQ(memcmp(origBuf, workBuf, len1), 0); //cleanup delete[] origBuf; delete[] workBuf; ASSERT_TRUE(pws_os::DeleteAFile(workTestFile)); ASSERT_TRUE(pws_os::DeleteAFile(workCipherFile)); }
27.430168
90
0.716701
ronys
4e8ca1bde906fa0b4334fd414f3deca9d0d1456f
4,581
cpp
C++
WebKit2-7604.1.38.0.7/WebKit2-7604.1.38.0.7/UIProcess/API/APIWebsiteDataStore.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
1
2021-05-27T07:29:31.000Z
2021-05-27T07:29:31.000Z
WebKit2-7604.1.38.0.7/WebKit2-7604.1.38.0.7/UIProcess/API/APIWebsiteDataStore.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
WebKit2-7604.1.38.0.7/WebKit2-7604.1.38.0.7/UIProcess/API/APIWebsiteDataStore.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
/* * Copyright (C) 2014-2017 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h" #include "APIWebsiteDataStore.h" #include "WebKit2Initialize.h" #include "WebsiteDataStore.h" namespace API { Ref<WebsiteDataStore> WebsiteDataStore::defaultDataStore() { WebKit::InitializeWebKit2(); static WebsiteDataStore* defaultDataStore = adoptRef(new WebsiteDataStore(defaultDataStoreConfiguration(), WebCore::SessionID::defaultSessionID())).leakRef(); return *defaultDataStore; } Ref<WebsiteDataStore> WebsiteDataStore::createNonPersistentDataStore() { return adoptRef(*new WebsiteDataStore); } Ref<WebsiteDataStore> WebsiteDataStore::createLegacy(WebKit::WebsiteDataStore::Configuration configuration) { return adoptRef(*new WebsiteDataStore(WTFMove(configuration), WebCore::SessionID::defaultSessionID())); } WebsiteDataStore::WebsiteDataStore() : m_websiteDataStore(WebKit::WebsiteDataStore::createNonPersistent()) { } WebsiteDataStore::WebsiteDataStore(WebKit::WebsiteDataStore::Configuration configuration, WebCore::SessionID sessionID) : m_websiteDataStore(WebKit::WebsiteDataStore::create(WTFMove(configuration), sessionID)) { } WebsiteDataStore::~WebsiteDataStore() { } HTTPCookieStore& WebsiteDataStore::httpCookieStore() { if (!m_apiHTTPCookieStore) m_apiHTTPCookieStore = HTTPCookieStore::create(*this); return *m_apiHTTPCookieStore; } bool WebsiteDataStore::isPersistent() { return m_websiteDataStore->isPersistent(); } bool WebsiteDataStore::resourceLoadStatisticsEnabled() const { return m_websiteDataStore->resourceLoadStatisticsEnabled(); } void WebsiteDataStore::setResourceLoadStatisticsEnabled(bool enabled) { m_websiteDataStore->setResourceLoadStatisticsEnabled(enabled); } #if !PLATFORM(COCOA) && !PLATFORM(GTK) WebKit::WebsiteDataStore::Configuration WebsiteDataStore::defaultDataStoreConfiguration() { // FIXME: Fill everything in. WebKit::WebsiteDataStore::Configuration configuration; return configuration; } String WebsiteDataStore::websiteDataDirectoryFileSystemRepresentation(const String&) { // FIXME: Implement. return String(); } String WebsiteDataStore::defaultLocalStorageDirectory() { // FIXME: Implement. return String(); } String WebsiteDataStore::defaultWebSQLDatabaseDirectory() { // FIXME: Implement. return String(); } String WebsiteDataStore::defaultNetworkCacheDirectory() { // FIXME: Implement. return String(); } String WebsiteDataStore::defaultApplicationCacheDirectory() { // FIXME: Implement. return String(); } String WebsiteDataStore::defaultMediaKeysStorageDirectory() { // FIXME: Implement. return String(); } String WebsiteDataStore::defaultIndexedDBDatabaseDirectory() { // FIXME: Implement. return String(); } String WebsiteDataStore::defaultResourceLoadStatisticsDirectory() { // FIXME: Implement. return String(); } #endif #if !PLATFORM(COCOA) String WebsiteDataStore::defaultMediaCacheDirectory() { // FIXME: Implement. https://bugs.webkit.org/show_bug.cgi?id=156369 and https://bugs.webkit.org/show_bug.cgi?id=156370 return String(); } String WebsiteDataStore::defaultJavaScriptConfigurationDirectory() { // FIXME: Implement. return String(); } #endif }
27.932927
162
0.764244
mlcldh
4e921ff5e1eb14af06013b9fd87c094e4aa19fcd
17,497
hpp
C++
include/nori/RenderContext.hpp
elmindreda/Nori
fdeec9970ee6a254bae389ade4455171df875473
[ "Zlib" ]
23
2015-06-13T22:42:38.000Z
2019-08-06T19:56:19.000Z
include/nori/RenderContext.hpp
elmindreda/nori
fdeec9970ee6a254bae389ade4455171df875473
[ "Zlib" ]
null
null
null
include/nori/RenderContext.hpp
elmindreda/nori
fdeec9970ee6a254bae389ade4455171df875473
[ "Zlib" ]
3
2015-05-31T17:01:10.000Z
2020-03-26T13:55:24.000Z
/////////////////////////////////////////////////////////////////////// // Nori - a simple game engine // Copyright (c) 2004 Camilla Berglund <elmindreda@elmindreda.org> // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any // damages arising from the use of this software. // // Permission is granted to anyone to use this software for any // purpose, including commercial applications, and to alter it and // redistribute it freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you // must not claim that you wrote the original software. If you use // this software in a product, an acknowledgment in the product // documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and // must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // /////////////////////////////////////////////////////////////////////// #pragma once #include <nori/Core.hpp> #include <nori/Rect.hpp> #include <nori/Pixel.hpp> #include <nori/Signal.hpp> #include <nori/Time.hpp> #include <nori/Window.hpp> #include <deque> namespace nori { class AABB; class VertexBuffer; class IndexBuffer; class RenderContext; class PrimitiveRange; /*! @brief Polygon face enumeration. */ enum PolygonFace { /*! Cull front-facing geometry (i.e. render back-facing geometry). */ FACE_FRONT, /*! Cull back-facing geometry (i.e. render front-facing geometry). */ FACE_BACK, /*! Cull all cullable geometry (i.e. front and back faces). */ FACE_BOTH, /*! Do not cull any geometry. */ FACE_NONE }; /*! Blend factor enumeration. */ enum BlendFactor { BLEND_ZERO, BLEND_ONE, BLEND_SRC_COLOR, BLEND_DST_COLOR, BLEND_SRC_ALPHA, BLEND_DST_ALPHA, BLEND_ONE_MINUS_SRC_COLOR, BLEND_ONE_MINUS_DST_COLOR, BLEND_ONE_MINUS_SRC_ALPHA, BLEND_ONE_MINUS_DST_ALPHA }; /*! Stencil operation enumeration. */ enum StencilOp { STENCIL_KEEP, STENCIL_ZERO, STENCIL_REPLACE, STENCIL_INCREASE, STENCIL_DECREASE, STENCIL_INVERT, STENCIL_INCREASE_WRAP, STENCIL_DECREASE_WRAP }; /*! Comparison function enumeration. */ enum FragmentFunction { ALLOW_NEVER, ALLOW_ALWAYS, ALLOW_EQUAL, ALLOW_NOT_EQUAL, ALLOW_LESSER, ALLOW_LESSER_EQUAL, ALLOW_GREATER, ALLOW_GREATER_EQUAL }; enum { SHARED_MODEL_MATRIX, SHARED_VIEW_MATRIX, SHARED_PROJECTION_MATRIX, SHARED_MODELVIEW_MATRIX, SHARED_VIEWPROJECTION_MATRIX, SHARED_MODELVIEWPROJECTION_MATRIX, SHARED_INVERSE_MODEL_MATRIX, SHARED_INVERSE_VIEW_MATRIX, SHARED_INVERSE_PROJECTION_MATRIX, SHARED_INVERSE_MODELVIEW_MATRIX, SHARED_INVERSE_VIEWPROJECTION_MATRIX, SHARED_INVERSE_MODELVIEWPROJECTION_MATRIX, SHARED_CAMERA_NEAR_Z, SHARED_CAMERA_FAR_Z, SHARED_CAMERA_ASPECT_RATIO, SHARED_CAMERA_FOV, SHARED_CAMERA_POSITION, SHARED_VIEWPORT_WIDTH, SHARED_VIEWPORT_HEIGHT, SHARED_TIME, SHARED_STATE_CUSTOM_BASE }; /*! @brief Render context configuration. * * This class provides the settings parameters available for render * context creation, as provided through RenderContext::create. */ class RenderConfig { public: /*! Constructor. */ RenderConfig(uint colorBits = 32, uint depthBits = 24, uint stencilBits = 0, uint samples = 0, bool debug = false); /*! The desired color buffer bit depth. */ uint colorBits; /*! The desired depth buffer bit depth. */ uint depthBits; /*! The desired stencil buffer bit depth. */ uint stencilBits; /*! The desired number of FSAA samples. */ uint samples; /*! Whether to create a debug context. */ bool debug; }; /*! Render state. */ class RenderState { public: RenderState(); float lineWidth; BlendFactor srcFactor : 4; BlendFactor dstFactor : 4; PolygonFace cullFace : 2; FragmentFunction depthFunction : 3; bool depthTesting : 1; bool depthWriting : 1; bool colorWriting : 1; bool stencilTesting : 1; bool wireframe : 1; bool lineSmoothing : 1; bool multisampling : 1; struct { uint reference; uint mask; FragmentFunction function : 3; StencilOp stencilFailOp : 3; StencilOp depthFailOp : 3; StencilOp depthPassOp : 3; } stencil[2]; }; /*! Render context limits data. */ class RenderLimits { public: /*! Constructor. */ RenderLimits(RenderContext& context); /*! The maximum number of color buffers that can be attached to to an image * framebuffer (FBO). */ uint maxColorAttachments; /*! The maximum number of simultaneously active color buffers. */ uint maxDrawBuffers; /*! The number of available vertex shader texture image units. */ uint maxVertexTextureImageUnits; /*! The number of available fragment shader texture image units. */ uint maxFragmentTextureImageUnits; /*! The total number of available shader texture image units. */ uint maxCombinedTextureImageUnits; /*! The maximum size, in pixels, of 2D POT textures. */ uint maxTextureSize; /*! The maximum size, in pixels, of 3D POT textures. */ uint maxTexture3DSize; /*! The maximum size, in pixels, of cube map texture faces. */ uint maxTextureCubeSize; /*! The maximum size, in pixels, of non-POT 2D textures. */ uint maxTextureRectangleSize; /*! The number of available texture coordinates. */ uint maxTextureCoords; /*! The maximum texture anisotropy. */ float maxTextureAnisotropy; /*! The number of available vertex attributes. */ uint maxVertexAttributes; }; /*! @brief %Render statistics. */ class RenderStats { public: class Frame { public: Frame(); uint operationCount; uint stateChangeCount; uint vertexCount; uint pointCount; uint lineCount; uint triangleCount; Time duration; }; RenderStats(); void addFrame(); void addStateChange(); void addPrimitives(PrimitiveType type, uint vertexCount); void addTexture(size_t size); void removeTexture(size_t size); void addVertexBuffer(size_t size); void removeVertexBuffer(size_t size); void addIndexBuffer(size_t size); void removeIndexBuffer(size_t size); void addProgram(); void removeProgram(); float frameRate() const { return m_frameRate; } uint frameCount() const { return m_frameCount; } const Frame& currentFrame() const { return m_frames.front(); } uint textureCount() const { return m_textureCount; } uint vertexBufferCount() const { return m_vertexBufferCount; } uint indexBufferCount() const { return m_indexBufferCount; } uint programCount() const { return m_programCount; } size_t totalTextureSize() const { return m_textureSize; } size_t totalVertexBufferSize() const { return m_vertexBufferSize; } size_t totalIndexBufferSize() const { return m_indexBufferSize; } private: uint m_frameCount; float m_frameRate; std::deque<Frame> m_frames; uint m_textureCount; uint m_vertexBufferCount; uint m_indexBufferCount; uint m_programCount; size_t m_textureSize; size_t m_vertexBufferSize; size_t m_indexBufferSize; Timer m_timer; }; class SharedProgramState : public RefObject { public: /*! Constructor. */ SharedProgramState(); virtual void updateTo(Uniform& uniform); /*! @return The model matrix. */ const mat4& modelMatrix() const { return m_modelMatrix; } /*! @return The view matrix. */ const mat4& viewMatrix() const { return m_viewMatrix; } /*! @return The projection matrix. */ const mat4& projectionMatrix() const { return m_projectionMatrix; } void cameraProperties(vec3& position, float& FOV, float& aspect, float& nearZ, float& farZ) const; float viewportWidth() const { return m_viewportWidth; } float viewportHeight() const { return m_viewportHeight; } float time() const { return m_time; } /*! Sets the model matrix. * @param[in] newMatrix The desired model matrix. */ virtual void setModelMatrix(const mat4& newMatrix); /*! Sets the view matrix. * @param[in] newMatrix The desired view matrix. */ virtual void setViewMatrix(const mat4& newMatrix); /*! Sets the projection matrix. * @param[in] newMatrix The desired projection matrix. */ virtual void setProjectionMatrix(const mat4& newMatrix); /*! Sets an orthographic projection matrix as ([0..width], [0..height], * [-1, 1]). * @param[in] width The desired width of the clipspace volume. * @param[in] height The desired height of the clipspace volume. */ virtual void setOrthoProjectionMatrix(float width, float height); /*! Sets an orthographic projection matrix as ([minX..maxX], [minY..maxY], * [minZ, maxZ]). * @param[in] volume The desired projection volume. */ virtual void setOrthoProjectionMatrix(const AABB& volume); /*! Sets a perspective projection matrix. * @param[in] FOV The desired field of view of the projection. * @param[in] aspect The desired aspect ratio of the projection. * @param[in] nearZ The desired near plane distance of the projection. * @param[in] farZ The desired far plane distance of the projection. */ virtual void setPerspectiveProjectionMatrix(float FOV, float aspect, float nearZ, float farZ); virtual void setCameraProperties(const vec3& position, float FOV, float aspect, float nearZ, float farZ); virtual void setViewportSize(float newWidth, float newHeight); virtual void setTime(float newTime); private: bool m_dirtyModelView; bool m_dirtyViewProj; bool m_dirtyModelViewProj; bool m_dirtyInvModel; bool m_dirtyInvView; bool m_dirtyInvProj; bool m_dirtyInvModelView; bool m_dirtyInvViewProj; bool m_dirtyInvModelViewProj; mat4 m_modelMatrix; mat4 m_viewMatrix; mat4 m_projectionMatrix; mat4 m_modelViewMatrix; mat4 m_viewProjMatrix; mat4 m_modelViewProjMatrix; mat4 m_invModelMatrix; mat4 m_invViewMatrix; mat4 m_invProjMatrix; mat4 m_invModelViewMatrix; mat4 m_invViewProjMatrix; mat4 m_invModelViewProjMatrix; float m_cameraNearZ; float m_cameraFarZ; float m_cameraAspect; float m_cameraFOV; vec3 m_cameraPos; float m_viewportWidth; float m_viewportHeight; float m_time; }; /*! @brief Render context. */ class RenderContext : public Trackable { public: /*! Destructor. */ ~RenderContext(); /*! Clears the color buffers of the current framebuffer with the specified * color. * @param[in] color The color value to use. */ void clearColorBuffer(const vec4& color = vec4(0.f)); /*! Clears the depth buffer of the current framebuffer with the specified * depth value. * @param[in] depth The depth value to use. */ void clearDepthBuffer(float depth = 1.f); /*! Clears the stencil buffer of the current framebuffer with the specified * stencil value. * @param[in] value The stencil value to use. */ void clearStencilBuffer(uint value = 0); /*! Clears all buffers of the current framebuffer with the specified values. * @param[in] color The color value to use. * @param[in] depth The depth value to use. * @param[in] value The stencil value to use. */ void clearBuffers(const vec4& color = vec4(0.f), float depth = 1.f, uint value = 0); /*! Renders the specified primitive range to the current framebuffer, using * the current GLSL program. * @pre A GLSL program must be set before calling this method. */ void render(const PrimitiveRange& range); /*! Renders the specified primitive range to the current framebuffer, using * the current GLSL program. * @pre A GLSL program must be set before calling this method. */ void render(PrimitiveType type, uint start, uint count, uint base = 0); /*! Allocates a range of temporary vertices of the specified format. * @param[in] count The number of vertices to allocate. * @param[in] format The format of vertices to allocate. * @return @c The newly allocated vertex range. * * @remarks The allocated vertex range is only valid until the end of the * current frame. */ VertexRange allocateVertices(uint count, const VertexFormat& format); /*! Reserves the specified uniform signature as shared. */ void createSharedUniform(const char* name, UniformType type, int ID); /*! @return The shared ID of the specified uniform signature. */ int sharedUniformID(const char* name, UniformType type) const; /*! @return The current shared program state, or @c nullptr if no shared * program state is currently set. */ SharedProgramState* sharedProgramState() const; /*! Sets the current shared program state. * @param[in] newState The new state object. */ void setSharedProgramState(SharedProgramState* newState); /*! @return GLSL declarations of all shared uniforms. */ const char* sharedProgramStateDeclaration() const; /*! @return The swap interval of this context. */ int swapInterval() const; /*! Sets the swap interval of this context. * @param[in] newInterval The desired swap interval. */ void setSwapInterval(int newInterval); /*! @return The current scissor rectangle. */ const Recti& scissorArea() const; /*! Sets the scissor area of this context. * * @remarks Scissor testing is enabled if the area doesn't include the * entire current framebuffer. */ void setScissorArea(const Recti& newArea); /*! @return The current viewport rectangle. */ const Recti& viewportArea() const; /*! Sets the current viewport rectangle. * @param[in] newArea The desired viewport rectangle. */ void setViewportArea(const Recti& newArea); /*! @return The current framebuffer. */ Framebuffer& framebuffer() const; /*! @return The screen framebuffer. */ WindowFramebuffer& windowFramebuffer() const; /*! Makes the default framebuffer current. */ void setWindowFramebuffer(); /*! Makes the specified framebuffer current. * @param[in] newFramebuffer The desired framebuffer. * @return @c true if successful, or @c false otherwise. */ bool setFramebuffer(Framebuffer& newFramebuffer); /*! Sets the current GLSL program for use when rendering. * @param[in] newProgram The desired GLSL program, or @c nullptr to unbind * the current program. */ void setProgram(Program* newProgram); /*! Sets the current vertex buffer. */ void setVertexBuffer(VertexBuffer* newVertexBuffer); /*! Sets the current index buffer. */ void setIndexBuffer(IndexBuffer* newIndexBuffer); /*! @note Unless you are Nori, you probably don't need to call this. */ void setTexture(Texture* newTexture); /*! @note Unless you are Nori, you probably don't need to call this. */ void setTextureUnit(uint unit); bool isCullingInverted(); void setCullingInversion(bool newState); const RenderState& renderState() const; void setRenderState(const RenderState& newState); bool debug() const { return m_debug; } RenderStats* stats() const; void setStats(RenderStats* newStats); /*! @return The limits of this context. */ const RenderLimits& limits() const; /*! @return The resource cache used by this context. */ ResourceCache& cache() const; /*! @return The window of this context. */ Window& window(); /*! Creates the context object, using the specified settings. * @param[in] cache The resource cache to use. * @param[in] wndconfig The desired window configuration. * @param[in] ctxconfig The desired context configuration. * @return @c true if successful, or @c false otherwise. */ static std::unique_ptr<RenderContext> create(ResourceCache& cache, const WindowConfig& wc = WindowConfig(), const RenderConfig& rc = RenderConfig()); private: RenderContext(ResourceCache& cache); RenderContext(const RenderContext&) = delete; bool init(const WindowConfig& wc, const RenderConfig& rc); void applyState(const RenderState& newState); void forceState(const RenderState& newState); RenderContext& operator = (const RenderContext&) = delete; void onFrame(); struct Slot { Ref<VertexBuffer> buffer; uint available; }; class SharedUniform; ResourceCache& m_cache; Window m_window; GLFWwindow* m_handle; bool m_debug; std::unique_ptr<RenderLimits> m_limits; int m_swapInterval; Recti m_scissorArea; Recti m_viewportArea; bool m_dirtyBinding; bool m_dirtyState; bool m_cullingInverted; std::vector<Ref<Texture>> m_textureUnits; uint m_textureUnit; RenderState m_renderState; Ref<Program> m_program; Ref<VertexBuffer> m_vertexBuffer; Ref<IndexBuffer> m_indexBuffer; Ref<Framebuffer> m_framebuffer; Ref<SharedProgramState> m_sharedProgramState; Ref<WindowFramebuffer> m_windowFramebuffer; std::vector<SharedUniform> m_uniforms; std::vector<Slot> m_slots; std::string m_declaration; RenderStats* m_stats; }; } /*namespace nori*/
30.063574
88
0.693605
elmindreda
4eaea4960660cb2daaa66818847a568f116c573f
3,874
hpp
C++
modules/engine/include/randar/Math/Dimensional2.hpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
1
2016-11-12T02:43:29.000Z
2016-11-12T02:43:29.000Z
modules/engine/include/randar/Math/Dimensional2.hpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
null
null
null
modules/engine/include/randar/Math/Dimensional2.hpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
null
null
null
#ifndef RANDAR_MATH_DIMENSIONAL2_HPP #define RANDAR_MATH_DIMENSIONAL2_HPP #include <limits> #include <stdexcept> #include <randar/Math/Vector2.hpp> namespace randar { /** * Base class for two-dimensional objects. */ template <typename T> class Dimensional2 { protected: T width; T height; T maxWidth; T maxHeight; public: /** * Disable assignments. */ explicit Dimensional2(const Dimensional2<T>& other) = delete; Dimensional2<T>& operator =(const Dimensional2<T>& other) = delete; /** * Default constructor. * * Initializes the object with 0 width, 0 height, and no limits. */ Dimensional2() : width(0), height(0) { } /** * Primary constructor. */ Dimensional2(T initWidth, T initHeight) : width(initWidth), height(initHeight) { } /** * Destructor. */ virtual ~Dimensional2() { } /** * Whether this object has non-zero dimensions. */ bool hasDimensions() const { return this->getWidth() != 0 && this->getHeight() != 0; } public: /** * Sets the width and height of this object. * * Invokes onResize after the new dimensions are set. */ virtual void resize(T newWidth, T newHeight) { if (newWidth < 0 || newHeight < 0) { throw std::runtime_error("Dimensions must not be negative"); } this->width = newWidth; this->height = newHeight; } /** * Sets the width or height of this object. * * Calls are delegated to the resize method. If you need to override the * resizing behavior, simply override resize. */ void setWidth(T newWidth) { this->resize(newWidth, this->height); } void setHeight(T newHeight) { this->resize(this->width, newHeight); } /** * Gets the width and height of this object. */ T getWidth() const { return this->width; } T getHeight() const { return this->height; } /** * Checks if a position is within this dimension's range. * * This check is 0-based. If the dimensions are 20x20, a position at * (5, 20) is out of range; (0, 19) is within range. */ bool isWithinDimensions(const Vector2<T>& position) { return this->isWithinDimensions(position.x, position.y); } bool isWithinDimensions(T x, T y) { return x < this->getWidth() && y < this->getHeight() && x >= 0 && y >= 0; } /** * Describes the dimensions of this object as a string. */ std::string toString() const { return std::to_string(this->width) + "x" + std::to_string(this->height); } }; } #ifdef SWIG %template(Dimensional2_float) randar::Dimensional2<float>; %template(Dimensional2_int8) randar::Dimensional2<int8_t>; %template(Dimensional2_int16) randar::Dimensional2<int16_t>; %template(Dimensional2_int32) randar::Dimensional2<int32_t>; %template(Dimensional2_int64) randar::Dimensional2<int64_t>; %template(Dimensional2_uint8) randar::Dimensional2<uint8_t>; %template(Dimensional2_uint16) randar::Dimensional2<uint16_t>; %template(Dimensional2_uint32) randar::Dimensional2<uint32_t>; %template(Dimensional2_uint64) randar::Dimensional2<uint64_t>; #endif #endif
24.675159
84
0.535622
litty-studios
4eb039b9129daf0faf211f7f987b3361b39e20ba
812
cpp
C++
DataStructure/UnionFindTree.cpp
Kenshin-Y/competitive
9035b86d772e4a48973309dbe45c3355ac18dbcb
[ "MIT" ]
null
null
null
DataStructure/UnionFindTree.cpp
Kenshin-Y/competitive
9035b86d772e4a48973309dbe45c3355ac18dbcb
[ "MIT" ]
null
null
null
DataStructure/UnionFindTree.cpp
Kenshin-Y/competitive
9035b86d772e4a48973309dbe45c3355ac18dbcb
[ "MIT" ]
null
null
null
/* @created: 2019-12 @verified: ATC001-B @description: * UnionFind * 最小全域木にも使える * data[x]= par, rootならsizeになっていて、符号で判定 */ #ifndef UNIONFIND #define UNIONFIND #include <bits/stdc++.h> using namespace std; struct Unionfind { vector<int> data; Unionfind(int size):data(size, -1) {} bool unite(int x, int y) { x=root(x); y=root(y); if(x!=y){ if(data[y] < data[x]) swap(x, y); data[x] += data[y]; data[y] = x; } return x!=y; } bool same(int x, int y) { return root(x) == root(y); } int root(int x) { return (data[x] < 0) ? x : data[x]=root(data[x]); } int size(int x) { return -data[root(x)]; } }; #endif // UNIONFIND
16.916667
57
0.477833
Kenshin-Y
4eb28f2f60f1e4b1d7ea24aa150379f385abfa87
4,813
cc
C++
src/geometry/flat/Flat.cc
Keegan-Humphrey/Mu-Simulation
1201049c4ca388dd68b6e1708180731fc0bb3efc
[ "Unlicense" ]
6
2018-02-06T21:28:07.000Z
2022-03-19T12:55:15.000Z
src/geometry/flat/Flat.cc
Keegan-Humphrey/Mu-Simulation
1201049c4ca388dd68b6e1708180731fc0bb3efc
[ "Unlicense" ]
8
2018-02-18T16:08:45.000Z
2020-01-17T18:11:55.000Z
src/geometry/flat/Flat.cc
Keegan-Humphrey/Mu-Simulation
1201049c4ca388dd68b6e1708180731fc0bb3efc
[ "Unlicense" ]
9
2018-02-06T20:58:50.000Z
2021-09-15T18:17:28.000Z
/* src/geometry/flat/Flat.cc * * Copyright 2018 Brandon Gomes * * 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 "geometry/Flat.hh" #include <tls.hh> #include "geometry/Earth.hh" #include "tracking.hh" namespace MATHUSLA { namespace MU { namespace Flat { /////////////////////////////////////////////////////////////////////////////// namespace { //////////////////////////////////////////////////////////////////////////////////// //__Flat Layers_________________________________________________________________________________ std::vector<Layer*> _layers; //---------------------------------------------------------------------------------------------- //__Flat Hit Collection_________________________________________________________________________ G4ThreadLocal Tracking::HitCollection* _hit_collection; //---------------------------------------------------------------------------------------------- } /* anonymous namespace */ //////////////////////////////////////////////////////////////////// //__Flat Data Variables_________________________________________________________________________ const std::string& Detector::DataName = "flat_run"; const Analysis::ROOT::DataKeyList Detector::DataKeys = Analysis::ROOT::DefaultDataKeyList; const Analysis::ROOT::DataKeyTypeList Detector::DataKeyTypes = Analysis::ROOT::DefaultDataKeyTypeList; bool Detector::SaveAll = false; //---------------------------------------------------------------------------------------------- //__Detector Constructor________________________________________________________________________ Detector::Detector() : G4VSensitiveDetector("MATHUSLA/MU/Flat") { collectionName.insert("Flat_HC"); for (auto& layer : _layers) layer->Register(this); } //---------------------------------------------------------------------------------------------- //__Initalize Event_____________________________________________________________________________ void Detector::Initialize(G4HCofThisEvent* event) { _hit_collection = Tracking::GenerateHitCollection(this, event); } //---------------------------------------------------------------------------------------------- //__Hit Processing______________________________________________________________________________ G4bool Detector::ProcessHits(G4Step* step, G4TouchableHistory*) { _hit_collection->insert(new Tracking::Hit(step)); return true; } //---------------------------------------------------------------------------------------------- //__Post-Event Processing_______________________________________________________________________ void Detector::EndOfEvent(G4HCofThisEvent*) { if (verboseLevel >= 2 && _hit_collection) std::cout << *_hit_collection; } //---------------------------------------------------------------------------------------------- //__Build Detector______________________________________________________________________________ G4VPhysicalVolume* Detector::Construct(G4LogicalVolume* world) { Scintillator::Material::Define(); _layers.clear(); constexpr double total_outer_box_height = 6000*mm; auto DetectorVolume = Construction::BoxVolume( "Flat", 2800*mm, 2800*mm, total_outer_box_height); const auto S1 = new Scintillator("S1", 2500*mm, 25*mm, 35*mm, 15*mm); auto L1 = new Layer("L1", 90, S1); auto L2 = new Layer("L2", 90, S1); auto L3 = new Layer("L3", 90, S1); L1->PlaceIn(DetectorVolume, Construction::Transform(0, 0, 0*m, 1, 0, 0, 90*deg)); L2->PlaceIn(DetectorVolume, Construction::Transform(0, 0, 1*m, 1, 0, 0, 90*deg)); L3->PlaceIn(DetectorVolume, Construction::Transform(0, 0, 2*m, 1, 0, 0, 90*deg)); _layers = {L1, L2, L3}; return Construction::PlaceVolume(DetectorVolume, world, G4Translate3D(0, 0, -0.5*total_outer_box_height)); } //---------------------------------------------------------------------------------------------- //__Build Earth for Detector____________________________________________________________________ G4VPhysicalVolume* Detector::ConstructEarth(G4LogicalVolume* world) { return Earth::Construct(world); } //---------------------------------------------------------------------------------------------- } /* namespace Flat */ ///////////////////////////////////////////////////////////////////////// } } /* namespace MATHUSLA::MU */
42.973214
102
0.587368
Keegan-Humphrey
4eb5312eca593cd8d0a31e7057f95c78a920b03b
134,074
cpp
C++
src/framework/shared/irphandlers/pnp/pnpstatemachine.cpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
994
2015-03-18T21:37:07.000Z
2019-04-26T04:04:14.000Z
src/framework/shared/irphandlers/pnp/pnpstatemachine.cpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
9
2015-03-19T08:40:01.000Z
2019-03-24T22:54:51.000Z
src/framework/shared/irphandlers/pnp/pnpstatemachine.cpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
350
2015-03-19T04:29:46.000Z
2019-05-05T23:26:50.000Z
/*++ Copyright (c) Microsoft. All rights reserved. Module Name: PnpStateMachine.cpp Abstract: This module implements the PnP state machine for the driver framework. This code was split out from FxPkgPnp.cpp. Author: Environment: Both kernel and user mode Revision History: --*/ #include "pnppriv.hpp" #include <wdmguid.h> #include<ntstrsafe.h> extern "C" { #if defined(EVENT_TRACING) #include "PnpStateMachine.tmh" #endif } // // The PnP State Machine // // This state machine responds to several PnP events: // // AddDevice -- Always targets the same state // IRP_MN_START_DEVICE // IRP_MN_START_DEVICE Complete -- Handled on the way up the stack // IRP_MN_QUERY_REMOVE_DEVICE // IRP_MN_QUERY_STOP_DEVICE // IRP_MN_CANCEL_REMOVE_DEVICE // IRP_MN_CANCEL_STOP_DEVICE // IRP_MN_STOP_DEVICE // IRP_MN_REMOVE_DEVICE // IRP_MN_SURPRISE_REMOVE_DEVICE -- Always targets the same state // IRP_MN_EJECT // // Each state has an entry for each of these events, listing the // target state for each of them. // #if FX_STATE_MACHINE_VERIFY #define VALIDATE_PNP_STATE(_CurrentState, _NewState) \ ValidatePnpStateEntryFunctionReturnValue((_CurrentState), (_NewState)) #else #define VALIDATE_PNP_STATE(_CurrentState, _NewState) (0) #endif //FX_STATE_MACHINE_VERIFY // @@SMVERIFY_SPLIT_BEGIN const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpInitOtherStates[] = { { PnpEventQueryRemove, WdfDevStatePnpInitQueryRemove DEBUGGED_EVENT }, { PnpEventRemove, WdfDevStatePnpRemoved DEBUGGED_EVENT }, { PnpEventParentRemoved, WdfDevStatePnpRemoved DEBUGGED_EVENT }, { PnpEventSurpriseRemove, WdfDevStatePnpInitSurpriseRemoved DEBUGGED_EVENT }, { PnpEventEject, WdfDevStatePnpEjectHardware DEBUGGED_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpInitStartingOtherStates[] = { { PnpEventStartDeviceFailed, WdfDevStatePnpInit DEBUGGED_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpHardwareAvailableOtherStates[] = { { PnpEventPwrPolStartFailed, WdfDevStatePnpHardwareAvailablePowerPolicyFailed DEBUGGED_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpQueryStopPendingOtherStates[] = { { PnpEventCancelStop, WdfDevStatePnpQueryCanceled DEBUGGED_EVENT }, { PnpEventSurpriseRemove, WdfDevStatePnpQueriedSurpriseRemove TRAP_ON_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpRemovedPdoWaitOtherStates[] = { { PnpEventStartDevice, WdfDevStatePnpPdoRestart DEBUGGED_EVENT }, { PnpEventRemove, WdfDevStatePnpCheckForDevicePresence DEBUGGED_EVENT }, { PnpEventParentRemoved, WdfDevStatePnpPdoRemoved DEBUGGED_EVENT }, { PnpEventSurpriseRemove, WdfDevStatePnpRemovedPdoSurpriseRemoved DEBUGGED_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpRestartingOtherStates[] = { { PnpEventPwrPolStartFailed, WdfDevStatePnpHardwareAvailablePowerPolicyFailed DEBUGGED_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpStartedOtherStates[] = { { PnpEventQueryStop, WdfDevStatePnpQueryStopStaticCheck DEBUGGED_EVENT }, { PnpEventCancelStop, WdfDevStatePnpStartedCancelStop DEBUGGED_EVENT }, { PnpEventCancelRemove, WdfDevStatePnpStartedCancelRemove DEBUGGED_EVENT }, { PnpEventRemove, WdfDevStatePnpStartedRemoving DEBUGGED_EVENT }, { PnpEventSurpriseRemove, WdfDevStatePnpSurpriseRemoveIoStarted DEBUGGED_EVENT }, { PnpEventPowerUpFailed, WdfDevStatePnpFailedIoStarting DEBUGGED_EVENT }, { PnpEventPowerDownFailed, WdfDevStatePnpFailedPowerDown DEBUGGED_EVENT }, { PnpEventStartDevice, WdfDevStatePnpRestart DEBUGGED_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpQueryRemovePendingOtherStates[] = { { PnpEventCancelRemove, WdfDevStatePnpQueryCanceled DEBUGGED_EVENT }, { PnpEventSurpriseRemove, WdfDevStatePnpQueriedSurpriseRemove TRAP_ON_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpQueriedRemovingOtherStates[] = { { PnpEventPwrPolStopFailed, WdfDevStatePnpRemovingDisableInterfaces DEBUGGED_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpInitQueryRemoveOtherStates[] = { { PnpEventCancelRemove, WdfDevStatePnpInitQueryRemoveCanceled DEBUGGED_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpStoppedOtherStates[] = { { PnpEventSurpriseRemove, WdfDevStatePnpSurpriseRemove DEBUGGED_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpStoppedWaitForStartCompletionOtherStates[] = { { PnpEventStartDeviceFailed, WdfDevStatePnpFailed TRAP_ON_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpStartedStoppingOtherStates[] = { { PnpEventPwrPolStopFailed, WdfDevStatePnpFailedOwnHardware DEBUGGED_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpStartedStoppingFailedOtherStates[] = { { PnpEventPwrPolStopFailed, WdfDevStatePnpFailedOwnHardware TRAP_ON_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpEjectFailedOtherStates[] = { { PnpEventSurpriseRemove, WdfDevStatePnpSurpriseRemove TRAP_ON_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpStartedRemovingOtherStates[] = { { PnpEventPwrPolStopFailed, WdfDevStatePnpRemovingDisableInterfaces DEBUGGED_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpFailedPowerDownOtherStates[] = { { PnpEventPwrPolStopFailed, WdfDevStatePnpFailedOwnHardware DEBUGGED_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpFailedIoStartingOtherStates[] = { { PnpEventPwrPolStopFailed, WdfDevStatePnpFailedOwnHardware DEBUGGED_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpFailedWaitForRemoveOtherStates[] = { { PnpEventSurpriseRemove, WdfDevStatePnpFailedSurpriseRemoved DEBUGGED_EVENT }, { PnpEventStartDevice, WdfDevStatePnpFailedStarted TRAP_ON_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpRestartOtherStates[] = { { PnpEventPwrPolStopFailed, WdfDevStatePnpHardwareAvailablePowerPolicyFailed DEBUGGED_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpRestartReleaseHardware[] = { { PnpEventStartDeviceFailed, WdfDevStatePnpFailed TRAP_ON_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_EVENT_TARGET_STATE FxPkgPnp::m_PnpRestartHardwareAvailableOtherStates[] = { { PnpEventPwrPolStartFailed, WdfDevStatePnpHardwareAvailablePowerPolicyFailed DEBUGGED_EVENT }, { PnpEventNull, WdfDevStatePnpNull }, }; const PNP_STATE_TABLE FxPkgPnp::m_WdfPnpStates[] = { // State function // First transition event & state // Other transition events & states // state info // WdfDevStatePnpObjectCreated { NULL, { PnpEventAddDevice, WdfDevStatePnpInit DEBUGGED_EVENT }, NULL, { TRUE, 0 }, }, // WdfDevStatePnpCheckForDevicePresence { FxPkgPnp::PnpEventCheckForDevicePresence, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpEjectFailed { NULL, { PnpEventStartDevice, WdfDevStatePnpPdoRestart DEBUGGED_EVENT }, FxPkgPnp::m_PnpEjectFailedOtherStates, { TRUE, 0 }, }, // WdfDevStatePnpEjectHardware { FxPkgPnp::PnpEventEjectHardware, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpEjectedWaitingForRemove { NULL, { PnpEventRemove, WdfDevStatePnpPdoRemoved DEBUGGED_EVENT }, NULL, { TRUE, PnpEventSurpriseRemove }, // can receive this if parent is surprise // removed while the ejected pdo is waiting // for remove. }, // WdfDevStatePnpInit { NULL, { PnpEventStartDevice, WdfDevStatePnpInitStarting DEBUGGED_EVENT }, FxPkgPnp::m_PnpInitOtherStates, { TRUE, PnpEventStartDevice }, }, // WdfDevStatePnpInitStarting { FxPkgPnp::PnpEventInitStarting, { PnpEventStartDeviceComplete, WdfDevStatePnpHardwareAvailable DEBUGGED_EVENT }, FxPkgPnp::m_PnpInitStartingOtherStates, { TRUE, 0 }, }, // WdfDevStatePnpInitSurpriseRemoved { FxPkgPnp::PnpEventInitSurpriseRemoved, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpHardwareAvailable { FxPkgPnp::PnpEventHardwareAvailable, { PnpEventPwrPolStarted, WdfDevStatePnpEnableInterfaces DEBUGGED_EVENT }, FxPkgPnp::m_PnpHardwareAvailableOtherStates, { FALSE, PnpEventPowerUpFailed }, }, // WdfDevStatePnpEnableInterfaces { FxPkgPnp::PnpEventEnableInterfaces, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpHardwareAvailablePowerPolicyFailed { FxPkgPnp::PnpEventHardwareAvailablePowerPolicyFailed, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpQueryRemoveAskDriver { FxPkgPnp::PnpEventQueryRemoveAskDriver, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpQueryRemovePending { FxPkgPnp::PnpEventQueryRemovePending, { PnpEventRemove, WdfDevStatePnpQueriedRemoving DEBUGGED_EVENT }, FxPkgPnp::m_PnpQueryRemovePendingOtherStates, { TRUE, 0, }, }, // WdfDevStatePnpQueryRemoveStaticCheck { FxPkgPnp::PnpEventQueryRemoveStaticCheck, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpQueriedRemoving, { FxPkgPnp::PnpEventQueriedRemoving, { PnpEventPwrPolStopped, WdfDevStatePnpRemovingDisableInterfaces DEBUGGED_EVENT }, FxPkgPnp::m_PnpQueriedRemovingOtherStates, { FALSE, PnpEventPowerDownFailed | // We ignore these power failed events because PnpEventPowerUpFailed // they will be translated into failed power // policy events. }, }, // WdfDevStatePnpQueryStopAskDriver { FxPkgPnp::PnpEventQueryStopAskDriver, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpQueryStopPending { FxPkgPnp::PnpEventQueryStopPending, { PnpEventStop, WdfDevStatePnpStartedStopping DEBUGGED_EVENT }, FxPkgPnp::m_PnpQueryStopPendingOtherStates, { TRUE, 0, }, }, // WdfDevStatePnpQueryStopStaticCheck { FxPkgPnp::PnpEventQueryStopStaticCheck, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpQueryCanceled, { FxPkgPnp::PnpEventQueryCanceled, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpRemoved { FxPkgPnp::PnpEventRemoved, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpPdoRemoved { FxPkgPnp::PnpEventPdoRemoved, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpRemovedPdoWait { FxPkgPnp::PnpEventRemovedPdoWait, { PnpEventEject, WdfDevStatePnpEjectHardware DEBUGGED_EVENT }, FxPkgPnp::m_PnpRemovedPdoWaitOtherStates, { TRUE, PnpEventCancelRemove | // Amazingly enough, you can get a cancel q.r. // on a PDO without seeing the query remove if // the stack is partially built PnpEventQueryRemove | // Can get a query remove from the removed state // when installing a PDO that is disabled PnpEventPowerDownFailed // We may get this for a PDO if implicit power // down callbacks were failed. The failed power // policy stop event took care of rundown. }, }, // WdfDevStatePnpRemovedPdoSurpriseRemoved { FxPkgPnp::PnpEventRemovedPdoSurpriseRemoved, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpRemovingDisableInterfaces { FxPkgPnp::PnpEventRemovingDisableInterfaces, { PnpEventPwrPolRemoved, WdfDevStatePnpRemoved DEBUGGED_EVENT }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpRestarting { FxPkgPnp::PnpEventRestarting, { PnpEventPwrPolStarted, WdfDevStatePnpStarted DEBUGGED_EVENT }, FxPkgPnp::m_PnpRestartingOtherStates, { FALSE, PnpEventPowerUpFailed }, }, // WdfDevStatePnpStarted { FxPkgPnp::PnpEventStarted, { PnpEventQueryRemove, WdfDevStatePnpQueryRemoveStaticCheck DEBUGGED_EVENT }, FxPkgPnp::m_PnpStartedOtherStates, { TRUE, 0, }, }, // WdfDevStatePnpStartedCancelStop { FxPkgPnp::PnpEventStartedCancelStop, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpStartedCancelRemove { FxPkgPnp::PnpEventStartedCancelRemove, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpStartedRemoving { FxPkgPnp::PnpEventStartedRemoving, { PnpEventPwrPolStopped, WdfDevStatePnpRemovingDisableInterfaces DEBUGGED_EVENT }, FxPkgPnp::m_PnpStartedRemovingOtherStates, { TRUE, PnpEventPowerUpFailed | // device was idled out and in Dx when we got removed // and this event is due to the power up that occured // to move it into D0 so it could be disarmed PnpEventPowerDownFailed }, }, // WdfDevStatePnpStartingFromStopped { FxPkgPnp::PnpEventStartingFromStopped, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpStopped { FxPkgPnp::PnpEventStopped, { PnpEventStartDevice, WdfDevStatePnpStoppedWaitForStartCompletion DEBUGGED_EVENT }, FxPkgPnp::m_PnpStoppedOtherStates, { TRUE, 0, }, }, // WdfDevStatePnpStoppedWaitForStartCompletion { FxPkgPnp::PnpEventStoppedWaitForStartCompletion, { PnpEventStartDeviceComplete, WdfDevStatePnpStartingFromStopped DEBUGGED_EVENT }, FxPkgPnp::m_PnpStoppedWaitForStartCompletionOtherStates, { TRUE, 0 }, }, // WdfDevStatePnpStartedStopping { FxPkgPnp::PnpEventStartedStopping, { PnpEventPwrPolStopped, WdfDevStatePnpStopped DEBUGGED_EVENT }, FxPkgPnp::m_PnpStartedStoppingOtherStates, { TRUE, PnpEventPowerUpFailed | // device was idled out and in Dx when we got stopped // and this event is due to the power up that occured // to move it into D0 so it could be disarmed PnpEventPowerDownFailed }, }, // The function is named PnpEventSurpriseRemoved with a 'd' because // PnpEventSurpriseRemove (no 'd') is an event name // WdfDevStatePnpSurpriseRemove { FxPkgPnp::PnpEventSurpriseRemoved, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpInitQueryRemove { FxPkgPnp::PnpEventInitQueryRemove, { PnpEventRemove, WdfDevStatePnpRemoved DEBUGGED_EVENT }, FxPkgPnp::m_PnpInitQueryRemoveOtherStates, { TRUE, 0 }, }, // WdfDevStatePnpInitQueryRemoveCanceled { FxPkgPnp::PnpEventInitQueryRemoveCanceled, { PnpEventNull, WdfDevStatePnpNull }, NULL, { TRUE, 0 }, }, // WdfDevStatePnpFdoRemoved { FxPkgPnp::PnpEventFdoRemoved, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpRemovedWaitForChildren { NULL, { PnpEventChildrenRemovalComplete, WdfDevStatePnpRemovedChildrenRemoved DEBUGGED_EVENT }, NULL, { TRUE, PnpEventPowerDownFailed // device power down even from processing remove }, }, // WdfDevStatePnpQueriedSurpriseRemove { FxPkgPnp::PnpEventQueriedSurpriseRemove, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpSurpriseRemoveIoStarted { FxPkgPnp::PnpEventSurpriseRemoveIoStarted, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpFailedPowerDown { FxPkgPnp::PnpEventFailedPowerDown, { PnpEventPwrPolStopped, WdfDevStatePnpFailedOwnHardware DEBUGGED_EVENT }, FxPkgPnp::m_PnpFailedPowerDownOtherStates, { FALSE, PnpEventPowerDownFailed , }, }, // WdfDevStatePnpFailedIoStarting { FxPkgPnp::PnpEventFailedIoStarting, { PnpEventPwrPolStopped, WdfDevStatePnpFailedOwnHardware DEBUGGED_EVENT }, FxPkgPnp::m_PnpFailedIoStartingOtherStates, { FALSE, PnpEventPowerDownFailed | PnpEventPowerUpFailed // if the device idled out and then failed // d0 entry, the power up failed can be passed // up by the IoInvalidateDeviceRelations and // subsequence surprise remove event. }, }, // WdfDevStatePnpFailedOwnHardware { FxPkgPnp::PnpEventFailedOwnHardware, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpFailed { FxPkgPnp::PnpEventFailed, { PnpEventPwrPolRemoved, WdfDevStatePnpFailedPowerPolicyRemoved DEBUGGED_EVENT }, NULL, { FALSE, 0, }, }, // WdfDevStatePnpFailedSurpriseRemoved { FxPkgPnp::PnpEventFailedSurpriseRemoved, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0, }, }, // WdfDevStatePnpFailedStarted { FxPkgPnp::PnpEventFailedStarted, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0, }, }, // WdfDevStatePnpFailedWaitForRemove, { NULL, { PnpEventRemove, WdfDevStatePnpRemoved DEBUGGED_EVENT }, FxPkgPnp::m_PnpFailedWaitForRemoveOtherStates, { TRUE, PnpEventPowerUpFailed | // initial power up failed, power policy start // failed event moved the state machine to the // failed state first PnpEventPowerDownFailed | // implicitD3 power down failed PnpEventQueryRemove | // start succeeded, but we still get a query in // the removed case PnpEventCancelStop | // power down failure while processing query stop // and q.s. irp completed with error PnpEventCancelRemove // power down failure while processing query remove // and q.r. irp completed with error }, }, // WdfDevStatePnpFailedInit { FxPkgPnp::PnpEventFailedInit, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpPdoInitFailed { FxPkgPnp::PnpEventPdoInitFailed, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpRestart { FxPkgPnp::PnpEventRestart, { PnpEventPwrPolStopped, WdfDevStatePnpRestartReleaseHardware DEBUGGED_EVENT }, FxPkgPnp::m_PnpRestartOtherStates, { FALSE, PnpEventPowerUpFailed | // when stopping power policy, device was in // Dx and bringing it to D0 succeeded or failed PnpEventPowerDownFailed // same as power up }, }, // WdfDevStatePnpRestartReleaseHardware { FxPkgPnp::PnpEventRestartReleaseHardware, { PnpEventStartDeviceComplete, WdfDevStatePnpRestartHardwareAvailable DEBUGGED_EVENT }, FxPkgPnp::m_PnpRestartReleaseHardware, { TRUE, PnpEventPowerDownFailed // the previous pwr policy stop // in WdfDevStaePnpRestart will // cause these events to show up here }, }, // WdfDevStatePnpRestartHardwareAvailable { FxPkgPnp::PnpEventRestartHardwareAvailable, { PnpEventPwrPolStarted, WdfDevStatePnpStarted DEBUGGED_EVENT }, FxPkgPnp::m_PnpRestartHardwareAvailableOtherStates, { TRUE, PnpEventPowerUpFailed }, }, // WdfDevStatePnpPdoRestart { FxPkgPnp::PnpEventPdoRestart, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpFinal { FxPkgPnp::PnpEventFinal, { PnpEventNull, WdfDevStatePnpNull }, NULL, { TRUE, PnpEventPowerDownFailed, // on the final implicit power down, a // callback returned !NT_SUCCESS }, }, // WdfDevStatePnpRemovedChildrenRemoved { FxPkgPnp::PnpEventRemovedChildrenRemoved, { PnpEventNull, WdfDevStatePnpNull }, NULL, { TRUE, 0 } , }, // WdfDevStatePnpQueryRemoveEnsureDeviceAwake { FxPkgPnp::PnpEventQueryRemoveEnsureDeviceAwake, { PnpEventDeviceInD0, WdfDevStatePnpQueryRemovePending DEBUGGED_EVENT }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpQueryStopEnsureDeviceAwake { FxPkgPnp::PnpEventQueryStopEnsureDeviceAwake, { PnpEventDeviceInD0, WdfDevStatePnpQueryStopPending DEBUGGED_EVENT }, NULL, { FALSE, 0 }, }, // WdfDevStatePnpFailedPowerPolicyRemoved { FxPkgPnp::PnpEventFailedPowerPolicyRemoved, { PnpEventNull, WdfDevStatePnpNull }, NULL, { FALSE, 0 } , }, }; // @@SMVERIFY_SPLIT_END VOID FxPkgPnp::PnpCheckAssumptions( VOID ) /*++ Routine Description: This routine is never actually called by running code, it just has WDFCASSERTs who upon failure, would not allow this file to be compiled. DO NOT REMOVE THIS FUNCTION just because it is not callec by any running code. Arguments: None Return Value: None --*/ { WDFCASSERT(sizeof(FxPnpStateInfo) == sizeof(ULONG)); WDFCASSERT((sizeof(m_WdfPnpStates)/sizeof(m_WdfPnpStates[0])) == (WdfDevStatePnpNull - WdfDevStatePnpObjectCreated)); // we assume these are the same length when we update the history index WDFCASSERT((sizeof(m_PnpMachine.m_Queue)/sizeof(m_PnpMachine.m_Queue[0])) == (sizeof(m_PnpMachine.m_States.History)/ sizeof(m_PnpMachine.m_States.History[0]))); } /*++ The locking model for the PnP state machine requires that events be enqueued possibly at DISPATCH_LEVEL. It also requires that the PnP state machine be runnable at PASSIVE_LEVEL. Consequently, we have two locks, one DISPATCH_LEVEL lock that guards the event queue and one PASSIVE_LEVEL lock that guards the state machine itself. Algorithm: 1) Acquire the PnP queue lock. 2) Enqueue the request. Requests are put at the end of the queue, except if they are PowerUp, or PowerDown, in which case they are put at the head of the queue. 3) Drop the PnP queue lock. 4) If the thread is running at PASSIVE_LEVEL, skip to step 6. 5) Queue a work item onto any work queue. 6) Attempt to acquire the state machine lock, with a near-zero-length timeout. 7) If successful, skip to step 10. 8) Queue a work item onto any work queue. 9) Acquire the state machine lock. 10) Acquire the PnP queue lock. 11) Attempt to dequeue an event. 12) Drop the PnP queue lock. 13) If there was no event to dequeue, drop the state machine lock and exit. 14) Execute the state handler. This may involve taking one of the other state machine queue locks, briefly, to deliver an event. 15) Go to Step 10. Implementing this algorithm requires three functions. PnpProcessEvent -- Implements steps 1-8. _PnpProcessEventInner -- Implements step 9. PnpProcessEventInner -- Implements steps 10-15. --*/ VOID FxPkgPnp::PnpProcessEvent( __in FxPnpEvent Event, __in BOOLEAN ProcessOnDifferentThread ) /*++ Routine Description: This function implements steps 1-8 of the algorithm described above. Arguments: Event - Current PnP event Return Value: NTSTATUS --*/ { NTSTATUS status; KIRQL oldIrql; // // Take the lock, raising to DISPATCH_LEVEL. // m_PnpMachine.Lock(&oldIrql); if (m_PnpMachine.IsFull()) { DoTraceLevelMessage( GetDriverGlobals(), TRACE_LEVEL_INFORMATION, TRACINGPNP, "WDFDEVICE 0x%p !devobj 0x%p current pnp state %!WDF_DEVICE_PNP_STATE! " "dropping event %!FxPnpEvent! because of a full queue", m_Device->GetHandle(), m_Device->GetDeviceObject(), m_Device->GetDevicePnpState(), Event); // // The queue is full. Bail. // m_PnpMachine.Unlock(oldIrql); ASSERT(!"The PnP queue is full. This shouldn't be able to happen."); return; } if (m_PnpMachine.IsClosedLocked()) { DoTraceLevelMessage( GetDriverGlobals(), TRACE_LEVEL_INFORMATION, TRACINGPNP, "WDFDEVICE 0x%p !devobj 0x%p current pnp state %!WDF_DEVICE_PNP_STATE! " "dropping event %!FxPnpEvent! because of a closed queue", m_Device->GetHandle(), m_Device->GetDeviceObject(), m_Device->GetDevicePnpState(), Event); // // The queue is closed. Bail // m_PnpMachine.Unlock(oldIrql); return; } // // Enqueue the event. Whether the event goes on the front // or the end of the queue depends on which event it is. // if (Event & PnpPriorityEventsMask) { // // Stick it on the front of the queue, making it the next // event that will be processed. // m_PnpMachine.m_Queue[m_PnpMachine.InsertAtHead()] = Event; } else { // // Stick it on the end of the queue. // m_PnpMachine.m_Queue[m_PnpMachine.InsertAtTail()] = Event; } // // Drop the lock. // m_PnpMachine.Unlock(oldIrql); // // Now, if we are running at PASSIVE_LEVEL, attempt to run the state // machine on this thread. If we can't do that, then queue a work item. // if (FALSE == ShouldProcessPnpEventOnDifferentThread( oldIrql, ProcessOnDifferentThread )) { LONGLONG timeout = 0; status = m_PnpMachine.m_StateMachineLock.AcquireLock(GetDriverGlobals(), &timeout); if (FxWaitLockInternal::IsLockAcquired(status)) { FxPostProcessInfo info; // // We now hold the state machine lock. So call the function that // dispatches the next state. // PnpProcessEventInner(&info); m_PnpMachine.m_StateMachineLock.ReleaseLock(GetDriverGlobals()); info.Evaluate(this); return; } } // // For one reason or another, we couldn't run the state machine on this // thread. So queue a work item to do it. If m_PnPWorkItemEnqueuing // is non-zero, that means that the work item is already being enqueued // on another thread. This is significant, since it means that we can't do // anything with the work item on this thread, but it's okay, since the // work item will pick up our work and do it. // m_PnpMachine.QueueToThread(); } VOID FxPkgPnp::_PnpProcessEventInner( __inout FxPkgPnp* This, __inout FxPostProcessInfo* Info, __in PVOID WorkerContext ) { UNREFERENCED_PARAMETER(WorkerContext); // // Take the state machine lock. // This->m_PnpMachine.m_StateMachineLock.AcquireLock( This->GetDriverGlobals() ); // // Call the function that will actually run the state machine. // This->PnpProcessEventInner(Info); // // We are being called from the work item and m_WorkItemRunning is > 0, so // we cannot be deleted yet. // ASSERT(Info->SomethingToDo() == FALSE); // // Now release the lock // This->m_PnpMachine.m_StateMachineLock.ReleaseLock( This->GetDriverGlobals() ); } VOID FxPkgPnp::PnpProcessEventInner( __inout FxPostProcessInfo* Info ) /*++ Routine Description: This routine runs the state machine. It implements steps 10-15 of the algorithm described above. --*/ { WDF_DEVICE_PNP_STATE newState; CPPNP_STATE_TABLE entry; FxPnpEvent event; KIRQL oldIrql; // // Process as many events as we can. // for ( ; ; ) { entry = GetPnpTableEntry(m_Device->GetDevicePnpState()); // // Get an event from the queue. // m_PnpMachine.Lock(&oldIrql); if (m_PnpMachine.IsEmpty()) { m_PnpMachine.GetFinishedState(Info); if (m_PnpMachine.m_FireAndForget) { m_PnpMachine.m_FireAndForget = FALSE; Info->m_FireAndForgetIrp = ClearPendingPnpIrp(); ASSERT(Info->m_FireAndForgetIrp != NULL); } Info->m_SetRemovedEvent = m_SetDeviceRemoveProcessed; m_SetDeviceRemoveProcessed = FALSE; // // The queue is empty. // m_PnpMachine.Unlock(oldIrql); return; } event = m_PnpMachine.m_Queue[m_PnpMachine.GetHead()]; // // At this point, we need to determine whether we can process this // event. // if (event & PnpPriorityEventsMask) { // // These are always possible to handle. // DO_NOTHING(); } else { // // Check to see if this state can handle new events. // if (entry->StateInfo.Bits.QueueOpen == FALSE) { // // This state can't handle new events. // m_PnpMachine.Unlock(oldIrql); return; } } m_PnpMachine.IncrementHead(); m_PnpMachine.Unlock(oldIrql); // // Find the entry in the PnP state table that corresponds // to this event. // newState = WdfDevStatePnpNull; if (entry->FirstTargetState.PnpEvent == event) { newState = entry->FirstTargetState.TargetState; DO_EVENT_TRAP(&entry->FirstTargetState); } else if (entry->OtherTargetStates != NULL) { ULONG i = 0; for (i = 0; entry->OtherTargetStates[i].PnpEvent != PnpEventNull; i++) { if (entry->OtherTargetStates[i].PnpEvent == event) { newState = entry->OtherTargetStates[i].TargetState; DO_EVENT_TRAP(&entry->OtherTargetStates[i]); break; } } } if (newState == WdfDevStatePnpNull) { DoTraceLevelMessage( GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGPNP, "WDFDEVICE 0x%p !devobj 0x%p current pnp state " "%!WDF_DEVICE_PNP_STATE! dropping event %!FxPnpEvent!", m_Device->GetHandle(), m_Device->GetDeviceObject(), m_Device->GetDevicePnpState(), event); if ((entry->StateInfo.Bits.KnownDroppedEvents & event) == 0) { COVERAGE_TRAP(); DoTraceLevelMessage( GetDriverGlobals(), TRACE_LEVEL_WARNING, TRACINGPNP, "WDFDEVICE 0x%p !devobj %p current state " "%!WDF_DEVICE_PNP_STATE!, policy event %!FxPnpEvent! is not" " a known dropped event, known dropped events are " "%!FxPnpEvent!", m_Device->GetHandle(), m_Device->GetDeviceObject(), m_Device->GetDevicePnpState(), event, entry->StateInfo.Bits.KnownDroppedEvents); // DIAG: add diag code here } // // This state doesn't respond to the Event. Make sure we do not // drop an event which pends a pnp irp on the floor though. // if (event & PnpEventPending) { // // In the case of a previous power up/down failure, the following // can happen // 1 invalidate device relations // 2 failure event is posted to pnp state machine // 3 process power failure event first, but while processing, // query device state is completed, and failed /removed is reported // 4 surprise remove comes, the irp is queued, the event is queued // 5 processing of power failure event continues, gets to // Failed and completes the s.r irp // 6 the surprise remove event is processed (the current value // of the local var event), but since we are already in the // Failed state, we ignore this event and end up // here. // // This means that if we are processing surprise remove, we cannot // 100% expect that an irp has been pended. // PnpFinishProcessingIrp( (event == PnpEventSurpriseRemove) ? FALSE : TRUE); } else { DO_NOTHING(); } } else { // // Now enter the new state. // PnpEnterNewState(newState); } } } VOID FxPkgPnp::PnpEnterNewState( __in WDF_DEVICE_PNP_STATE State ) /*++ Routine Description: This function looks up the handler for a state and then calls it. Arguments: Event - Current PnP event Return Value: None. --*/ { CPPNP_STATE_TABLE entry; WDF_DEVICE_PNP_STATE currentState, newState; WDF_DEVICE_PNP_NOTIFICATION_DATA data; currentState = m_Device->GetDevicePnpState(); newState = State; while (newState != WdfDevStatePnpNull) { DoTraceLevelMessage( GetDriverGlobals(), TRACE_LEVEL_INFORMATION, TRACINGPNPPOWERSTATES, "WDFDEVICE 0x%p !devobj 0x%p entering PnP State " "%!WDF_DEVICE_PNP_STATE! from %!WDF_DEVICE_PNP_STATE!", m_Device->GetHandle(), m_Device->GetDeviceObject(), newState, currentState); if (m_PnpStateCallbacks != NULL) { // // Callback for leaving the old state // RtlZeroMemory(&data, sizeof(data)); data.Type = StateNotificationLeaveState; data.Data.LeaveState.CurrentState = currentState; data.Data.LeaveState.NewState = newState; m_PnpStateCallbacks->Invoke(currentState, StateNotificationLeaveState, m_Device->GetHandle(), &data); } m_PnpMachine.m_States.History[m_PnpMachine.IncrementHistoryIndex()] = (USHORT) newState; if (m_PnpStateCallbacks != NULL) { // // Callback for entering the new state // RtlZeroMemory(&data, sizeof(data)); data.Type = StateNotificationEnterState; data.Data.EnterState.CurrentState = currentState; data.Data.EnterState.NewState = newState; m_PnpStateCallbacks->Invoke(newState, StateNotificationEnterState, m_Device->GetHandle(), &data); } m_Device->SetDevicePnpState(newState); currentState = newState; entry = GetPnpTableEntry(currentState); // // Call the state handler if one is present and record our new state // if (entry->StateFunc != NULL) { newState = entry->StateFunc(this); // // Validate the return value if FX_STATE_MACHINE_VERIFY is enabled // VALIDATE_PNP_STATE(currentState, newState); } else { newState = WdfDevStatePnpNull; } if (m_PnpStateCallbacks != NULL) { // // Callback for post processing the new state // RtlZeroMemory(&data, sizeof(data)); data.Type = StateNotificationPostProcessState; data.Data.PostProcessState.CurrentState = currentState; m_PnpStateCallbacks->Invoke(currentState, StateNotificationPostProcessState, m_Device->GetHandle(), &data); } } } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventCheckForDevicePresence( __inout FxPkgPnp* This ) /*++ Routine Description: This function implements the Check For Device Presence state. This is a state that is specific to PDOs, so this function should be overloaded by the PDO class and never called. Arguments: none Return Value: VOID --*/ { return This->PnpEventCheckForDevicePresenceOverload(); } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventEjectHardware( __inout FxPkgPnp* This ) /*++ Routine Description: This function implements the Eject Hardware state. This is a state that is specific to PDOs, so this function should be overloaded by the PDO class and never called. Arguments: none Return Value: VOID --*/ { return This->PnpEventEjectHardwareOverload(); } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventInitStarting( __inout FxPkgPnp* This ) /*++ Routine Description: The device is recieving a start for the first time. The start is on the way down the stack. Arguments: This - instance of the state machine Return Value: new machine state --*/ { if (This->PnpSendStartDeviceDownTheStackOverload() == FALSE) { // // Start was sent asynchronously down the stack, the irp's completion // routine will move the state machine to the new state. // return WdfDevStatePnpNull; } return WdfDevStatePnpHardwareAvailable; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventInitSurpriseRemoved( __inout FxPkgPnp* This ) /*++ Routine Description: This transition should only occur for a PDO. The device was initialized, but then it's parent bus was surprise removed. Complete the surprise remove and wait for the remove. Arguments: This - instance of the state machine Return Value: WdfDevStatePnpInit --*/ { This->PnpFinishProcessingIrp(TRUE); return WdfDevStatePnpInit; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventHardwareAvailable( __inout FxPkgPnp* This ) /*++ Routine Description: This function implements the Hardware Available state. Arguments: none Return Value: VOID --*/ { NTSTATUS status; BOOLEAN matched; FxCxCallbackProgress progress = FxCxCallbackProgressInitialized; status = STATUS_SUCCESS; matched = FALSE; status = This->QueryForReenumerationInterface(); if (NT_SUCCESS(status)) { status = This->CreatePowerThreadIfNeeded(); } if (NT_SUCCESS(status)) { status = This->PnpPrepareHardware(&matched, &progress); } if (!NT_SUCCESS(status)) { if ((matched == FALSE) || (progress < FxCxCallbackProgressClientCalled)) { // // NOTE: consider going to WdfDevStatePnpFailed instead of yet // another failed state out of start device handling. // // // We can handle remove out of the init state, revert back to that // state. // return WdfDevStatePnpFailedInit; } else { // // EvtDevicePrepareHardware is what failed, goto a state where we // undo that call. // return WdfDevStatePnpFailedOwnHardware; } } // // We only query for the capabilities for the power policy owner because // we use the capabilities to determine the right Dx state when we want to // wake from S0 or Sx. Since only the power policy owner can enable wake // behavior, only the owner needs to query for the information. // // ALSO, if we are a filter, there are issues in stacks wrt pnp reentrancy. // if (This->IsPowerPolicyOwner()) { // // Query the stack for capabilities before telling the stack hw is // available // status = This->QueryForCapabilities(); if (!NT_SUCCESS(status)) { DoTraceLevelMessage( This->GetDriverGlobals(), TRACE_LEVEL_ERROR, TRACINGPNP, "could not query caps for stack, %!STATUS!", status); This->SetPendingPnpIrpStatus(status); return WdfDevStatePnpFailedOwnHardware; } This->m_CapsQueried = TRUE; } This->PnpPowerPolicyStart(); return WdfDevStatePnpNull; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventEnableInterfaces( __inout FxPkgPnp* This ) /*++ Routine Description: The device has powered up and fully started, now enable the device interfaces and WMI. We wait until the last possible moment because on win2k WMI registration is not synchronized with the completion of start device, so if we register WMI early in start device processing, we could get wmi requests while we are initializing, which is a race condition we want to eliminate. Arguments: This - instance of the state machine Return Value: new state --*/ { NTSTATUS status; status = This->PnpEnableInterfacesAndRegisterWmi(); if (!NT_SUCCESS(status)) { // // Upon failure, PnpEnableInterfacesAndRegisterWmi already marked the // irp as failed and recorded an internal error. // // FailedPowerDown will gracefully tear down the stack and bring it out // of D0. // return WdfDevStatePnpFailedPowerDown; } return WdfDevStatePnpStarted; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventHardwareAvailablePowerPolicyFailed( __inout FxPkgPnp* This ) /*++ Routine Description: Our previous state called PowerPolicyStart or PowerPolicyStopRemove and the power state machine could not perform the requested action. We still have a start irp pending, so set its status and then proceed down the start failure path. Arguments: This - instance of the state machine Return Value: WdfDevStatePnpFailedOwnHardware --*/ { This->SetPendingPnpIrpStatus(STATUS_DEVICE_POWER_FAILURE); return WdfDevStatePnpFailedOwnHardware; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventQueryRemoveAskDriver( __inout FxPkgPnp* This ) /*++ Routine Description: This function implements the Query Remove Ask Driver state. It's job is to invoke EvtDeviceQueryRemove and then complete the QueryRemove IRP if needed. Arguments: This - instance of the state machine Return Value: new state --*/ { WDF_DEVICE_PNP_STATE state; NTSTATUS status; // // First, call the driver. If it succeeds, look at whether // it managed to stop its stuff. // status = This->m_DeviceQueryRemove.Invoke(This->m_Device->GetHandle()); if (NT_SUCCESS(status)) { // // The driver has stopped all of its self managed io. Proceed to // stop everything before passing the request down the stack. // state = WdfDevStatePnpQueryRemoveEnsureDeviceAwake; } else { // // The callback didn't manage to stop. Go back to the Started state // where we will complete the pended pnp irp // DoTraceLevelMessage( This->GetDriverGlobals(), TRACE_LEVEL_ERROR, TRACINGPNP, "EvtDeviceQueryRemove failed, %!STATUS!", status); if (status == STATUS_NOT_SUPPORTED) { DoTraceLevelMessage( This->GetDriverGlobals(), TRACE_LEVEL_ERROR, TRACINGPNP, "EvtDeviceQueryRemove returned an invalid status " "STATUS_NOT_SUPPORTED"); if (This->GetDriverGlobals()->IsVerificationEnabled(1, 11, OkForDownLevel)) { FxVerifierDbgBreakPoint(This->GetDriverGlobals()); } } state = WdfDevStatePnpStarted; } This->SetPendingPnpIrpStatus(status); return state; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventQueryRemoveEnsureDeviceAwake( __inout FxPkgPnp *This ) /*++ Routine Description: This function brings the device to a working state if it is idle. If the device is already in working state, it ensures that it does not idle out. Arguments: This - instance of the state machine Return Value: new state --*/ { NTSTATUS status; WDF_DEVICE_PNP_STATE state; // // Make sure that the device is powered on before we send the query remove // on its way. If we do this after we send the query remove, we could race // with the remove which removes the reference and we want the device // powered on when processing remove. // status = This->PnpPowerReferenceDuringQueryPnp(); if (STATUS_PENDING == status) { // // Device is transitioning to D0. The Pnp state machine will wait in // the current state until the transition is complete // state = WdfDevStatePnpNull; } else if (NT_SUCCESS(status)) { // // Already in D0 // state = WdfDevStatePnpQueryRemovePending; } else { DoTraceLevelMessage( This->GetDriverGlobals(), TRACE_LEVEL_ERROR, TRACINGPNP, "StopIdle on WDFDEVICE %p failed, %!STATUS!, failing query remove", This->m_Device->GetHandle(), status); This->SetPendingPnpIrpStatus(status); // // The Started state will complete the irp when it sees the failure // status set on the irp. // state = WdfDevStatePnpStarted; } return state; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventQueryRemovePending( __inout FxPkgPnp* This ) /*++ Routine Description: The device has fully stopped. Let go of the query remove irp. Arguments: This - instance of the state machine for this device Return Value: WdfDevStatePnpNull --*/ { FxIrp irp; irp.SetIrp(This->ClearPendingPnpIrp()); (void) This->FireAndForgetIrp(&irp); return WdfDevStatePnpNull; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventQueryRemoveStaticCheck( __inout FxPkgPnp* This ) /*++ Routine Description: This function implements the Query Remove Static Check state. It's job is to determine whether this device, in general, can stop. If it can, then we proceed on to Query Remove Ask Driver. If not, then we go to back to Started. Arguments: none Return Value: VOID --*/ { NTSTATUS status; BOOLEAN completeQuery; completeQuery = TRUE; if (This->m_DeviceStopCount != 0) { DoTraceLevelMessage( This->GetDriverGlobals(), TRACE_LEVEL_INFORMATION, TRACINGPNP, "Failing QueryRemoveDevice because the driver " "has indicated that it cannot be stopped, count %d", This->m_DeviceStopCount); status = STATUS_INVALID_DEVICE_STATE; } else if (This->IsInSpecialUse()) { DoTraceLevelMessage( This->GetDriverGlobals(), TRACE_LEVEL_INFORMATION, TRACINGPNP, "Failing QueryRemoveDevice due to open special file counts " "(paging %d, hiber %d, dump %d, boot %d, guest assigned %d)", This->GetUsageCount(WdfSpecialFilePaging), This->GetUsageCount(WdfSpecialFileHibernation), This->GetUsageCount(WdfSpecialFileDump), This->GetUsageCount(WdfSpecialFileBoot), This->GetUsageCount(WdfSpecialFileGuestAssigned)); status = STATUS_DEVICE_NOT_READY; } else { // // Go on to next state in the "remove" progression. // completeQuery = FALSE; status = STATUS_SUCCESS; } if (completeQuery) { // // Store the status which Started will complete // This->SetPendingPnpIrpStatus(status); // // Revert to started // return WdfDevStatePnpStarted; } else { // // Wait for the other state machines to stop // return WdfDevStatePnpQueryRemoveAskDriver; } } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventQueriedRemoving( __inout FxPkgPnp* This ) /*++ Routine Description: The device was query removed and is now in the removed state. Arguments: This - instance of the state machine Return Value: WdfDevStatePnpNull --*/ { // // It is important to stop power policy before releasing the reference. // If the reference was released first, we could get into a situation where // we immediately go idle and then we must send a D0 irp when in the remove. // If there are devices on top of this device and we send a D0 irp during // remove processing, the upper devices will be sent an irp after getting a // pnp remove (and either crash or fail the power irp upon receiving it). // This->PnpPowerPolicyStop(); This->PnpPowerDereferenceSelf(); return WdfDevStatePnpNull; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventQueryStopAskDriver( __inout FxPkgPnp* This ) /*++ Routine Description: This function implements the Query Stop Ask Driver state. It's job is to invoke the EvtDeviceQueryStop callback and then complete the QueryStop IRP if needed. Arguments: This - instance of the state machine Return Value: new state --*/ { WDF_DEVICE_PNP_STATE state; NTSTATUS status; // // First, call the driver. If it succeeds, look at whether // it managed to stop its stuff. // status = This->m_DeviceQueryStop.Invoke(This->m_Device->GetHandle()); if (NT_SUCCESS(status)) { // // Tell the other state machines to stop // state = WdfDevStatePnpQueryStopEnsureDeviceAwake; } else { DoTraceLevelMessage( This->GetDriverGlobals(), TRACE_LEVEL_ERROR, TRACINGPNP, "EvtDeviceQueryStop failed, %!STATUS!", status); if (status == STATUS_NOT_SUPPORTED) { DoTraceLevelMessage( This->GetDriverGlobals(), TRACE_LEVEL_ERROR, TRACINGPNP, "EvtDeviceQueryStop returned an invalid status " "STATUS_NOT_SUPPORTED"); if (This->GetDriverGlobals()->IsVerificationEnabled(1, 11, OkForDownLevel)) { FxVerifierDbgBreakPoint(This->GetDriverGlobals()); } } // // The callback didn't manage to stop. Go back to the Started state. // state = WdfDevStatePnpStarted; } This->SetPendingPnpIrpStatus(status); return state; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventQueryStopEnsureDeviceAwake( __inout FxPkgPnp *This ) /*++ Routine Description: This function brings the device to a working state if it is idle. If the device is already in working state, it ensures that it does not idle out. Arguments: This - instance of the state machine Return Value: new state --*/ { NTSTATUS status; WDF_DEVICE_PNP_STATE state; // // Make sure that the device is powered on before we send the query stop // on its way. If we do this after we send the query stop, we could race // with the stop and we want the device powered on when processing stop. // status = This->PnpPowerReferenceDuringQueryPnp(); if (STATUS_PENDING == status) { // // Device is transitioning to D0. The Pnp state machine will wait in // the current state until the transition is complete // state = WdfDevStatePnpNull; } else if (NT_SUCCESS(status)) { // // Already in D0 // state = WdfDevStatePnpQueryStopPending; } else { DoTraceLevelMessage( This->GetDriverGlobals(), TRACE_LEVEL_ERROR, TRACINGPNP, "StopIdle on WDFDEVICE %p failed, %!STATUS!, failing query stop", This->m_Device->GetHandle(), status); This->SetPendingPnpIrpStatus(status); // // The Started state will complete the irp when it sees the failure // status set on the irp. // state = WdfDevStatePnpStarted; } return state; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventQueryStopPending( __inout FxPkgPnp* This ) /*++ Routine Description: Everything in the device has stopped due to the stop device irp. Complete it now Arguments: This - instance of the state machine Return Value: WdfDevStatePnpNull --*/ { FxIrp irp; irp.SetIrp(This->ClearPendingPnpIrp()); (void) This->FireAndForgetIrp(&irp); return WdfDevStatePnpNull; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventQueryStopStaticCheck( __inout FxPkgPnp* This ) /*++ Routine Description: This function implements the Query Stop Static Check state. It's job is to determine whether this device, in general, can stop. If it can, then we proceed on to Query Stop Ask Driver. Otherwise we will return to the Started state. If the driver has set that the state machine should ignore query stop/remove, the query will succeed, otherwise it will fail Arguments: This - instance of the state machine Return Value: new machine state --*/ { NTSTATUS status; BOOLEAN completeQuery = TRUE; if (This->m_DeviceStopCount != 0) { DoTraceLevelMessage( This->GetDriverGlobals(), TRACE_LEVEL_INFORMATION, TRACINGPNP, "Failing QueryStopDevice because the driver " "has indicated that it cannot be stopped, count %d", This->m_DeviceStopCount); status = STATUS_INVALID_DEVICE_STATE; } else if (This->IsInSpecialUse()) { DoTraceLevelMessage( This->GetDriverGlobals(), TRACE_LEVEL_INFORMATION, TRACINGPNP, "Failing QueryStopDevice due to open special file counts (paging %d," " hiber %d, dump %d, boot %d, guest assigned %d)", This->GetUsageCount(WdfSpecialFilePaging), This->GetUsageCount(WdfSpecialFileHibernation), This->GetUsageCount(WdfSpecialFileDump), This->GetUsageCount(WdfSpecialFileBoot), This->GetUsageCount(WdfSpecialFileGuestAssigned)); status = STATUS_DEVICE_NOT_READY; } else { // // Go on to next state in the "stop" progression. // status = STATUS_SUCCESS; completeQuery = FALSE; } if (completeQuery) { // // Set the state which started will complete the request with // This->SetPendingPnpIrpStatus(status); // // Revert to started // return WdfDevStatePnpStarted; } else { // // Go ask power what the self managed io state is // return WdfDevStatePnpQueryStopAskDriver; } } VOID FxPkgPnp::PnpEventRemovedCommonCode( VOID ) /*++ Routine Description: This function implements the Removed state. Arguments: none Return Value: VOID --*/ { // // Purge non power managed queues now // m_Device->m_PkgIo->StopProcessingForPower( FxIoStopProcessingForPowerPurgeNonManaged ); if (m_SelfManagedIoMachine != NULL) { m_SelfManagedIoMachine->Cleanup(); } // // Cleanup WMI *after* EvtDeviceSelfManagedIoCleanup b/c we want to cleanup // after a well known and documented time. The WMI docs state that you can // register providers and instances all the way through // EvtDeviceSelfManagedIoCleanup, so we mark WMI as cleaned up after that // call. // m_Device->WmiPkgCleanup(); // // Mark the device as removed. // m_PnpState.Value &= ~FxPnpStateRemovedMask; m_PnpState.Value |= FxPnpStateRemovedTrue; // // Now call the driver and tell it to cleanup all its software state. // // We do the dispose early here before deleting the object // since the PNP remove event is the main trigger for // the Dispose chain in the framework. // // (Almost everything in the driver is rooted on the device object) // m_Device->EarlyDispose(); // // All the children are in the disposed state, destroy them all. m_Device // is not destroyed in this call. // m_Device->DestroyChildren(); // // Wait for all children to drain out and cleanup. // m_Device->m_DisposeList->WaitForEmpty(); } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventQueryCanceled( __inout FxPkgPnp* This ) /*++ Routine Description: The device was in the queried state (remove or stop) and the query was canceled. Remove the power reference taken and return to the started state. Arguments: This - instance of the state machine Return Value: WdfDevStatePnpStarted --*/ { This->PnpPowerDereferenceSelf(); return WdfDevStatePnpStarted; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventRemoved( __inout FxPkgPnp* This ) /*++ Routine Description: This function implements the Removed state. It tears down any remaining children and the moves into a role (FDO/PDO) specific state. Arguments: This - instance of the state machine Return Value: new machine state --*/ { // // Remove any child PDOs which may still be lingering around. We do // the cleanup here so that we do it only once for the PDO which is being // removed (but may stick around) b/c it was not reported as missing. // // // Iterate over all of the reported children // This->ChildListNotifyRemove(&This->m_PendingChildCount); // // Decrement our bias from when the device was (re)started. If all of the // children removed themselves synchronously, we just move to the cleanup // state, otherwise wait for all the children to fully process the remove // before remove the parent so that ordering of removal between parent and // child is guaranteed (where the order is that all children are cleaned // up before the parent is cleaned up). // if (InterlockedDecrement(&This->m_PendingChildCount) > 0) { return WdfDevStatePnpRemovedWaitForChildren; } else { return WdfDevStatePnpRemovedChildrenRemoved; } } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventPdoRemoved( __inout FxPkgPnp* This ) /*++ Routine Description: This function implements the PDO Removed state. This function is called when the PDO is actually reported missing to the OS or the FDO is removed. Arguments: none Return Value: new state --*/ { return This->PnpEventPdoRemovedOverload(); } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventRemovedPdoWait( __inout FxPkgPnp* This ) /*++ Routine Description: Indicates to the remove path that remove processing is done and we will wait for additional PNP events to arrive at this state machine Arguments: This - Instance of the state machine Return Value: WdfDevStatePnpNull --*/ { if (This->m_DeviceRemoveProcessed != NULL) { This->m_SetDeviceRemoveProcessed = TRUE; } return WdfDevStatePnpNull; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventRemovedPdoSurpriseRemoved( __inout FxPkgPnp* This ) /*++ Routine Description: PDO has been removed (could have been disabled in user mode) and is now surprise removed by the underlying bus. Arguments: This - instance of the state machine Return Value: WdfDevStatePnpRemovedPdoWait --*/ { // // Invoke EvtDeviceSurpriseRemove // This->m_DeviceSurpriseRemoval.Invoke(This->m_Device->GetHandle()); // // Call the overloaded surprise remove handler since // PnpEventSurpriseRemovePendingOverload will not get called // This->PnpEventSurpriseRemovePendingOverload(); // // The surprise remove irp was pended, complete it now // This->PnpFinishProcessingIrp(); return WdfDevStatePnpRemovedPdoWait; } VOID FxPkgPnp::PnpCleanupForRemove( __in BOOLEAN GracefulRemove ) /*++ Routine Description: This is a common worker function between surprise remove and the graceful remove path to do common cleanup. This involves deregistering from WMI, device interfaces, symbolic links and stopping power managed i/o. Arguments: GracefulRemove - if TRUE, we are in the graceful remove path, otherwise we are in the surprise remove path. Return Value: None --*/ { // // Disable WMI. // m_Device->WmiPkgDeregister(); // // Disable any device interfaces. // PnpDisableInterfaces(); DeleteSymbolicLinkOverload(GracefulRemove); // Flush/purge top-edge queues m_Device->m_PkgIo->StopProcessingForPower( FxIoStopProcessingForPowerPurgeManaged ); // // Invoke EvtDeviceSelfManagedIoFlush // if (m_SelfManagedIoMachine != NULL) { m_SelfManagedIoMachine->Flush(); } // // Tell all the resource objects that they no longer own anything. // NotifyResourceobjectsToReleaseResources(); // // Flush persistent state to permanent storage. We do this in the failed // state for the surprise removed case. By storing the state when we are // surprise removed, if the stack is reenumerated, it will pick up the saved // state that was just committed. If the state was saved during remove // device it can be too late because the new instance of the same device // could already be up and running and not pick up the saved state. // // It is important to save the state before completing the (potentially) // pended pnp irp. Completing the pnp irp will allow a new instance of the // device to be enumerated and we want to save state before that happens. // SaveState(FALSE); if (m_SharedPower.m_WaitWakeOwner) { // // Don't care about the return code, just blindly try to complete the // wake request. The function can handle the case where there is no // irp to complete. // (void) PowerIndicateWaitWakeStatus(STATUS_NO_SUCH_DEVICE); } } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventRemovingDisableInterfaces( __inout FxPkgPnp* This ) /*++ Routine Description: This function implements the Removing Disable Interfaces state. It disables any device interfaces and then tells the power policy state machine to prepare for device removal. Arguments: none Return Value: WdfDevStatePnpNull --*/ { NTSTATUS status; // // Surprise remove path releases hardware first then disables the interfaces, // so do the same in the graceful remove path. // // // Call the driver and tell it to unmap resources. // status = This->PnpReleaseHardware(); if (!NT_SUCCESS(status)) { // // The driver failed to unmap resources. Presumably this means that // there are now some leaked PTEs. Error is logged prior to this point. // DO_NOTHING(); } This->PnpCleanupForRemove(TRUE); // // Tell the power policy state machine to prepare for device removal // This->PnpPowerPolicyRemove(); return WdfDevStatePnpNull; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventStarted( __inout FxPkgPnp* This ) /*++ Routine Description: Completes the pending request or sends it on its way. Arguments: This - instance of the state machine for the device Return Value: WdfDevStatePnpNull --*/ { This->m_AchievedStart = TRUE; // // Log Telemetry event for the FDO // if (This->m_Device->IsPdo() == FALSE) { This->m_Device->FxLogDeviceStartTelemetryEvent(); } This->PnpFinishProcessingIrp(); return WdfDevStatePnpNull; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventStartedCancelStop( __inout FxPkgPnp* This ) /*++ Routine Description: Cancel stop received from the started state. Just return to the started state where we will handle the pended irp. Arguments: This - Instance of the state machine Return Value: WdfDevStatePnpStarted --*/ { UNREFERENCED_PARAMETER(This); return WdfDevStatePnpStarted; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventStartedCancelRemove( __inout FxPkgPnp* This ) /*++ Routine Description: Cancel remove received from the started state. Just return to the started state where we will handle the pended irp. Arguments: This - Instance of the state machine Return Value: WdfDevStatePnpStarted --*/ { UNREFERENCED_PARAMETER(This); return WdfDevStatePnpStarted; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventStartedRemoving( __inout FxPkgPnp* This ) /*++ Routine Description: Remove directly from started. Power down the other state machines. Arguments: This - instance of the state machine Return Value: WdfDevStatePnpNull --*/ { This->PnpPowerPolicyStop(); return WdfDevStatePnpNull; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventRestarting( __inout FxPkgPnp* This ) /*++ Routine Description: This function implements the Cancelling Stop state. Arguments: none Return Value: VOID --*/ { // // Send an event to the Power Policy State Machine // telling it to "Start." // This->PnpPowerPolicyStart(); return WdfDevStatePnpNull; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventStartingFromStopped( __inout FxPkgPnp* This ) /*++ Routine Description: This function implements the Restarting From Stopped state. It's job is to map new resources and then proceed to the Restarting state. Arguments: none Return Value: VOID --*/ { NTSTATUS status; BOOLEAN matched; FxCxCallbackProgress progress; status = This->PnpPrepareHardware(&matched, &progress); if (!NT_SUCCESS(status)) { // // We can handle remove out of the init state, revert back to that state // if ((matched == FALSE) || (progress < FxCxCallbackProgressClientCalled)) { // // Wait for the remove irp to come in // COVERAGE_TRAP(); return WdfDevStatePnpFailed; } else { // // EvtDevicePrepareHardware is what failed, goto a state where we // undo that call. // COVERAGE_TRAP(); return WdfDevStatePnpFailedOwnHardware; } } return WdfDevStatePnpRestarting; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventStopped( __inout FxPkgPnp* This ) /*++ Routine Description: This function implements the Stopped state. It's job is to invoke EvtDeviceReleaseHardware. Arguments: none Return Value: VOID --*/ { WDF_DEVICE_PNP_STATE state; NTSTATUS status; status = This->PnpReleaseHardware(); if (NT_SUCCESS(status)) { // // Tell all the resource objects that they no longer own anything. // This->NotifyResourceobjectsToReleaseResources(); state = WdfDevStatePnpNull; } else { COVERAGE_TRAP(); This->SetInternalFailure(); state = WdfDevStatePnpFailed; } // // Send the irp on its merry way. This irp (stop device) cannot be failed // and must always be sent down the stack. // This->PnpFinishProcessingIrp(); return state; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventStoppedWaitForStartCompletion( __inout FxPkgPnp* This ) /*++ Routine Description: The start irp is coming down from the stopped state. Send it down the stack and transition to the new state if needed. Arguments: This - instance of the state machine Return Value: new machine state --*/ { if (This->PnpSendStartDeviceDownTheStackOverload() == FALSE) { // // The start irp's completion routine will move the state machine into // the new state. // return WdfDevStatePnpNull; } return WdfDevStatePnpStartingFromStopped; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventStartedStopping( __inout FxPkgPnp* This ) /*++ Routine Description: Received a stop irp. Stop the power policy machine and then wait for it to complete. Arguments: This - instance of the state machine Return Value: WdfDevStatePnpNull --*/ { // // It is important to stop power policy before releasing the reference. // If the reference was released first, we could get into a situation where // we immediately go idle and then we must send a D0 irp when in the remove. // If there are devices on top of this device and we send a D0 irp during // remove processing, the upper devices will be sent an irp after getting a // pnp remove (and either crash or fail the power irp upon receiving it). // This->PnpPowerPolicyStop(); This->PnpPowerDereferenceSelf(); return WdfDevStatePnpNull; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventSurpriseRemoved( __inout FxPkgPnp* This ) /*++ Routine Description: We got IRP_MN_SURPRISE_REMOVE_DEVICE while the system was pretty far down the removal path, or never started. Call EvtDeviceSurpriseRemoval, call the surprise remove virtual and drop into the Failed path. Arguments: This - instance of the state machine Return Value: new device pnp state --*/ { // // Invoke EvtDeviceSurpriseRemove // This->m_DeviceSurpriseRemoval.Invoke(This->m_Device->GetHandle()); // // Notify the virtual override of the surprise remove. // This->PnpEventSurpriseRemovePendingOverload(); return WdfDevStatePnpFailed; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventInitQueryRemove( __inout FxPkgPnp* This ) /*++ Routine Description: Query remove from the init state. Complete the pended request. Arguments: This - instance of th state machine. Return Value: WdfDevStatePnpNull --*/ { FxIrp irp(This->ClearPendingPnpIrp()); irp.SetStatus(STATUS_SUCCESS); This->FireAndForgetIrp(&irp); return WdfDevStatePnpNull; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventInitQueryRemoveCanceled( __inout FxPkgPnp* This ) /*++ Routine Description: Handle a query remove canceled from the init state. Complete the pended request. Arguments: This - instance of the state machine Return Value: WdfDevStatePnpInit --*/ { FxIrp irp(This->ClearPendingPnpIrp()); This->FireAndForgetIrp(&irp); return WdfDevStatePnpInit; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventFdoRemoved( __inout FxPkgPnp* This ) /*++ Routine Description: FDO is being removed, hand off to the derived pnp package Arguments: This - instance of the state machine Return Value: new device pnp state --*/ { return This->PnpEventFdoRemovedOverload(); } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventQueriedSurpriseRemove( __inout FxPkgPnp* This ) /*++ Routine Description: The device was in a queried (either stop or cancel) state and was surprise removed from it. Arguments: This - instance of the state machine Return Value: new state, WdfDevStatePnpSurpriseRemoveIoStarted --*/ { COVERAGE_TRAP(); This->PnpPowerDereferenceSelf(); return WdfDevStatePnpSurpriseRemoveIoStarted; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventSurpriseRemoveIoStarted( __inout FxPkgPnp* This ) /*++ Routine Description: We got IRP_MN_SURPRISE_REMOVE_DEVICE while the system was more or less running. Start down the Surprise Remove/Device Failed path. This state calls EvtDeviceSurpriseRemoval, calls the virtual surprise remove overload, and then drops into the Failed path. Arguments: This - instance of the state machine Return Value: new device pnp state --*/ { // // Invoke EvtDeviceSurpriseRemove // This->m_DeviceSurpriseRemoval.Invoke(This->m_Device->GetHandle()); // // Notify the virtual override of the surprise remove. // This->PnpEventSurpriseRemovePendingOverload(); return WdfDevStatePnpFailedIoStarting; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventFailedPowerDown( __inout FxPkgPnp* This ) /*++ Routine Description: The device was in the started state and failed power down or could not enable its interfaces. Gracefully power down the device and tear down the stack. The difference between this routine and PnpEventFailedIoStarting is that FailedIoStarting sends a surprise remove to the power state machine. After surprise remove has been sent to the power state machine, it will not attempt to put the device into Dx because it assumes the device is no longer present. In this error case, we still want the device to be powered down, so we send a normal stop remove. Arguments: This - instance of the state machine Return Value: new state --*/ { // // Normal stop so that the power state machine will go through the power off // path and not skip directly to off like it would if we sent it a surprise // remove notification. // This->PnpPowerPolicyStop(); return WdfDevStatePnpNull; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventFailedIoStarting( __inout FxPkgPnp* This ) /*++ Routine Description: The device failed (or was yanked out of the machine) while it was more or less running. Tell the driver to stop self-managed I/O and drop into the next state on the failure path. Arguments: j This - instance of the state machine Return Value: new device pnp state --*/ { This->PnpPowerPolicySurpriseRemove(); return WdfDevStatePnpNull; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventFailedOwnHardware( __inout FxPkgPnp* This ) /*++ Routine Description: The device failed (or was yanked out of the machine) while it owned access to the hardware. Tell the driver to release resources and drop into the next state on the failure path. Arguments: This - instance of the state machine Return Value: new device pnp state --*/ { // // Invoke EvtDeviceReleaseHardware // (void) This->PnpReleaseHardware(); return WdfDevStatePnpFailed; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventFailed( __inout FxPkgPnp* This ) /*++ Routine Description: The device failed (or was yanked out of the machine). Disable interfaces, flush queues and tell the driver to clean up random stuff. Also ask the power policy state machine to prepare for device removal. Arguments: This - instance of the state machine Return Value: WdfDevStatePnpNull --*/ { This->PnpCleanupForRemove(FALSE); // // Tell the power policy state machine to prepare for device removal // This->PnpPowerPolicyRemove(); return WdfDevStatePnpNull; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventFailedPowerPolicyRemoved( __inout FxPkgPnp* This ) /*++ Routine Description: The power policy state machine has prepared for device removal. Invalidate the device state and wait for IRP_MN_REMOVE_DEVICE. Arguments: This - instance of the state machine Return Value: WdfDevStatePnpFailedWaitForRemove --*/ { BOOLEAN failedActionAttemptRestart; failedActionAttemptRestart = FALSE; // // Finish processing any pended PnP IRP. Since we can reach this state from // states where a pnp irp was *not* pended, we do not require a pnp irp to // have been pended when trying to complete it. // This->PnpFinishProcessingIrp(FALSE); // // For compatibility reasons, in case of UMDF version < 2.23 // and KMDF version < 1.23 renumerate the PDO if FailedAction // is WdfDeviceFailedAttemptRestart. For later versions // reenumeration is done by SetDeviceFailed // if (This->m_FailedAction == WdfDeviceFailedAttemptRestart) { #if (FX_CORE_MODE == FX_CORE_USER_MODE) if (This->GetDriverGlobals()->IsVersionGreaterThanOrEqualTo(2, 23) == FALSE) { failedActionAttemptRestart = TRUE; } #else if (This->GetDriverGlobals()->IsVersionGreaterThanOrEqualTo(1, 23) == FALSE) { failedActionAttemptRestart = TRUE; } #endif } // // Request reenumeration if the client driver asked for it or if there was // an internal failure *and* if the client driver didn't specify failure... // AND if we have not yet exceeded our restart count within a period of time. // if ((failedActionAttemptRestart || (This->m_FailedAction == WdfDeviceFailedUndefined && This->m_InternalFailure)) && This->PnpCheckAndIncrementRestartCount()) { // // No need to invalidate state because we are in a state waiting for // a remove device anyways so failure is imminent. // This->AskParentToRemoveAndReenumerate(); } if (This->m_FailedAction != WdfDeviceFailedUndefined || This->m_InternalFailure) { // // If the failure occurred in this device, then tear down the stack if // we are in a state in which pnp thinks we are started. If we are // already in a stopped state, this invalidation will do no harm. // MxDeviceObject physicalDeviceObject( This->m_Device->GetPhysicalDevice() ); // // We need to pass FDO as a parameter as UMDF currently doesn't have // PDOs and instead needs FDO to invalidate device state. // physicalDeviceObject.InvalidateDeviceState( This->m_Device->GetDeviceObject() //FDO ); } return WdfDevStatePnpFailedWaitForRemove; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventFailedSurpriseRemoved( __inout FxPkgPnp* This ) /*++ Routine Description: The device has failed and then received a surprise remove. This can easily happen on return from low power as following: 1 device attempts to enter D0, D0Entry fails 2 pnp state machine proceeds down failure path and stops at FailedWaitForRemove 3 bus driver finds device missing, reports it as such and a s.r. irp arrives Arguments: This - instance of the state machine Return Value: WdfDevStatePnpFailedWaitForRemove --*/ { // // Invoke EvtDeviceSurpriseRemove // This->m_DeviceSurpriseRemoval.Invoke(This->m_Device->GetHandle()); // // Call the overloaded surprise remove handler // This->PnpEventSurpriseRemovePendingOverload(); // // The surprise remove irp was pended, complete it now. The irp need not // be present. If we failed before the surprise irp was sent and the irp // arrived in the middle of processing the failure, we could have completed // the s.r. irp in FailedWaitForRemove, which is OK. // This->PnpFinishProcessingIrp(FALSE); // // Return back to the failed state where will wait for remove // return WdfDevStatePnpFailedWaitForRemove; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventFailedStarted( __inout FxPkgPnp* This ) /*++ Routine Description: Device failed (probably somewhere in the start path) and got another start request. Fail the start and return to the state where we will wait for a remove irp. Arguments: This - instance of the state machine Return Value: WdfDevStatePnpFailedWaitForRemove --*/ { // // Complete the pended start irp with error // This->SetPendingPnpIrpStatus(STATUS_INVALID_DEVICE_STATE); This->PnpFinishProcessingIrp(); return WdfDevStatePnpFailedWaitForRemove; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventFailedInit( __inout FxPkgPnp* This ) /*++ Routine Description: Processing of the start irp's resources failed. Complete the start irp. Arguments: This - instance of the state machine Return Value: WdfDevStatePnpNull --*/ { // // Release the power thread that we may have previously acquired in // HardwareAvailable. // This->ReleasePowerThread(); // // Deref the reenumeration interface // This->ReleaseReenumerationInterface(); This->PnpFinishProcessingIrp(); return WdfDevStatePnpInit; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventPdoInitFailed( __inout FxPkgPnp* This ) /*++ Routine Description: The driver failed EvtDeviceSoftwareInit. Run cleanup and die. Arguments: This - instance of the state machine Return Value: new device pnp state --*/ { COVERAGE_TRAP(); This->m_Device->EarlyDispose(); // // All the children are in the disposed state, destroy them all. m_Device // is not destroyed in this call. // This->m_Device->DestroyChildren(); return WdfDevStatePnpFinal; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventRestart( __inout FxPkgPnp* This ) /*++ Routine Description: A start to start transition has occurred. Go through the normal stop path first and then restart things. Arguments: This - instance of the state machine Return Value: WdfDevStateNull or new machine state --*/ { // // Stop the power policy machine so that we simulate stopping first // This->PnpPowerPolicyStop(); return WdfDevStatePnpNull; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventRestartReleaseHardware( __inout FxPkgPnp* This ) /*++ Routine Description: Release the hardware resources and send the start irp down the stack Arguments: This - instance of the state machine Return Value: new machine state --*/ { NTSTATUS status; status = This->PnpReleaseHardware(); if (!NT_SUCCESS(status)) { COVERAGE_TRAP(); This->SetInternalFailure(); This->SetPendingPnpIrpStatus(status); return WdfDevStatePnpFailed; } if (This->PnpSendStartDeviceDownTheStackOverload() == FALSE) { // // The start irp's completion routine will move the state machine into // the new state. // return WdfDevStatePnpNull; } // // Start happened synchronously. Transition to the new state now. // return WdfDevStatePnpRestartHardwareAvailable; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventRestartHardwareAvailable( __inout FxPkgPnp* This ) /*++ Routine Description: Prepare the hardware and restart the power and power policy state machines after a successful start -> start transition where the start irp is coming up the stack. Arguments: This - instance of the state machine Return Value: new machine state --*/ { NTSTATUS status; BOOLEAN matched; FxCxCallbackProgress progress; status = This->PnpPrepareHardware(&matched, &progress); if (!NT_SUCCESS(status)) { if ((matched == FALSE) || (progress < FxCxCallbackProgressClientCalled)) { // // Wait for the remove irp to come in // COVERAGE_TRAP(); return WdfDevStatePnpFailed; } else { // // EvtDevicePrepareHardware is what failed, goto a state where we // undo that call. // COVERAGE_TRAP(); return WdfDevStatePnpFailedOwnHardware; } } This->PnpPowerPolicyStart(); return WdfDevStatePnpNull; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventPdoRestart( __inout FxPkgPnp* This ) /*++ Routine Description: The PDO was in the removed state has received another start irp. Reset state and then move into the start sequence. Arguments: This - instance of the state machine Return Value: WdfDevStatePnpHardwareAvailable --*/ { // // Since this is a PDO and it is being restarted, it could have had an internal // failure during its previous start. Since we use m_InternalFailure to set // PNP_DEVICE_FAILED when handling IRP_MN_QUERY_PNP_DEVICE_STATE, it should // be set to FALSE so we don't immediately fail the device after the start // has been succeeded. // This->m_InternalFailure = FALSE; This->m_Failed = FALSE; // // The PDO is being restarted and could have previous had a power thread // running. If so, the reference count goes to zero when removed from a // started state. Reset back to 1. // This->m_PowerThreadInterfaceReferenceCount = 1; // // The count is decremented on the initial started->removed transition (and // not subsequent removed -> removed transitiosn). On removed -> restarted, // we need to set the count back to a bias of 1 so when we process the remove // again we can know if there are any pending child (of this PDO) removals // that we must wait for. // This->m_PendingChildCount = 1; // // Reset WMI state // This->m_Device->m_PkgWmi->ResetStateForPdoRestart(); This->m_Device->m_PkgIo->ResetStateForRestart(); if (This->IsPowerPolicyOwner()) { This->m_PowerPolicyMachine.m_Owner->m_PowerIdleMachine.Reset(); } // // Set STATUS_SUCCESS in the irp so that the stack will start smoothly after // we have powered up. // This->SetPendingPnpIrpStatus(STATUS_SUCCESS); // // This flag is set on the wake-enabled device powering down path, // but if the device power down failed it may not have been cleared. // This->m_WakeInterruptsKeepConnected = FALSE; // // This flag is cleared so we can reacquire the start time and state // This->m_AchievedStart = FALSE; return WdfDevStatePnpHardwareAvailable; } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventRemovedChildrenRemoved( __inout FxPkgPnp* This ) /*++ Routine Description: All of this device's previously enumerated children have been removed. Move the state machine into its next state based on the device's role. Arguments: This - instance of the state machine Return Value: new state --*/ { return This->PnpGetPostRemoveState(); } WDF_DEVICE_PNP_STATE FxPkgPnp::PnpEventFinal( __inout FxPkgPnp* This ) /*++ Routine Description: The final resting and dead state for the FxDevice that has been removed. We release our final reference here and destroy the object. Arguments: This - This instance of the state machine Return Value: WdfDevStatePnpNull --*/ { NTSTATUS status; // // We may not have a pnp irp at this stage (esp for PDO which are in the // removed state and whose parent is being removed) so we use the function // pointer as the unique tag. // // IoReleaseRemoveLockAndWait requires an outstanding reference to release, // so acquire it before calling it if we are in the case where the PDO is // being removed with no outstanding PNP remove irp b/c the parent is being // removed. // if (This->m_DeviceRemoveProcessed == NULL) { status = Mx::MxAcquireRemoveLock( This->m_Device->GetRemoveLock(), &FxPkgPnp::PnpEventFinal); ASSERT(NT_SUCCESS(status)); UNREFERENCED_PARAMETER(status); } // // Indicate to the parent device that we are removed now (vs the destructor // of the object where we would never reach because in the case of the PDO // being removed b/c the parent is going away, the parent has a reference // on the PDO). if (This->m_Device->m_ParentWaitingOnChild) { (This->m_Device->m_ParentDevice->m_PkgPnp)->ChildRemoved(); } if (This->m_DeviceRemoveProcessed == NULL) { // // We can get into this state w/out an event to set when a PDO (this // device) is in the removed state and then the parent is removed. // // // After this is called, any irp dispatched to FxDevice::DispatchWithLock // will fail with STATUS_INVALID_DEVICE_REQUEST. // Mx::MxReleaseRemoveLockAndWait( This->m_Device->GetRemoveLock(), &FxPkgPnp::PnpEventFinal); // // Delete the object when we exit the state machine. Dispose was run // early in a previous state. // This->m_PnpMachine.SetDelayedDeletion(); } else { // // The thread which received the pnp remove irp will delete the device // This->m_SetDeviceRemoveProcessed = TRUE; } return WdfDevStatePnpNull; } _Must_inspect_result_ NTSTATUS FxPkgPnp::PnpEnableInterfacesAndRegisterWmi( VOID ) /*++ Routine Description: Enables all of the device interfaces and then registers wmi. Arguments: None Return Value: NT_SUCCESS if all goes well, !NT_SUCCESS otherwise --*/ { PSINGLE_LIST_ENTRY ple; NTSTATUS status; status = STATUS_SUCCESS; // // Enable any device interfaces. // m_DeviceInterfaceLock.AcquireLock(GetDriverGlobals()); m_DeviceInterfacesCanBeEnabled = TRUE; for (ple = m_DeviceInterfaceHead.Next; ple != NULL; ple = ple->Next) { FxDeviceInterface *pDeviceInterface; pDeviceInterface = FxDeviceInterface::_FromEntry(ple); #if (FX_CORE_MODE == FX_CORE_KERNEL_MODE) // // By this time, the device interface, no matter what the WDFDEVICE role // will have been registered. // ASSERT(pDeviceInterface->m_SymbolicLinkName.Buffer != NULL); #endif if (pDeviceInterface->m_AutoEnableOnFirstStart) { pDeviceInterface->SetState(TRUE); } status = STATUS_SUCCESS; } m_DeviceInterfaceLock.ReleaseLock(GetDriverGlobals()); if (NT_SUCCESS(status)) { status = m_Device->WmiPkgRegister(); } if (!NT_SUCCESS(status)) { SetInternalFailure(); SetPendingPnpIrpStatus(status); } return status; } __drv_when(!NT_SUCCESS(return), __drv_arg(ResourcesMatched, _Must_inspect_result_)) __drv_when(!NT_SUCCESS(return), __drv_arg(Progress, _Must_inspect_result_)) NTSTATUS FxPkgPnp::PnpPrepareHardware( _Out_ PBOOLEAN ResourcesMatched, _Out_ FxCxCallbackProgress *Progress ) /*++ Routine Description: Matches the PNP resources with the WDFINTERRUPT objects registered and then calls EvtDevicePrepareHardware. All start paths call this function Arguments: ResourcesMatched - indicates to the caller what stage failed if !NT_SUCCESS is returned Progress - indicates to the caller what stage the API failed if !NT_SUCCESS is returned Return Value: NT_SUCCESS if all goes well, !NT_SUCCESS if failure occurrs --*/ { NTSTATUS status; *ResourcesMatched = FALSE; *Progress = FxCxCallbackProgressInitialized; // // FxPnpStateRemoved: // Mark the device a not removed. This is just so that anybody sending // a PnP IRP_MN_QUERY_DEVICE_STATE gets a reasonable answer. // // FxPnpStateFailed, FxPnpStateResourcesChanged: // Both of these values can be set to true and cause another start to // be sent down the stack. Reset these values back to false. If there is // a need to set these values, the driver can set them in // EvtDevicePrepareHardware. // m_PnpState.Value &= ~(FxPnpStateRemovedMask | FxPnpStateFailedMask | FxPnpStateResourcesChangedMask); m_PnpState.Value |= (FxPnpStateRemovedUseDefault | FxPnpStateFailedUseDefault | FxPnpStateResourcesChangedUseDefault); // // This will parse the resources and setup all the WDFINTERRUPT handles // status = PnpMatchResources(); if (!NT_SUCCESS(status)) { *ResourcesMatched = FALSE; SetInternalFailure(); SetPendingPnpIrpStatus(status); return status; } #if (FX_CORE_MODE == FX_CORE_USER_MODE) // // Build register resource table // status = m_Resources->BuildRegisterResourceTable(); if (!NT_SUCCESS(status)) { SetInternalFailure(); SetPendingPnpIrpStatus(status); goto exit; } // // Build Port resource table // status = m_Resources->BuildPortResourceTable(); if (!NT_SUCCESS(status)) { SetInternalFailure(); SetPendingPnpIrpStatus(status); goto exit; } // // We keep track if the device has any connection resources, // in which case we allow unrestricted access to interrupts // regardless of the UmdfDirectHardwareAccess directive. // status = m_Resources->CheckForConnectionResources(); if (!NT_SUCCESS(status)) { SetInternalFailure(); SetPendingPnpIrpStatus(status); goto exit; } #endif *ResourcesMatched = TRUE; m_Device->SetCallbackFlags( FXDEVICE_CALLBACK_IN_PREPARE_HARDWARE ); status = m_DevicePrepareHardware.Invoke(m_Device->GetHandle(), m_ResourcesRaw->GetHandle(), m_Resources->GetHandle(), Progress); m_Device->ClearCallbackFlags( FXDEVICE_CALLBACK_IN_PREPARE_HARDWARE ); if (!NT_SUCCESS(status)) { if (status == STATUS_NOT_SUPPORTED) { DoTraceLevelMessage( GetDriverGlobals(), TRACE_LEVEL_ERROR, TRACINGPNP, "EvtDevicePrepareHardware returned an invalid status " "STATUS_NOT_SUPPORTED"); if (GetDriverGlobals()->IsVerificationEnabled(1, 11, OkForDownLevel)) { FxVerifierDbgBreakPoint(GetDriverGlobals()); } } SetInternalFailure(); SetPendingPnpIrpStatus(status); goto exit; } // // Now that we have assigned the resources to all the interrupts, figure out // the highest synch irql for each interrupt set which shares a spinlock. // PnpAssignInterruptsSyncIrql(); // // Do mode-specific work. For KMDF, there is nothing additional to do. // status = PnpPrepareHardwareInternal(); if (!NT_SUCCESS(status)) { DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_ERROR, TRACINGPNP, "PrepareHardware failed %!STATUS!", status); SetInternalFailure(); SetPendingPnpIrpStatus(status); } exit: return status; } _Must_inspect_result_ NTSTATUS FxPkgPnp::PnpReleaseHardware( VOID ) /*++ Routine Description: Invokes the driver's release hardware callback if present. Releases any interrupt resources allocated during the prepare hardware callback. Arguments: None Return Value: Driver's release hardware callback return status or STATUS_SUCCESS if callback is not present. --*/ { NTSTATUS status; FxInterrupt* interrupt; PLIST_ENTRY le; // // Invoke the device's release hardware callback. // status = m_DeviceReleaseHardware.Invoke( m_Device->GetHandle(), m_Resources->GetHandle()); if (status == STATUS_NOT_SUPPORTED) { DoTraceLevelMessage( GetDriverGlobals(), TRACE_LEVEL_ERROR, TRACINGPNP, "EvtDeviceReleaseHardware returned an invalid status " "STATUS_NOT_SUPPORTED"); if (GetDriverGlobals()->IsVerificationEnabled(1, 11, OkForDownLevel)) { FxVerifierDbgBreakPoint(GetDriverGlobals()); } } #if (FX_CORE_MODE == FX_CORE_USER_MODE) if (NT_SUCCESS(status)) { // // make sure driver has unmapped its resources // m_Resources->ValidateResourceUnmap(); } // // delete the register and port resource tables // m_Resources->DeleteRegisterResourceTable(); m_Resources->DeletePortResourceTable(); #endif // // Delete all interrupt objects that were created in the prepare hardware // callback that the driver did not explicitly delete (in reverse order). // le = m_InterruptListHead.Blink; while(le != &m_InterruptListHead) { // Find the interrupt object pointer. interrupt = CONTAINING_RECORD(le, FxInterrupt, m_PnpList); // Advance the entry before it becomes invalid. le = le->Blink; // Let the interrupt know that 'release hardware' was called. interrupt->OnPostReleaseHardware(); } return status; } VOID FxPkgPnp::PnpPowerPolicyStart( VOID ) /*++ Routine Description: Informs the power policy state machine that it should start. Arguments: None Return Value: None --*/ { PowerPolicyProcessEvent(PwrPolStart); } VOID FxPkgPnp::PnpPowerPolicyStop( VOID ) /*++ Routine Description: Informs the power and power policy state machines that they should stop. Arguments: None Return Value: None --*/ { PowerPolicyProcessEvent(PwrPolStop); } VOID FxPkgPnp::PnpPowerPolicySurpriseRemove( VOID ) /*++ Routine Description: Informs the policy state machines that it should stop due to the hardware being surprise removed. Arguments: None Return Value: None --*/ { PowerPolicyProcessEvent(PwrPolSurpriseRemove); } VOID FxPkgPnp::PnpPowerPolicyRemove( VOID ) /*++ Routine Description: Informs the policy state machine that it should prepare for device removal. Arguments: None Return Value: None --*/ { PowerPolicyProcessEvent(PwrPolRemove); } VOID FxPkgPnp::PnpFinishProcessingIrp( __in BOOLEAN IrpMustBePresent ) /*++ Routine Description: Finishes handling a pended pnp irp Arguments: None Return Value: None --*/ { FxIrp irp; UNREFERENCED_PARAMETER(IrpMustBePresent); ASSERT(IrpMustBePresent == FALSE || IsPresentPendingPnpIrp()); // // Start device is the only request we handle on the way back up the stack. // Also, if we fail any pnp irps that we are allowed to fail, we just // complete them. // if (IsPresentPendingPnpIrp()) { irp.SetIrp(GetPendingPnpIrp()); if (irp.GetMinorFunction() == IRP_MN_START_DEVICE || !NT_SUCCESS(irp.GetStatus())) { irp.SetIrp(ClearPendingPnpIrp()); CompletePnpRequest(&irp, irp.GetStatus()); } else { m_PnpMachine.m_FireAndForget = TRUE; } } } VOID FxPkgPnp::PnpDisableInterfaces( VOID ) /*++ Routine Description: Disables all of the registerd interfaces on the device. Arguments: None Return Value: None --*/ { PSINGLE_LIST_ENTRY ple; m_DeviceInterfaceLock.AcquireLock(GetDriverGlobals()); m_DeviceInterfacesCanBeEnabled = FALSE; for (ple = m_DeviceInterfaceHead.Next; ple != NULL; ple = ple->Next) { FxDeviceInterface *pDeviceInterface; pDeviceInterface = FxDeviceInterface::_FromEntry(ple); pDeviceInterface->SetState(FALSE); } m_DeviceInterfaceLock.ReleaseLock(GetDriverGlobals()); } VOID FxPkgPnp::PnpEventSurpriseRemovePendingOverload( VOID ) { // // Mark all of the children as missing because the parent has just been // removed. Note that this will happen after all of the children have // already received the surprise remove event. This is OK because the // reported status is inspected during the remove device event which will // happen after the parent finishes processing the surprise event. // if (m_EnumInfo != NULL) { m_EnumInfo->m_ChildListList.LockForEnum(GetDriverGlobals()); FxTransactionedEntry* ple; ple = NULL; while ((ple = m_EnumInfo->m_ChildListList.GetNextEntry(ple)) != NULL) { FxChildList::_FromEntry(ple)->NotifyDeviceSurpriseRemove(); } m_EnumInfo->m_ChildListList.UnlockFromEnum(GetDriverGlobals()); } } _Must_inspect_result_ NTSTATUS FxPkgPnp::PnpMatchResources( VOID ) /*++ Routine Description: This method is called in response to a PnP StartDevice IRP coming up the stack. It: - Captures the device's resources - Calls out to interested resource objects - Sends an event to the PnP state machine Arguemnts: Irp - a pointer to the FxIrp Returns: NTSTATUS --*/ { PCM_RESOURCE_LIST pResourcesRaw; PCM_RESOURCE_LIST pResourcesTranslated; FxResourceCm* resCmRaw; FxResourceCm* resCmTrans; FxInterrupt* interrupt; PLIST_ENTRY ple; NTSTATUS status; FxCollectionEntry *curRaw, *curTrans, *endTrans; ULONG messageCount; FxIrp irp; DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGPNP, "Entering PnpMatchResources"); // // We must clear these flags before calling into the event handler because // it might set these states back (which is OK). If we don't clear these // states and the start succeeds, we would endlessly report that our // resources have changed and be restarted over and over. // m_PnpState.Value &= ~(FxPnpStateFailedMask | FxPnpStateResourcesChangedMask); m_PnpState.Value |= (FxPnpStateFailedUseDefault | FxPnpStateResourcesChangedUseDefault); irp.SetIrp(m_PendingPnPIrp); pResourcesRaw = irp.GetParameterAllocatedResources(); pResourcesTranslated = irp.GetParameterAllocatedResourcesTranslated(); status = m_ResourcesRaw->BuildFromWdmList(pResourcesRaw, FxResourceNoAccess); if (!NT_SUCCESS(status)) { DoTraceLevelMessage( GetDriverGlobals(), TRACE_LEVEL_ERROR, TRACINGPNP, "Could not allocate raw resource list for WDFDEVICE 0x%p, %!STATUS!", m_Device->GetHandle(), status); goto Done; } status = m_Resources->BuildFromWdmList(pResourcesTranslated, FxResourceNoAccess); if (!NT_SUCCESS(status)) { DoTraceLevelMessage( GetDriverGlobals(), TRACE_LEVEL_ERROR, TRACINGPNP, "Could not allocate translated resource list for WDFDEVICE 0x%p, %!STATUS!", m_Device->GetHandle(), status); goto Done; } // // reset the stored information in all interrupts in the rebalance case // for (ple = m_InterruptListHead.Flink; ple != &m_InterruptListHead; ple = ple->Flink) { interrupt = CONTAINING_RECORD(ple, FxInterrupt, m_PnpList); interrupt->Reset(); } // // Now iterate across the resources, looking for ones that correspond // to objects that we are managing. Tell those objects about the resources // that were assigned. // ple = &m_InterruptListHead; endTrans = m_Resources->End(); for (curTrans = m_Resources->Start(), curRaw = m_ResourcesRaw->Start(); curTrans != endTrans; curTrans = curTrans->Next(), curRaw = curRaw->Next()) { ASSERT(curTrans->m_Object->GetType() == FX_TYPE_RESOURCE_CM); ASSERT(curRaw->m_Object->GetType() == FX_TYPE_RESOURCE_CM); resCmRaw = (FxResourceCm*) curRaw->m_Object; if (resCmRaw->m_Descriptor.Type == CmResourceTypeInterrupt) { // // We're looking at an interrupt resource. // if (ple->Flink == &m_InterruptListHead) { // // Oops, there are no more interrupt objects. // DoTraceLevelMessage( GetDriverGlobals(), TRACE_LEVEL_WARNING, TRACINGPNP, "Not enough interrupt objects created by WDFDEVICE 0x%p", m_Device->GetHandle()); break; } resCmTrans = (FxResourceCm*) curTrans->m_Object; ASSERT(resCmTrans->m_Descriptor.Type == CmResourceTypeInterrupt); messageCount = resCmRaw->m_Descriptor.u.MessageInterrupt.Raw.MessageCount; if (FxInterrupt::_IsMessageInterrupt(resCmTrans->m_Descriptor.Flags) && (messageCount > 1)) { ULONG i; // // Multi-message MSI 2.2 needs to be handled differently // for (i = 0, ple = ple->Flink; i < messageCount && ple != &m_InterruptListHead; i++, ple = ple->Flink) { // // Get the next interrupt object. // interrupt = CONTAINING_RECORD(ple, FxInterrupt, m_PnpList); // // Tell the interrupt object what its resources are. // interrupt->AssignResources(&resCmRaw->m_Descriptor, &resCmTrans->m_Descriptor); } } else { // // This is either MSI2.2 with 1 message, MSI-X or Line based. // ple = ple->Flink; interrupt = CONTAINING_RECORD(ple, FxInterrupt, m_PnpList); // // Tell the interrupt object what its resources are. // interrupt->AssignResources(&resCmRaw->m_Descriptor, &resCmTrans->m_Descriptor); } } } #if FX_IS_KERNEL_MODE // // If there are any pended I/Os that were sent to the target // that were pended in the transition to stop, then this will // resend them. // // ISSUE: This has the potential of I/O completing // before the driver's start callback has been called...but, // this is the same as the PDO pending a sent irp and completing // it when the PDO is restarted before the FDO has a change to // process the start irp which was still pended below. // if (m_Device->IsFilter()) { // // If this is a filter device, then copy the FILE_REMOVABLE_MEDIA // characteristic from the lower device. // if (m_Device->GetAttachedDevice()->Characteristics & FILE_REMOVABLE_MEDIA) { ULONG characteristics; characteristics = m_Device->GetDeviceObject()->Characteristics | FILE_REMOVABLE_MEDIA; m_Device->GetDeviceObject()->Characteristics = characteristics; } m_Device->SetFilterIoType(); } #endif // FX_IS_KERNEL_MODE Done: DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGPNP, "Exiting PnpMatchResources %!STATUS!", status); return status; } VOID FxPkgPnp::PnpAssignInterruptsSyncIrql( VOID ) /*++ Routine Description: Figure out the highest synch irql for each interrupt set which shares a spinlock. foreach(interrupt assigned to this instance) determine the max sync irql in the set set all the associated interrupts to the sync irql set the sync irql on the first interrupt in the set Arguments: None Return Value: None --*/ { PLIST_ENTRY ple; FxInterrupt* pInterrupt; for (ple = m_InterruptListHead.Flink; ple != &m_InterruptListHead; ple = ple->Flink) { KIRQL syncIrql; pInterrupt = CONTAINING_RECORD(ple, FxInterrupt, m_PnpList); syncIrql = pInterrupt->GetResourceIrql(); if (syncIrql == PASSIVE_LEVEL) { // // The irql associated with the resources assigned is passive, // this can happen in the following scenarios: // // (1) no resources were assigned. Skip this interrupt b/c it has // no associated resources. Note: setting the SynchronizeIrql // to PASSIVE_LEVEL is a no-op. // // (2) this interrupt is handled at passive-level. // Set SynchronizeIrql to passive-level and continue. // pInterrupt->SetSyncIrql(PASSIVE_LEVEL); continue; } if (pInterrupt->IsSharedSpinLock() == FALSE) { // // If the interrupt spinlock is not shared, it's sync irql is the // irql assigned to it in the resources. // pInterrupt->SetSyncIrql(syncIrql); } else if (pInterrupt->IsSyncIrqlSet() == FALSE) { FxInterrupt* pFwdInterrupt; PLIST_ENTRY pleFwd; // // Find all of the other interrupts which share the lock and compute // the max sync irql. // for (pleFwd = ple->Flink; pleFwd != &m_InterruptListHead; pleFwd = pleFwd->Flink) { pFwdInterrupt = CONTAINING_RECORD(pleFwd, FxInterrupt, m_PnpList); // // If the 2 do not share the same lock, they are not in the same // set. // if (pFwdInterrupt->SharesLock(pInterrupt) == FALSE) { continue; } if (pFwdInterrupt->GetResourceIrql() > syncIrql) { syncIrql = pFwdInterrupt->GetResourceIrql(); } } // // Now that we found the max sync irql, set it for all interrupts in // the set which share the lock // for (pleFwd = ple->Flink; pleFwd != &m_InterruptListHead; pleFwd = pleFwd->Flink) { pFwdInterrupt = CONTAINING_RECORD(pleFwd, FxInterrupt, m_PnpList); // // If the 2 do not share the same lock, they are not in the same // set. // if (pFwdInterrupt->SharesLock(pInterrupt) == FALSE) { continue; } pFwdInterrupt->SetSyncIrql(syncIrql); } // // Set the sync irql for the first interrupt in the set. We have set // the sync irql for all other interrupts in the set. // pInterrupt->SetSyncIrql(syncIrql); } else { // // If IsSyncIrqlSet is TRUE, we already covered this interrupt in a // previous pass of this loop when we computed the max sync irql for // an interrupt set. // ASSERT(pInterrupt->GetSyncIrql() > PASSIVE_LEVEL); DO_NOTHING(); } } } _Must_inspect_result_ NTSTATUS FxPkgPnp::ValidateCmResource( __inout PCM_PARTIAL_RESOURCE_DESCRIPTOR* CmResourceRaw, __inout PCM_PARTIAL_RESOURCE_DESCRIPTOR* CmResource ) /*++ Routine Description: Makes sure the specified resource is valid. Arguments: CmResourceRaw - the raw resource to validate. CmResource - the translated resources to validate. Return Value: STATUS_SUCCESS if resource is valid or NTSTATUS error. --*/ { NTSTATUS status; FxCollectionEntry* cur; FxCollectionEntry* curRaw; FxResourceCm* res; FxResourceCm* resRaw; PFX_DRIVER_GLOBALS fxDriverGlobals; ASSERT(m_ResourcesRaw != NULL); ASSERT(m_Resources != NULL); res = NULL; resRaw = NULL; fxDriverGlobals = GetDriverGlobals(); // // Find the resource in our list. // for (cur = m_Resources->Start(), curRaw = m_ResourcesRaw->Start(); cur != m_Resources->End(); cur = cur->Next(), curRaw = curRaw->Next()) { res = (FxResourceCm*) cur->m_Object; resRaw = (FxResourceCm*) curRaw->m_Object; if (&res->m_DescriptorClone == *CmResource) { break; } } // // Error out if not found. // if (cur == m_Resources->End()) { status = STATUS_INVALID_PARAMETER; DoTraceLevelMessage( fxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGPNP, "The translated PCM_PARTIAL_RESOURCE_DESCRIPTOR 0x%p is not valid, " "WDFDEVICE 0x%p, %!STATUS!", *CmResource, m_Device->GetHandle(), status); FxVerifierDbgBreakPoint(fxDriverGlobals); goto Done; } // // Error out if the associated raw resource is not the same. // if (&resRaw->m_DescriptorClone != *CmResourceRaw) { status = STATUS_INVALID_PARAMETER; DoTraceLevelMessage( fxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGPNP, "The raw PCM_PARTIAL_RESOURCE_DESCRIPTOR 0x%p is not valid, " "WDFDEVICE 0x%p, %!STATUS!", *CmResourceRaw, m_Device->GetHandle(), status); FxVerifierDbgBreakPoint(fxDriverGlobals); goto Done; } // // Make sure driver didn't change any of the PnP settings. // if (sizeof(res->m_Descriptor) != RtlCompareMemory(&res->m_DescriptorClone, &res->m_Descriptor, sizeof(res->m_Descriptor))) { status = STATUS_INVALID_PARAMETER; DoTraceLevelMessage( fxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGPNP, "The translated PCM_PARTIAL_RESOURCE_DESCRIPTOR 0x%p is not valid, " "driver cannot change the assigned PnP resources, WDFDEVICE 0x%p, " "%!STATUS!", *CmResource, m_Device->GetHandle(), status); FxVerifierDbgBreakPoint(fxDriverGlobals); goto Done; } if (sizeof(resRaw->m_Descriptor) != RtlCompareMemory(&resRaw->m_DescriptorClone, &resRaw->m_Descriptor, sizeof(resRaw->m_Descriptor))) { status = STATUS_INVALID_PARAMETER; DoTraceLevelMessage( fxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGPNP, "The raw PCM_PARTIAL_RESOURCE_DESCRIPTOR 0x%p is not valid, " "driver cannot change the assigned PnP resources, WDFDEVICE 0x%p, " "%!STATUS!", *CmResourceRaw, m_Device->GetHandle(), status); FxVerifierDbgBreakPoint(fxDriverGlobals); goto Done; } // // Return the real descriptor. // ASSERT(res != NULL && resRaw != NULL); *CmResource = &res->m_Descriptor; *CmResourceRaw = &resRaw->m_Descriptor; status = STATUS_SUCCESS; Done: return status; } _Must_inspect_result_ NTSTATUS FxPkgPnp::ValidateInterruptResourceCm( __in PCM_PARTIAL_RESOURCE_DESCRIPTOR CmIntResourceRaw, __in PCM_PARTIAL_RESOURCE_DESCRIPTOR CmIntResource, __in PWDF_INTERRUPT_CONFIG Configuration ) /*++ Routine Description: Makes sure the specified resource is valid for an interrupt resource. Arguments: CmIntResourceRaw - the raw interrupt resource to validate. CmIntResource - the translated interrupt resource to validate. Return Value: STATUS_SUCCESS if resource is valid or NTSTATUS error. --*/ { NTSTATUS status; PLIST_ENTRY le; FxInterrupt* interrupt; ULONG messageCount; PFX_DRIVER_GLOBALS fxDriverGlobals; PCM_PARTIAL_RESOURCE_DESCRIPTOR cmIntResourceRaw; PCM_PARTIAL_RESOURCE_DESCRIPTOR cmIntResource; cmIntResourceRaw = CmIntResourceRaw; cmIntResource = CmIntResource; fxDriverGlobals = GetDriverGlobals(); // // Get the real descriptor not the copy. // status = ValidateCmResource(&cmIntResourceRaw, &cmIntResource); if (!NT_SUCCESS(status)) { goto Done; } // // Make sure this is an interrupt resource. // if (cmIntResourceRaw->Type != CmResourceTypeInterrupt) { status = STATUS_INVALID_PARAMETER; DoTraceLevelMessage( fxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGPNP, "The raw PCM_PARTIAL_RESOURCE_DESCRIPTOR 0x%p is not an " "interrupt resource, WDFDEVICE 0x%p, %!STATUS!", CmIntResourceRaw, m_Device->GetHandle(), status); FxVerifierDbgBreakPoint(fxDriverGlobals); goto Done; } if (cmIntResource->Type != CmResourceTypeInterrupt) { status = STATUS_INVALID_PARAMETER; DoTraceLevelMessage( fxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGPNP, "The translated PCM_PARTIAL_RESOURCE_DESCRIPTOR 0x%p is not an " "interrupt resource, WDFDEVICE 0x%p, %!STATUS!", CmIntResource, m_Device->GetHandle(), status); FxVerifierDbgBreakPoint(fxDriverGlobals); goto Done; } // // Make sure resource was not claimed by another interrupt. // Multi-message MSI 2.2 interrupts: allowed to reuse claimed resources. // Driver must create them sequentially. // Line-based interrupts: allowed to reuse claimed resources. // Driver can create them out-of-order. // Other MSI: not allowed to reuse claimed resources. // messageCount = 0; for (le = m_InterruptListHead.Flink; le != &m_InterruptListHead; le = le->Flink) { interrupt = CONTAINING_RECORD(le, FxInterrupt, m_PnpList); if (cmIntResource != interrupt->GetResources()) { // // Multi-message MSI 2.2 interrupts must be sequential. // if (messageCount != 0) { status = STATUS_INVALID_PARAMETER; DoTraceLevelMessage( fxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGPNP, "Multi-message MSI 2.2 interrupts must be created " "sequentially, WDFDEVICE 0x%p, %!STATUS!", m_Device->GetHandle(), status); FxVerifierDbgBreakPoint(fxDriverGlobals); goto Done; } continue; } if (interrupt->IsWakeCapable() && Configuration->PassiveHandling) { DoTraceLevelMessage( fxDriverGlobals, TRACE_LEVEL_INFORMATION, TRACINGPNP, "The PCM_PARTIAL_RESOURCE_DESCRIPTOR 0x%p was already used " "to create a wakable interrupt 0x%p, WDFDEVICE 0x%p and " "any functional interrupt being shared with wakable interrupt " "can not use passive level handling", CmIntResource, interrupt->GetHandle(), m_Device->GetHandle()); status = STATUS_INVALID_PARAMETER; goto Done; } if (interrupt->IsPassiveHandling() && Configuration->CanWakeDevice) { DoTraceLevelMessage( fxDriverGlobals, TRACE_LEVEL_INFORMATION, TRACINGPNP, "The PCM_PARTIAL_RESOURCE_DESCRIPTOR 0x%p was already used " "to create a passive level interrupt 0x%p, WDFDEVICE 0x%p and " "is now being used to create a wakable interrupt. A functional " "passive level interrupt can not be shared with wakable interrupt", CmIntResource, interrupt->GetHandle(), m_Device->GetHandle()); status = STATUS_INVALID_PARAMETER; goto Done; } // // Check for multi-message MSI 2.2 interrupts. These are allowed // to use the same resource. // We allow line based interrupts to reuse claimed resources. // if (FxInterrupt::_IsMessageInterrupt(cmIntResource->Flags) == FALSE) { DoTraceLevelMessage( fxDriverGlobals, TRACE_LEVEL_INFORMATION, TRACINGPNP, "The PCM_PARTIAL_RESOURCE_DESCRIPTOR 0x%p was already used " "to create interrupt 0x%p, WDFDEVICE 0x%p", CmIntResource, interrupt->GetHandle(), m_Device->GetHandle()); continue; } // // Only allow the correct # of messages. // messageCount++; if (messageCount > cmIntResourceRaw->u.MessageInterrupt.Raw.MessageCount) { status = STATUS_INVALID_PARAMETER; DoTraceLevelMessage( fxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGPNP, "All the MSI 2.2 interrupts for " "PCM_PARTIAL_RESOURCE_DESCRIPTOR 0x%p are already created, " "WDFDEVICE 0x%p, %!STATUS!", CmIntResource, m_Device->GetHandle(), status); FxVerifierDbgBreakPoint(fxDriverGlobals); goto Done; } } status = STATUS_SUCCESS; Done: return status; } #define RESTART_START_ACHIEVED_NAME L"StartAchieved" #define RESTART_START_TIME_NAME L"StartTime" #define RESTART_COUNT_NAME L"Count" const PWCHAR FxPkgPnp::m_RestartStartAchievedName = RESTART_START_ACHIEVED_NAME; const PWCHAR FxPkgPnp::m_RestartStartTimeName = RESTART_START_TIME_NAME; const PWCHAR FxPkgPnp::m_RestartCountName = RESTART_COUNT_NAME; const ULONG FxPkgPnp::m_RestartTimePeriodMaximum = 60; const ULONG FxPkgPnp::m_RestartCountMaximum = 5; BOOLEAN FxPkgPnp::PnpIncrementRestartCountLogic( _In_ HANDLE RestartKey, _In_ BOOLEAN CreatedNewKey ) /*++ Routine Description: This routine determines if this device should ask the bus driver to reenumerate the device. This is determined by how many times the entire stack has asked for a restart within a given period. This is stack wide because the settings are stored in a key in the device node itself (which all devices share). The period and number of times a restart are attempted are defined as constants (m_RestartTimePeriodMaximum, m_RestartCountMaximum)in this class. They are current defined as a period of 60 seconds and a restart max count of 5. The settings are stored in a volatile key so that they do not persist across machine reboots. Persisting across reboots makes no sense if we restrict the number of restarts w/in a period. The rules are as follows 1) if the key does not exist, treat this as the beginning of the period and ask for a reenumeration 2) if the key exists a) if the beginning of the period and the restart count cannot be read do not ask for a reenumeration b) if the beginning of the period is after the current time, either the current tick count has wrapped or the key has somehow survived a reboot. Either way, treat this as a reset of the period and ask for a reenumeration c) if the current time is after the period start time and within the restart period, increment the restart count. if the count is <= the max restart count, ask for a reenumeration. If it exceeds the max, do not ask for a reenumeration. d) if the current time is after the period stat time and exceeds the maximum period, and if the device as reached the started state, reset the period, count, and started state, then ask for a reenumeration. Considerations: There is a reenumeration loop that a device can get caught in. If a device takes more than m_RestartTimePeriodMaximum to fail m_RestartCountMaximum times then the device will be caught in this loop. If it is failing on the way to PnpEventStarted then the device will likely cause a 9F bugcheck. This is because they hold a power lock while in this loop. If the device fails after PnpEventStarted then pnp can progress and the device can loop here indefinitely. We have shipped with this behavior for several releases, so we are hesitant to completely change this behavior. The concern is that a device out there relies on this behavior. Arguments: RestartKey - opened handle to the Restart registry key CreatedNewKey - TRUE if the Restart key was created just now Return Value: TRUE if a restart should be requested. --*/ { NTSTATUS status = STATUS_SUCCESS; ULONG count; LARGE_INTEGER currentTickCount, startTickCount; BOOLEAN started, writeTick, writeCount, writeStarted; DECLARE_CONST_UNICODE_STRING(valueNameStartTime, RESTART_START_TIME_NAME); DECLARE_CONST_UNICODE_STRING(valueNameCount, RESTART_COUNT_NAME); DECLARE_CONST_UNICODE_STRING(valueNameStartAchieved, RESTART_START_ACHIEVED_NAME); count = 0; started = FALSE; writeTick = FALSE; writeCount = FALSE; writeStarted = FALSE; Mx::MxQueryTickCount(&currentTickCount); started = m_AchievedStart; if (started) { // // Save the fact the driver started without failing // writeStarted = TRUE; } // // If the key was created right now, there is nothing to check, just write out // the data. // if (CreatedNewKey) { writeTick = TRUE; writeCount = TRUE; // // First restart // count = 1; } else { ULONG length, type; // // First try to get the start time of when we first attempted a restart // status = FxRegKey::_QueryValue(GetDriverGlobals(), RestartKey, &valueNameStartTime, sizeof(startTickCount.QuadPart), &startTickCount.QuadPart, &length, &type); if (NT_SUCCESS(status) && length == sizeof(startTickCount.QuadPart) && type == REG_BINARY) { // // Now try to get the last restart count // status = FxRegKey::_QueryULong(RestartKey, &valueNameCount, &count); if (status == STATUS_OBJECT_NAME_NOT_FOUND) { // // We read the start time, but not the count. Assume there was // at least one previous restart. // count = 1; status = STATUS_SUCCESS; } } if (NT_SUCCESS(status)) { if (currentTickCount.QuadPart < startTickCount.QuadPart) { // // Somehow the key survived a reboot or the clock overflowed // and the current time is less then the last time we started // timing restarts. Either way, just treat this as the first // time we are restarting. // writeTick = TRUE; writeCount = TRUE; count = 1; } else { LONGLONG delta; // // Compute the difference in time in 100 ns units // delta = (currentTickCount.QuadPart - startTickCount.QuadPart) * Mx::MxQueryTimeIncrement(); if (delta <= WDF_ABS_TIMEOUT_IN_SEC(m_RestartTimePeriodMaximum)) { // // We are within the time limit, see if we are within the // count limit count++; // // The count starts at one, so include the maximum in the // compare. // if (count <= m_RestartCountMaximum) { writeCount = TRUE; } else { // // Exceeded the restart count, do not attempt to restart // the device. // status = STATUS_UNSUCCESSFUL; } } else { if (started == FALSE) { ULONG length, type, value; status = FxRegKey::_QueryValue(GetDriverGlobals(), RestartKey, &valueNameStartAchieved, sizeof(value), &value, &length, &type); if (!NT_SUCCESS(status) || length != sizeof(value) || type != REG_DWORD) { value = 0; } started = value != 0; status = STATUS_SUCCESS; } if (started) { // // Exceeded the time limit. This is treated as a reset of // the time limit, so we will try to restart and reset the // start time and restart count. // writeTick = TRUE; writeCount = TRUE; count = 1; // // Erase the fact the driver once started and // make it do it again to get another 5 attempts to // restart. // writeStarted = TRUE; started = FALSE; } else { // // Device never started // status = STATUS_UNSUCCESSFUL; } } } } } if (writeTick) { // // Write out the time and the count // NTSTATUS status2; status2 = FxRegKey::_SetValue(RestartKey, (PUNICODE_STRING)&valueNameStartTime, REG_BINARY, &currentTickCount.QuadPart, sizeof(currentTickCount.QuadPart)); // // Don't let status report success if it was an error prior to _SetValue // if(NT_SUCCESS(status)) { status = status2; } } if (NT_SUCCESS(status) && writeCount) { status = FxRegKey::_SetValue(RestartKey, (PUNICODE_STRING)&valueNameCount, REG_DWORD, &count, sizeof(count)); } if (writeStarted) { NTSTATUS status2; DWORD value = started; status2 = FxRegKey::_SetValue(RestartKey, (PUNICODE_STRING)&valueNameStartAchieved, REG_DWORD, &value, sizeof(value)); // // Don't let status report success if it was an error prior to _SetValue // if(NT_SUCCESS(status)) { status = status2; } } return NT_SUCCESS(status) ? TRUE : FALSE; }
27.604282
99
0.627698
IT-Enthusiast-Nepal
4eb54dbccc98e3fabf5187753c48af4e53b00cce
1,163
cpp
C++
src/eepp/ui/cuimenuitem.cpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
src/eepp/ui/cuimenuitem.cpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
src/eepp/ui/cuimenuitem.cpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
#include <eepp/ui/cuimenuitem.hpp> #include <eepp/ui/cuimenu.hpp> namespace EE { namespace UI { cUIMenuItem::cUIMenuItem( cUIPushButton::CreateParams& Params ) : cUIPushButton( Params ) { ApplyDefaultTheme(); } cUIMenuItem::~cUIMenuItem() { } Uint32 cUIMenuItem::Type() const { return UI_TYPE_MENUITEM; } bool cUIMenuItem::IsType( const Uint32& type ) const { return cUIMenuItem::Type() == type ? true : cUIPushButton::IsType( type ); } void cUIMenuItem::SetTheme( cUITheme * Theme ) { cUIControl::SetThemeControl( Theme, "menuitem" ); DoAfterSetTheme(); } Uint32 cUIMenuItem::OnMouseEnter( const eeVector2i &Pos, const Uint32 Flags ) { cUIPushButton::OnMouseEnter( Pos, Flags ); reinterpret_cast<cUIMenu*> ( Parent() )->SetItemSelected( this ); return 1; } void cUIMenuItem::OnStateChange() { cUIMenu * tMenu = reinterpret_cast<cUIMenu*> ( Parent() ); if ( mSkinState->GetState() == cUISkinState::StateSelected ) { mTextBox->Color( tMenu->mFontSelectedColor ); } else if ( mSkinState->GetState() == cUISkinState::StateMouseEnter ) { mTextBox->Color( tMenu->mFontOverColor ); } else { mTextBox->Color( tMenu->mFontColor ); } } }}
23.734694
79
0.712812
dogtwelve
4eb6e778ea6495c583adb743b192c1f921f6e222
291
cpp
C++
src/objects/mesh.cpp
hardware/ObjectViewer
718922e00a6f3e83510e6091f7630ac3c0e5066b
[ "MIT" ]
52
2015-02-26T04:00:19.000Z
2021-04-25T03:18:25.000Z
src/objects/mesh.cpp
hardware/ObjectViewer
718922e00a6f3e83510e6091f7630ac3c0e5066b
[ "MIT" ]
2
2017-03-15T02:11:06.000Z
2017-12-04T12:26:06.000Z
src/objects/mesh.cpp
hardware/ObjectViewer
718922e00a6f3e83510e6091f7630ac3c0e5066b
[ "MIT" ]
21
2015-09-09T13:59:02.000Z
2021-04-25T03:18:27.000Z
#include "mesh.h" Mesh::Mesh(const string& name, unsigned int numIndices, unsigned int baseVertex, unsigned int baseIndex) : m_name(name), m_numIndices(numIndices), m_baseVertex(baseVertex), m_baseIndex(baseIndex) {} Mesh::~Mesh() {}
20.785714
35
0.61512
hardware
4ebc7840939c14250b0910c9d1a7d784f9ff0ebe
216
cpp
C++
testclassnonqt.cpp
edgecrusher8074/Templates_Qt5DesignPattern_Assignment7
cad0ad7f3e2aec3f50cb0c397a5c8369bae49f0c
[ "WTFPL" ]
null
null
null
testclassnonqt.cpp
edgecrusher8074/Templates_Qt5DesignPattern_Assignment7
cad0ad7f3e2aec3f50cb0c397a5c8369bae49f0c
[ "WTFPL" ]
null
null
null
testclassnonqt.cpp
edgecrusher8074/Templates_Qt5DesignPattern_Assignment7
cad0ad7f3e2aec3f50cb0c397a5c8369bae49f0c
[ "WTFPL" ]
null
null
null
#include "testclassnonqt.h" #include <QDebug> TestClassNonQt::TestClassNonQt() { qInfo() << "Created"; } void TestClassNonQt::setObjectName(const QString &name) { qInfo() << "doin nohting for: " << name; }
16.615385
55
0.671296
edgecrusher8074
4ebd7a21ffd92c247628b585c7867b42bff0a3d6
460
hpp
C++
worker/environment_lock.hpp
5cript/minide2
3464d84da3d6029450518de43ab15cecc9de75c7
[ "MIT" ]
null
null
null
worker/environment_lock.hpp
5cript/minide2
3464d84da3d6029450518de43ab15cecc9de75c7
[ "MIT" ]
null
null
null
worker/environment_lock.hpp
5cript/minide2
3464d84da3d6029450518de43ab15cecc9de75c7
[ "MIT" ]
1
2020-08-27T17:00:54.000Z
2020-08-27T17:00:54.000Z
#pragma once #include <functional> #include <string> /** * You can safely change the environment of the worker here. * But only here. Using this ensures that multiple ran processes can be started without conflict. */ void environmentLockedDo(std::function <void()> const& work); /** * Do something (like running a program) with a modified PATH. */ void doWithModifiedPath(std::function <void()> const& work, std::string const& path);
28.75
99
0.702174
5cript
4ebfcaff2f6b636206449eb3b09bb0d270ce8142
1,765
hpp
C++
headers/flat.hpp/flat_fwd.hpp
BlackMATov/flat.hpp
98184d75a8227e47ac426b590fd23ead4859bb88
[ "MIT" ]
71
2019-05-04T01:34:33.000Z
2022-01-31T13:46:47.000Z
headers/flat.hpp/flat_fwd.hpp
BlackMATov/flat.hpp
98184d75a8227e47ac426b590fd23ead4859bb88
[ "MIT" ]
21
2019-05-04T11:23:59.000Z
2020-11-29T22:26:24.000Z
headers/flat.hpp/flat_fwd.hpp
BlackMATov/flat.hpp
98184d75a8227e47ac426b590fd23ead4859bb88
[ "MIT" ]
1
2019-05-06T11:04:38.000Z
2019-05-06T11:04:38.000Z
/******************************************************************************* * This file is part of the "https://github.com/blackmatov/flat.hpp" * For conditions of distribution and use, see copyright notice in LICENSE.md * Copyright (C) 2019-2021, by Matvey Cherevko (blackmatov@gmail.com) ******************************************************************************/ #pragma once #include <algorithm> #include <cassert> #include <functional> #include <initializer_list> #include <stdexcept> #include <type_traits> #include <utility> #include <vector> #include "detail/eq_compare.hpp" #include "detail/is_allocator.hpp" #include "detail/is_sorted.hpp" #include "detail/is_transparent.hpp" #include "detail/iter_traits.hpp" #include "detail/pair_compare.hpp" namespace flat_hpp { struct sorted_range_t {}; inline constexpr sorted_range_t sorted_range = sorted_range_t(); struct sorted_unique_range_t : public sorted_range_t {}; inline constexpr sorted_unique_range_t sorted_unique_range = sorted_unique_range_t(); template < typename Key , typename Compare = std::less<Key> , typename Container = std::vector<Key> > class flat_set; template < typename Key , typename Compare = std::less<Key> , typename Container = std::vector<Key> > class flat_multiset; template < typename Key , typename Value , typename Compare = std::less<Key> , typename Container = std::vector<std::pair<Key, Value>> > class flat_map; template < typename Key , typename Value , typename Compare = std::less<Key> , typename Container = std::vector<std::pair<Key, Value>> > class flat_multimap; }
32.090909
89
0.616431
BlackMATov
4ec3feb482c23d9b5773aec636feda4ae2fc22c2
12,678
cpp
C++
src/nyx/features/image_moments_nontriv.cpp
friskluft/nyxus-1
4cac89732be4d46b80716f118c12d016ae5231a1
[ "MIT" ]
null
null
null
src/nyx/features/image_moments_nontriv.cpp
friskluft/nyxus-1
4cac89732be4d46b80716f118c12d016ae5231a1
[ "MIT" ]
6
2022-02-09T20:42:43.000Z
2022-03-24T20:14:47.000Z
src/nyx/features/image_moments_nontriv.cpp
friskluft/nyxus-1
4cac89732be4d46b80716f118c12d016ae5231a1
[ "MIT" ]
4
2022-02-03T20:26:23.000Z
2022-02-17T02:59:27.000Z
#include "image_moments.h" void ImageMomentsFeature::osized_calculate(LR& r, ImageLoader& imlo) { const ImageMatrix& im = r.aux_image_matrix; ReadImageMatrix_nontriv I(r.aabb); calcOrigins_nontriv (imlo, I); calcSpatialMoments_nontriv (imlo, I); calcCentralMoments_nontriv (imlo, I); calcNormCentralMoments_nontriv (imlo, I); calcNormSpatialMoments_nontriv (imlo, I); calcHuInvariants_nontriv (imlo, I); WriteImageMatrix_nontriv W ("ImageMomentsFeature_osized_calculate_W", r.label); W.init_with_cloud_distance_to_contour_weights (r.osized_pixel_cloud, r.aabb, r.contour); calcOrigins_nontriv (W); calcWeightedSpatialMoments_nontriv (W); calcWeightedCentralMoments_nontriv (W); calcWeightedHuInvariants_nontriv (W); } double ImageMomentsFeature::Moment_nontriv (ImageLoader& imlo, ReadImageMatrix_nontriv& I, int p, int q) { // calc (p+q)th moment of object double sum = 0; for (size_t x = 0; x < I.get_width(); x++) { for (size_t y = 0; y < I.get_height(); y++) { sum += I.get_at(imlo, y, x) * pow(x, p) * pow(y, q); } } return sum; } double ImageMomentsFeature::Moment_nontriv (WriteImageMatrix_nontriv & I, int p, int q) { // calc (p+q)th moment of object double sum = 0; for (size_t x = 0; x < I.get_width(); x++) { for (size_t y = 0; y < I.get_height(); y++) { sum += I.get_at(y, x) * pow(x, p) * pow(y, q); } } return sum; } void ImageMomentsFeature::calcOrigins_nontriv (ImageLoader& imlo, ReadImageMatrix_nontriv& I) { // calc orgins double m00 = Moment_nontriv (imlo, I, 0, 0); originOfX = Moment_nontriv (imlo, I, 1, 0) / m00; originOfY = Moment_nontriv (imlo, I, 0, 1) / m00; } void ImageMomentsFeature::calcOrigins_nontriv (WriteImageMatrix_nontriv & I) { // calc orgins double m00 = Moment_nontriv (I, 0, 0); originOfX = Moment_nontriv (I, 1, 0) / m00; originOfY = Moment_nontriv (I, 0, 1) / m00; } double ImageMomentsFeature::CentralMom_nontriv (ImageLoader& imlo, ReadImageMatrix_nontriv& I, int p, int q) { // calculate central moment double sum = 0; for (int x = 0; x < I.get_width(); x++) { for (int y = 0; y < I.get_height(); y++) { sum += I.get_at(imlo, y, x) * pow((double(x) - originOfX), p) * pow((double(y) - originOfY), q); } } return sum; } double ImageMomentsFeature::CentralMom_nontriv (WriteImageMatrix_nontriv& W, int p, int q) { // calculate central moment double sum = 0; for (int x = 0; x < W.get_width(); x++) { for (int y = 0; y < W.get_height(); y++) { sum += W.get_at (y, x) * pow((double(x) - originOfX), p) * pow((double(y) - originOfY), q); } } return sum; } // https://handwiki.org/wiki/Standardized_moment double ImageMomentsFeature::NormSpatMom_nontriv (ImageLoader& imlo, ReadImageMatrix_nontriv& I, int p, int q) { double stddev = CentralMom_nontriv (imlo, I, 2, 2); int w = std::max(q, p); double normCoef = pow(stddev, w); double retval = CentralMom_nontriv(imlo, I, p, q) / normCoef; return retval; } double ImageMomentsFeature::NormCentralMom_nontriv (ImageLoader& imlo, ReadImageMatrix_nontriv& I, int p, int q) { double temp = ((double(p) + double(q)) / 2.0) + 1.0; double retval = CentralMom_nontriv (imlo, I, p, q) / pow(Moment_nontriv (imlo, I, 0, 0), temp); return retval; } double ImageMomentsFeature::NormCentralMom_nontriv (WriteImageMatrix_nontriv& W, int p, int q) { double temp = ((double(p) + double(q)) / 2.0) + 1.0; double retval = CentralMom_nontriv (W, p, q) / pow(Moment_nontriv (W, 0, 0), temp); return retval; } void ImageMomentsFeature::calcSpatialMoments_nontriv (ImageLoader& imlo, ReadImageMatrix_nontriv& I) { m00 = Moment_nontriv (imlo, I, 0, 0); m01 = Moment_nontriv (imlo, I, 0, 1); m02 = Moment_nontriv (imlo, I, 0, 2); m03 = Moment_nontriv (imlo, I, 0, 3); m10 = Moment_nontriv (imlo, I, 1, 0); m11 = Moment_nontriv (imlo, I, 1, 1); m12 = Moment_nontriv (imlo, I, 1, 2); m20 = Moment_nontriv (imlo, I, 2, 0); m21 = Moment_nontriv (imlo, I, 2, 1); m30 = Moment_nontriv (imlo, I, 3, 0); } void ImageMomentsFeature::calcWeightedSpatialMoments_nontriv (WriteImageMatrix_nontriv& W) { wm00 = Moment_nontriv (W, 0, 0); wm01 = Moment_nontriv (W, 0, 1); wm02 = Moment_nontriv (W, 0, 2); wm03 = Moment_nontriv (W, 0, 3); wm10 = Moment_nontriv (W, 1, 0); wm11 = Moment_nontriv (W, 1, 1); wm12 = Moment_nontriv (W, 1, 2); wm20 = Moment_nontriv (W, 2, 0); wm21 = Moment_nontriv (W, 2, 1); wm30 = Moment_nontriv (W, 3, 0); } void ImageMomentsFeature::calcCentralMoments_nontriv (ImageLoader& imlo, ReadImageMatrix_nontriv& I) { mu02 = CentralMom_nontriv (imlo, I, 0, 2); mu03 = CentralMom_nontriv (imlo, I, 0, 3); mu11 = CentralMom_nontriv (imlo, I, 1, 1); mu12 = CentralMom_nontriv (imlo, I, 1, 2); mu20 = CentralMom_nontriv (imlo, I, 2, 0); mu21 = CentralMom_nontriv (imlo, I, 2, 1); mu30 = CentralMom_nontriv (imlo, I, 3, 0); } void ImageMomentsFeature::calcWeightedCentralMoments_nontriv (WriteImageMatrix_nontriv& W) { wmu02 = CentralMom_nontriv (W, 0, 2); wmu03 = CentralMom_nontriv (W, 0, 3); wmu11 = CentralMom_nontriv (W, 1, 1); wmu12 = CentralMom_nontriv (W, 1, 2); wmu20 = CentralMom_nontriv (W, 2, 0); wmu21 = CentralMom_nontriv (W, 2, 1); wmu30 = CentralMom_nontriv (W, 3, 0); } void ImageMomentsFeature::calcNormCentralMoments_nontriv (ImageLoader& imlo, ReadImageMatrix_nontriv& I) { nu02 = NormCentralMom_nontriv (imlo, I, 0, 2); nu03 = NormCentralMom_nontriv (imlo, I, 0, 3); nu11 = NormCentralMom_nontriv (imlo, I, 1, 1); nu12 = NormCentralMom_nontriv (imlo, I, 1, 2); nu20 = NormCentralMom_nontriv (imlo, I, 2, 0); nu21 = NormCentralMom_nontriv (imlo, I, 2, 1); nu30 = NormCentralMom_nontriv (imlo, I, 3, 0); } void ImageMomentsFeature::calcNormSpatialMoments_nontriv (ImageLoader& imlo, ReadImageMatrix_nontriv& I) { w00 = NormSpatMom_nontriv (imlo, I, 0, 0); w01 = NormSpatMom_nontriv (imlo, I, 0, 1); w02 = NormSpatMom_nontriv (imlo, I, 0, 2); w03 = NormSpatMom_nontriv (imlo, I, 0, 3); w10 = NormSpatMom_nontriv (imlo, I, 1, 0); w20 = NormSpatMom_nontriv (imlo, I, 2, 0); w30 = NormSpatMom_nontriv (imlo, I, 3, 0); } std::tuple<double, double, double, double, double, double, double> ImageMomentsFeature::calcHuInvariants_imp_nontriv (ImageLoader& imlo, ReadImageMatrix_nontriv& I) { // calculate 7 invariant moments double h1 = NormCentralMom_nontriv (imlo, I, 2, 0) + NormCentralMom_nontriv (imlo, I, 0, 2); double h2 = pow((NormCentralMom_nontriv (imlo, I, 2, 0) - NormCentralMom_nontriv (imlo, I, 0, 2)), 2) + 4 * (pow(NormCentralMom_nontriv (imlo, I, 1, 1), 2)); double h3 = pow((NormCentralMom_nontriv (imlo, I, 3, 0) - 3 * NormCentralMom_nontriv (imlo, I, 1, 2)), 2) + pow((3 * NormCentralMom_nontriv (imlo, I, 2, 1) - NormCentralMom_nontriv (imlo, I, 0, 3)), 2); double h4 = pow((NormCentralMom_nontriv (imlo, I, 3, 0) + NormCentralMom_nontriv (imlo, I, 1, 2)), 2) + pow((NormCentralMom_nontriv (imlo, I, 2, 1) + NormCentralMom_nontriv (imlo, I, 0, 3)), 2); double h5 = (NormCentralMom_nontriv (imlo, I, 3, 0) - 3 * NormCentralMom_nontriv (imlo, I, 1, 2)) * (NormCentralMom_nontriv (imlo, I, 3, 0) + NormCentralMom_nontriv (imlo, I, 1, 2)) * (pow(NormCentralMom_nontriv (imlo, I, 3, 0) + NormCentralMom_nontriv (imlo, I, 1, 2), 2) - 3 * pow(NormCentralMom_nontriv (imlo, I, 2, 1) + NormCentralMom_nontriv (imlo, I, 0, 3), 2)) + (3 * NormCentralMom_nontriv (imlo, I, 2, 1) - NormCentralMom_nontriv (imlo, I, 0, 3)) * (NormCentralMom_nontriv (imlo, I, 2, 1) + NormCentralMom_nontriv (imlo, I, 0, 3)) * (pow(3 * (NormCentralMom_nontriv (imlo, I, 3, 0) + NormCentralMom_nontriv (imlo, I, 1, 2)), 2) - pow(NormCentralMom_nontriv (imlo, I, 2, 1) + NormCentralMom_nontriv (imlo, I, 0, 3), 2)); double h6 = (NormCentralMom_nontriv (imlo, I, 2, 0) - NormCentralMom_nontriv (imlo, I, 0, 2)) * (pow(NormCentralMom_nontriv (imlo, I, 3, 0) + NormCentralMom_nontriv (imlo, I, 1, 2), 2) - pow(NormCentralMom_nontriv (imlo, I, 2, 1) + NormCentralMom_nontriv (imlo, I, 0, 3), 2)) + (4 * NormCentralMom_nontriv (imlo, I, 1, 1) * (NormCentralMom_nontriv (imlo, I, 3, 0) + NormCentralMom_nontriv (imlo, I, 1, 2)) * NormCentralMom_nontriv (imlo, I, 2, 1) + NormCentralMom_nontriv (imlo, I, 0, 3)); double h7 = (3 * NormCentralMom_nontriv (imlo, I, 2, 1) - NormCentralMom_nontriv (imlo, I, 0, 3)) * (NormCentralMom_nontriv (imlo, I, 3, 0) + NormCentralMom_nontriv (imlo, I, 1, 2)) * (pow(NormCentralMom_nontriv (imlo, I, 3, 0) + NormCentralMom_nontriv (imlo, I, 1, 2), 2) - 3 * pow(NormCentralMom_nontriv (imlo, I, 2, 1) + NormCentralMom_nontriv (imlo, I, 0, 3), 2)) - (NormCentralMom_nontriv (imlo, I, 3, 0) - 3 * NormCentralMom_nontriv (imlo, I, 1, 2)) * (NormCentralMom_nontriv (imlo, I, 2, 1) + NormCentralMom_nontriv (imlo, I, 0, 3)) * (3 * pow(NormCentralMom_nontriv (imlo, I, 3, 0) + NormCentralMom_nontriv (imlo, I, 1, 2), 2) - pow(NormCentralMom_nontriv (imlo, I, 2, 1) + NormCentralMom_nontriv (imlo, I, 0, 3), 2)); return { h1, h2, h3, h4, h5, h6, h7 }; } std::tuple<double, double, double, double, double, double, double> ImageMomentsFeature::calcHuInvariants_imp_nontriv (WriteImageMatrix_nontriv& W) { // calculate 7 invariant moments double h1 = NormCentralMom_nontriv (W, 2, 0) + NormCentralMom_nontriv (W, 0, 2); double h2 = pow((NormCentralMom_nontriv (W, 2, 0) - NormCentralMom_nontriv (W, 0, 2)), 2) + 4 * (pow(NormCentralMom_nontriv (W, 1, 1), 2)); double h3 = pow((NormCentralMom_nontriv (W, 3, 0) - 3 * NormCentralMom_nontriv (W, 1, 2)), 2) + pow((3 * NormCentralMom_nontriv (W, 2, 1) - NormCentralMom_nontriv (W, 0, 3)), 2); double h4 = pow((NormCentralMom_nontriv (W, 3, 0) + NormCentralMom_nontriv (W, 1, 2)), 2) + pow((NormCentralMom_nontriv (W, 2, 1) + NormCentralMom_nontriv (W, 0, 3)), 2); double h5 = (NormCentralMom_nontriv (W, 3, 0) - 3 * NormCentralMom_nontriv (W, 1, 2)) * (NormCentralMom_nontriv (W, 3, 0) + NormCentralMom_nontriv (W, 1, 2)) * (pow(NormCentralMom_nontriv (W, 3, 0) + NormCentralMom_nontriv (W, 1, 2), 2) - 3 * pow(NormCentralMom_nontriv (W, 2, 1) + NormCentralMom_nontriv (W, 0, 3), 2)) + (3 * NormCentralMom_nontriv (W, 2, 1) - NormCentralMom_nontriv (W, 0, 3)) * (NormCentralMom_nontriv (W, 2, 1) + NormCentralMom_nontriv (W, 0, 3)) * (pow(3 * (NormCentralMom_nontriv (W, 3, 0) + NormCentralMom_nontriv (W, 1, 2)), 2) - pow(NormCentralMom_nontriv (W, 2, 1) + NormCentralMom_nontriv (W, 0, 3), 2)); double h6 = (NormCentralMom_nontriv (W, 2, 0) - NormCentralMom_nontriv (W, 0, 2)) * (pow(NormCentralMom_nontriv (W, 3, 0) + NormCentralMom_nontriv (W, 1, 2), 2) - pow(NormCentralMom_nontriv (W, 2, 1) + NormCentralMom_nontriv (W, 0, 3), 2)) + (4 * NormCentralMom_nontriv (W, 1, 1) * (NormCentralMom_nontriv (W, 3, 0) + NormCentralMom_nontriv (W, 1, 2)) * NormCentralMom_nontriv (W, 2, 1) + NormCentralMom_nontriv (W, 0, 3)); double h7 = (3 * NormCentralMom_nontriv (W, 2, 1) - NormCentralMom_nontriv (W, 0, 3)) * (NormCentralMom_nontriv (W, 3, 0) + NormCentralMom_nontriv (W, 1, 2)) * (pow(NormCentralMom_nontriv (W, 3, 0) + NormCentralMom_nontriv (W, 1, 2), 2) - 3 * pow(NormCentralMom_nontriv (W, 2, 1) + NormCentralMom_nontriv (W, 0, 3), 2)) - (NormCentralMom_nontriv (W, 3, 0) - 3 * NormCentralMom_nontriv (W, 1, 2)) * (NormCentralMom_nontriv (W, 2, 1) + NormCentralMom_nontriv (W, 0, 3)) * (3 * pow(NormCentralMom_nontriv (W, 3, 0) + NormCentralMom_nontriv (W, 1, 2), 2) - pow(NormCentralMom_nontriv (W, 2, 1) + NormCentralMom_nontriv (W, 0, 3), 2)); return { h1, h2, h3, h4, h5, h6, h7 }; } void ImageMomentsFeature::calcHuInvariants_nontriv (ImageLoader& imlo, ReadImageMatrix_nontriv& I) { std::tie(hm1, hm2, hm3, hm4, hm5, hm6, hm7) = calcHuInvariants_imp_nontriv (imlo, I); } void ImageMomentsFeature::calcWeightedHuInvariants_nontriv (WriteImageMatrix_nontriv& W) { std::tie(whm1, whm2, whm3, whm4, whm5, whm6, whm7) = calcHuInvariants_imp_nontriv (W); }
51.120968
279
0.640401
friskluft
4eca52873069c923e043d0e2c62cae7a78d49901
123
cpp
C++
snake/main.cpp
kriss95/snake-game
cfd2121e6818f08b5275b16c03261c8ab538530e
[ "MIT" ]
null
null
null
snake/main.cpp
kriss95/snake-game
cfd2121e6818f08b5275b16c03261c8ab538530e
[ "MIT" ]
null
null
null
snake/main.cpp
kriss95/snake-game
cfd2121e6818f08b5275b16c03261c8ab538530e
[ "MIT" ]
null
null
null
#include "Game.h" using namespace std; int main() { Game snakeGame; snakeGame.Menu(); system("pause"); return 0; }
9.461538
20
0.650407
kriss95
4ecc8b25162369e3931e2922a2d6775ead25665d
389
cpp
C++
factorial.cpp
VivekWesley/CPP_BASICS
536d4e3b6c94e13ab5263f38c3a2e80f077b2d29
[ "MIT" ]
null
null
null
factorial.cpp
VivekWesley/CPP_BASICS
536d4e3b6c94e13ab5263f38c3a2e80f077b2d29
[ "MIT" ]
null
null
null
factorial.cpp
VivekWesley/CPP_BASICS
536d4e3b6c94e13ab5263f38c3a2e80f077b2d29
[ "MIT" ]
1
2022-01-17T09:27:19.000Z
2022-01-17T09:27:19.000Z
// factorial of n // SAMPLE OUTPUT: // enter a number: // 4 // 24 #include <iostream> using namespace std; int fact(int n) { int factorial = 1; for (int i = 2; i <= n; i++) { factorial *= i; } return factorial; } int main() { int n; cout << "enter a number: " << endl; cin >> n; int ans = fact(n); cout << ans << endl; return 0; }
12.15625
39
0.501285
VivekWesley
4ecd07bb7a5958abe7f2535a201adff7455d16f7
4,751
cpp
C++
SORAL/C++/con_area.cpp
tvrusso/soral
bc4a27e4330458934d3224e8bdaf4cfcb189752b
[ "MIT" ]
null
null
null
SORAL/C++/con_area.cpp
tvrusso/soral
bc4a27e4330458934d3224e8bdaf4cfcb189752b
[ "MIT" ]
null
null
null
SORAL/C++/con_area.cpp
tvrusso/soral
bc4a27e4330458934d3224e8bdaf4cfcb189752b
[ "MIT" ]
null
null
null
/********************************************************************* * SARBayes OPTIMAL RESOURCE ALLOCATION LIBRARY 2001-03 * * * *********************************************************************/ /** \file con_area.cpp * \brief con_area.cpp Implementation of the AreaAssignment container object. * * * Implementation of the AreaAssignment container object. * This one holds the (area, time) details for a particular resource. * That is, it stores the area number and the amount of time the given * resource is going to search there. * * <b>Version History</b> * * \verbatim *-----+---------+-----+----------------------------------------------------- * Who | When | Ver | What *-----+---------+-----+----------------------------------------------------- * ME | 05dec01 | 1 | Created. *-----+---------+-----+----------------------------------------------------- * GT | 25feb02 | 2 | Modifications: AreaAssignment now encapsulates a * | | | resource number, rather than an area number. *-----+---------+-----+----------------------------------------------------- * ASO | 10dec02 | 3 | Undid change 2 *-----+---------+-----+----------------------------------------------------- * crt | 13jan03 | 3.5 | Documentation. cvs 1.3 *-----+---------+-----+----------------------------------------------------- * crt | 06mar03 | 4 | Cleaned up. Removed container base. (cvs 1.5) *-----+---------+-----+----------------------------------------------------- * crt | 01may03 | 5 | Defined copy ctor; const'd *-----+---------+-----+----------------------------------------------------- * \endverbatim */ //===========================================================================// // Written by Michael Eldridge and Gareth Thompson http://sarbayes.org // //---------------------------------------------------------------------------// // The SORAL implementation is free software, but it is Copyright (C) // // 2001-2003 the authors and Monash University (the SARBayes project). // // It is distributed under the terms of the GNU General Public License. // // See the file COPYING for copying permission. // // // // If those licencing arrangements are not satisfactory, please contact us! // // We are willing to offer alternative arrangements, if the need should arise// // // // THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED OR // // IMPLIED. ANY USE IS AT YOUR OWN RISK. // // // // Permission is hereby granted to use or copy this program for any purpose, // // provided the above notices are retained on all copies. Permission to // // modify the code and to distribute modified code is granted, provided the // // above notices are retained, in accordance with the GNU GPL. // //===========================================================================// #include "containr.h" /**** AreaAssignment() ******************************************************/ /// Constructor for AreaAssignment, given (area number, time). /** * Author : Michael Eldridge */ AreaAssignment::AreaAssignment(const int p_areaNum, const double p_time) : time(p_time), areaNum(p_areaNum) { //\todo should set in body and check time > 0. ASO 10/12/02 } /**** AreaAssignment copy ctor *********************************************/ /// Copy constructor for AreaAssignment /** * Author : Charles Twardy */ AreaAssignment::AreaAssignment(const AreaAssignment &p_areaAssignment) : areaNum(p_areaAssignment.getAreaNum()), time(p_areaAssignment.getTime()) { } /**** getAreaNum() **********************************************************/ /// Returns the area number stored in this AreaAssignment /** * We use a "get" function with no "set" function (rather than * just declaring the variable public) so that the calling * function cannot change the data. * * Author : Michael Eldridge * */ int AreaAssignment::getAreaNum(void) const { return areaNum; } /**** getTime() *************************************************************/ /// Returns the time stored in this AreaAssignment /** * We use a "get" function with no "set" function (rather than * just declaring the variable public) so that the calling * function cannot change the data. * * Author : Michael Eldridge * */ double AreaAssignment::getTime(void) const { return time; }
41.675439
79
0.459272
tvrusso
4ed3d6ead5a7b693656ca20d2b54c47451b4e0cd
2,082
cc
C++
src/Graph/flow_manager/mincost_flow_square.cc
studla/RYUTO
43abd5757745a14d0ee8824093bbfa7a361581d8
[ "BSD-3-Clause" ]
3
2021-07-26T08:48:51.000Z
2022-03-27T07:33:21.000Z
src/Graph/flow_manager/mincost_flow_square.cc
studla/RYUTO
43abd5757745a14d0ee8824093bbfa7a361581d8
[ "BSD-3-Clause" ]
3
2019-06-03T08:40:23.000Z
2020-09-16T11:34:53.000Z
src/Graph/flow_manager/mincost_flow_square.cc
studla/RYUTO
43abd5757745a14d0ee8824093bbfa7a361581d8
[ "BSD-3-Clause" ]
1
2019-06-07T21:52:26.000Z
2019-06-07T21:52:26.000Z
/* * File: mincost_flow_square.cc * Author: Thomas Gatter <thomas(at)bioinf.uni-leipzig.de> * * Created on January 9, 2017, 11:27 AM */ #include "mincost_flow_square.h" mincost_flow_square::mincost_flow_square(pre_graph* raw, exon_meta* meta, const std::string &chromosome, std::set<int> &ids) : mincost_flow_base(raw, meta, chromosome, ids) { } mincost_flow_square::~mincost_flow_square() { } void mincost_flow_square::add_offset_edge(capacity_type capacity, capacity_type orig_cap, int exon_count, ListDigraph::Node &sn, ListDigraph::Node &tn, ListDigraph &og, ListDigraph::ArcMap<capacity_type> &upper, ListDigraph::ArcMap<signed_long_capacity_type> &cost, std::deque< ListDigraph::Arc> &reference) { if (orig_cap == 0) orig_cap = 1; unsigned int mod = 1; if (exon_count > 2) { mod = exon_count - 2; } capacity_type i = step_interval; for (; i <= capacity; i+= step_interval) { ListDigraph::Arc na = og.addArc(sn, tn); upper[na] = step_interval; capacity_type c1 = i; capacity_type c2 = i-step_interval; cost[na] = (c1*c1 - c2*c2 ) / step_interval * int_scaling_factor / orig_cap * mod; cost[na] = std::max(cost[na], 1ll); reference.push_back(na); } i = i - step_interval; capacity_type leftover = capacity - i; if (leftover > 0) { // add one last edge ListDigraph::Arc na = og.addArc(sn, tn); upper[na] = leftover; capacity_type c1 = capacity; capacity_type c2 = i; cost[na] = (c1*c1 - c2*c2 ) / leftover * int_scaling_factor / orig_cap * mod; cost[na] = std::max(cost[na], 1ll); reference.push_back(na); } } void mincost_flow_square::init_variables(capacity_type max_supply) { step_interval = max_supply / options::Instance()->get_max_arc_split(); if (step_interval == 0) { step_interval = 1; } int_scaling_factor = pow(ceil(log10(max_supply)),10); }
30.173913
175
0.617195
studla
4ed81c9d0eb1f244b3387b0869f84195e9aa6c12
776
cpp
C++
src/auth/AppRoleStrategy.cpp
jigar23/libvault
5caa7062f08c5ec41563a7bb3e49a5e0f9360148
[ "MIT" ]
24
2019-01-28T19:37:38.000Z
2022-03-10T01:09:53.000Z
src/auth/AppRoleStrategy.cpp
jigar23/libvault
5caa7062f08c5ec41563a7bb3e49a5e0f9360148
[ "MIT" ]
59
2019-03-27T22:34:21.000Z
2022-03-25T23:43:57.000Z
src/auth/AppRoleStrategy.cpp
jigar23/libvault
5caa7062f08c5ec41563a7bb3e49a5e0f9360148
[ "MIT" ]
20
2019-06-13T11:58:19.000Z
2022-02-17T23:38:28.000Z
#include <utility> #include "json.hpp" #include "VaultClient.h" Vault::AppRoleStrategy::AppRoleStrategy(Vault::RoleId roleId, Vault::SecretId secretId) : roleId_(std::move(roleId)) , secretId_(std::move(secretId)) {} std::optional<Vault::AuthenticationResponse> Vault::AppRoleStrategy::authenticate(const Vault::Client& client) { return Vault::HttpConsumer::authenticate( client, getUrl(client, Vault::Path{"/login"}), [&]() { nlohmann::json j; j = nlohmann::json::object(); j["role_id"] = roleId_.value(); j["secret_id"] = secretId_.value(); return j.dump(); } ); } Vault::Url Vault::AppRoleStrategy::getUrl(const Vault::Client& client, const Vault::Path& path) { return client.getUrl("/v1/auth/approle", path); }
27.714286
97
0.668814
jigar23
4de57a2ff685805c067c8c6c2aad8cc13fd5231c
6,465
cpp
C++
src/rtc.cpp
buggedbit/Fusion
95e971e890e5d49c50a92f5c34a866609996cdd4
[ "MIT" ]
3
2018-06-23T11:41:35.000Z
2018-07-07T14:10:55.000Z
src/rtc.cpp
buggedbit/Fusion
95e971e890e5d49c50a92f5c34a866609996cdd4
[ "MIT" ]
3
2020-08-04T18:08:57.000Z
2020-08-04T18:09:52.000Z
src/rtc.cpp
buggedbit/fusion
95e971e890e5d49c50a92f5c34a866609996cdd4
[ "MIT" ]
null
null
null
#include <random> #include "element.cpp" class RoundTableConference { class Chair { public: Element *person; Chair *next; Chair *prev; Chair(Element *person, Chair *next, Chair *prev) : person(person), next(next), prev(prev) { if (person == nullptr) { throw "Null pointer initialization exception"; } } ~Chair() { // free person in this chair delete person; } }; const Color COLOR_CHAURESTE = COLOR(60, 226, 10); Chair *head, *tail; Element *newlySpawned; int noChairs; /** * sectorNo >= 0 * */ void addChairAtSector(int sectorNo) { if (newlySpawned == nullptr) { throw "Null argument exception"; } if (sectorNo < 0) { throw "Illegal argument exception"; } Chair *justBeforeChair = head; for (int i = 0; i < sectorNo; ++i) { justBeforeChair = justBeforeChair->next; } Chair *justAfterChair = justBeforeChair == nullptr ? nullptr : justBeforeChair->next; // add chair Chair *newChair = new Chair(newlySpawned, justAfterChair, justBeforeChair); if (justBeforeChair != nullptr) { justBeforeChair->next = newChair; } if (justAfterChair != nullptr) { justAfterChair->prev = newChair; } // reset head and tail if (newChair->next == nullptr) { tail = newChair; } if (newChair->prev == nullptr) { head = newChair; } noChairs++; newlySpawned = nullptr; } void removeChair(Chair *chair) { if (chair == nullptr) { throw "Null argument exception"; } Chair *justAfterChair = chair->next; Chair *justBeforeChair = chair->prev; if (justAfterChair != nullptr && justBeforeChair != nullptr) { justBeforeChair->next = justAfterChair; justAfterChair->prev = justBeforeChair; } else if (justAfterChair == nullptr && justBeforeChair != nullptr) { justBeforeChair->next = justAfterChair; tail = justBeforeChair; } else if (justAfterChair != nullptr && justBeforeChair == nullptr) { justAfterChair->prev = justBeforeChair; head = justAfterChair; } else { head = justBeforeChair; tail = justAfterChair; } noChairs--; delete chair; } double getCurrentSectorAngle() { return noChairs == 0 ? 360.0 : 360.0 / noChairs; } Chair *getNextChair(const Chair *chair) { if (chair == nullptr) { throw "Null argument exception"; } return chair->next == nullptr ? head : chair->next; } Chair *getPrevChair(const Chair *chair) { if (chair == nullptr) { throw "Null argument exception"; } return chair->prev == nullptr ? tail : chair->prev; } void rearrangeChairs() { Chair *it = head; double sectorAngleAfterPlacing = getCurrentSectorAngle(); int i = 0; while (it != nullptr) { it->person->setSector(i, sectorAngleAfterPlacing); it = it->next; i++; } } public: RoundTableConference() : head(nullptr), tail(nullptr), newlySpawned(nullptr), noChairs(0) {} ~RoundTableConference() { // free all chairs Chair *it = tail; while (it != nullptr) { Chair *prev = it->prev; delete it; it = prev; } } int getCount() { return noChairs; } int getHighest() { int ans = 0; Chair *it = head; while (it != nullptr) { if (it->person->getAtomicNumber() > ans) { ans = it->person->getAtomicNumber(); } it = it->next; } return ans; } void print() { Chair *it = head; while (it != nullptr) { printf("%d ", it->person->getAtomicNumber()); it = it->next; } printf("\n"); } void spawn(int atomicNumber) { if (newlySpawned != nullptr) { throw "Over spawn exception"; } newlySpawned = new Element(atomicNumber); } /** * Assumption: 0 <= theta <= 359 * */ void place(double theta) { int sectorNo = theta / getCurrentSectorAngle(); addChairAtSector(sectorNo); rearrangeChairs(); } int fuse(int noFusionsOccured = 0) { if (noChairs < 3) { // fusion will not occur return noFusionsOccured; } // detect fusable combo int fusionCount = 0; Chair *it = head; while (it != nullptr) { if (it->person->isFusingElement()) { // look for combo on either sides Chair *cw = getNextChair(it); Chair *acw = getPrevChair(it); while (true) { if (cw->person->getAtomicNumber() == acw->person->getAtomicNumber()) { if (cw != acw) { fusionCount++; } else { break; } if (getNextChair(cw) == acw) { break; } } else { break; } // cw acw go round the circle cw = getNextChair(cw); acw = getPrevChair(acw); } } if (fusionCount > 0) { break; } it = it->next; } if (fusionCount == 0) { // nothing to fuse return noFusionsOccured; } // fuse elements Text fusingTextView(WINDOW_SIDE_LENGTH / 2., WINDOW_SIDE_LENGTH / 2., "FUSING ELEMENTS..."); fusingTextView.setColor(COLOR_CHAURESTE); Chair *fusingChair = it; int newName = 1; Chair *cw, *acw; Chair *nextCw = getNextChair(it); Chair *nextAcw = getPrevChair(it); for (int i = 0; i < fusionCount; i++) { cw = nextCw; acw = nextAcw; // update atomicNumber newName += cw->person->getAtomicNumber(); noFusionsOccured++; Element::bubblingEffect(cw->person, acw->person); nextCw = getNextChair(cw); nextAcw = getPrevChair(acw); removeChair(cw); removeChair(acw); } fusingChair->person->setAtomicNumber(newName); rearrangeChairs(); return fuse(noFusionsOccured); } };
29.520548
100
0.52266
buggedbit
4deff149db417f1e012b98c7d1db6ff5828041c9
187
cpp
C++
ConsoleApplication1/split_line.cpp
ConstantinusY/Homework_compeleted_time_statistics
b46a37e34368a8354e809d7110c37e441cb8b2db
[ "MIT" ]
1
2020-10-08T03:51:10.000Z
2020-10-08T03:51:10.000Z
ConsoleApplication1/split_line.cpp
ConstantinusY/Homework_compeleted_time_statistics
b46a37e34368a8354e809d7110c37e441cb8b2db
[ "MIT" ]
null
null
null
ConsoleApplication1/split_line.cpp
ConstantinusY/Homework_compeleted_time_statistics
b46a37e34368a8354e809d7110c37e441cb8b2db
[ "MIT" ]
null
null
null
#include"func.h" using namespace std; void split_line(bool all_blank) { if (all_blank) { cout << endl; } else { cout << "\n_-_-_ PROGRAM DESIGHED BY CON_Y _-_-_\n" << endl; } }
13.357143
62
0.625668
ConstantinusY
4df22e94a6cc76e777f3845b1299ffa60d98302d
7,089
cpp
C++
RunTest/RunTest/Profiler.cpp
dtrebilco/FrameworkTests
77c6a27e4f126d66d17daf7a794aa90544bc5e79
[ "MIT" ]
null
null
null
RunTest/RunTest/Profiler.cpp
dtrebilco/FrameworkTests
77c6a27e4f126d66d17daf7a794aa90544bc5e79
[ "MIT" ]
null
null
null
RunTest/RunTest/Profiler.cpp
dtrebilco/FrameworkTests
77c6a27e4f126d66d17daf7a794aa90544bc5e79
[ "MIT" ]
null
null
null
#include "Profiler.h" #include "LogInterface.h" #include <memory> #include <chrono> #include <ctime> #include <thread> #include <atomic> #include <mutex> #include <vector> #include <unordered_map> #include <sstream> #include <fstream> namespace profiler { using clock = std::chrono::high_resolution_clock; struct ProfileRecord { clock::time_point m_time; // The time of the profile data std::thread::id m_threadID; // The id of the thread const char* m_tag = nullptr; // The tag used in profiling - if empty is an end event }; struct Tags { int32_t m_index = -1; // The index of the thread std::vector<const char*> m_tags; // The tag stack }; struct ProfileData { clock::time_point m_startTime; // The start time of the profile std::atomic_bool m_enabled = false; // If profiling is enabled std::mutex m_access; // Access mutex for changing data size_t m_maxRecords = 0; // The maximum number of records std::vector<ProfileRecord> m_records; // The profiling records }; static std::unique_ptr<ProfileData> g_pData; // The global profile data (not concrete so that nothing is allocated if no profiling is done) static void ProfileBeginCallback(const char* i_str) { if (!g_pData->m_enabled) { return; } // Ensure no null pointers on begin if (i_str == nullptr) { i_str = "Unknown"; } // Create the profile record ProfileRecord newData = {}; newData.m_threadID = std::this_thread::get_id(); newData.m_tag = i_str; // There is a race condition where a record could be added after the profiling has ended (m_enabled changed)- this is benign however std::lock_guard<std::mutex> lock(g_pData->m_access); if (g_pData->m_records.size() < g_pData->m_maxRecords) { g_pData->m_records.push_back(newData); // Assign the time as the last possible thing g_pData->m_records.back().m_time = clock::now(); } } static void ProfileEndCallback() { if (!g_pData->m_enabled) { return; } ProfileRecord newData = {}; newData.m_time = clock::now(); // Always get time as soon as possible newData.m_threadID = std::this_thread::get_id(); newData.m_tag = nullptr; // There is a race condition where a record could be added after the profiling has ended (m_enabled changed)- this is benign however std::lock_guard<std::mutex> lock(g_pData->m_access); if (g_pData->m_records.size() < g_pData->m_maxRecords) { g_pData->m_records.push_back(newData); } } void Register() { if (!g_pData) { g_pData = std::make_unique<ProfileData>(); PROFILE_SETUP(ProfileBeginCallback, ProfileEndCallback); } } bool IsProfiling() { if (!g_pData) { return false; } return g_pData->m_enabled; } bool Begin(size_t i_bufferSize) { if (!g_pData) { return false; } std::lock_guard<std::mutex> lock(g_pData->m_access); if (g_pData->m_enabled) { return false; } // Clear all data (may have been some extra in buffers from previous enable) g_pData->m_maxRecords = i_bufferSize / sizeof(ProfileRecord); g_pData->m_records.resize(0); g_pData->m_records.reserve(g_pData->m_maxRecords); g_pData->m_startTime = clock::now(); g_pData->m_enabled = true; return true; } static void CleanJsonStr(std::string& io_str) { size_t startPos = 0; while ((startPos = io_str.find_first_of("\\\"", startPos)) != std::string::npos) { io_str.insert(startPos, 1, '\\'); startPos += 2; } } bool End(std::ostream& o_outStream) { if (!g_pData) { return false; } std::lock_guard<std::mutex> lock(g_pData->m_access); if (!g_pData->m_enabled) { return false; } g_pData->m_enabled = false; // Init this thread as the primary thread std::unordered_map<std::thread::id, Tags> threadStack; threadStack[std::this_thread::get_id()].m_index = 0; bool first = true; int32_t threadCounter = 1; std::string cleanTag; o_outStream << "{\"traceEvents\":[\n"; for (const ProfileRecord& entry : g_pData->m_records) { auto& stack = threadStack[entry.m_threadID]; // Assign a unique index to each thread if (stack.m_index < 0) { stack.m_index = threadCounter; threadCounter++; } // Get the name tags const char* tag = entry.m_tag; const char* typeTag = "B"; if (tag != nullptr) { stack.m_tags.push_back(tag); } else { typeTag = "E"; if (stack.m_tags.size() == 0) { tag = "Unknown"; } else { tag = stack.m_tags.back(); stack.m_tags.pop_back(); } } // Markup invalid json characters if (strchr(tag, '"') != nullptr || strchr(tag, '\\') != nullptr) { cleanTag = tag; CleanJsonStr(cleanTag); tag = cleanTag.c_str(); } // Get the microsecond count long long msCount = std::chrono::duration_cast<std::chrono::microseconds>(entry.m_time - g_pData->m_startTime).count(); if (!first) { o_outStream << ",\n"; } first = false; char msString[64]; snprintf(msString, sizeof(msString), "%lld", msCount); char indexString[64]; snprintf(indexString, sizeof(indexString), "%d", stack.m_index); // Format the string o_outStream << "{\"name\":\"" << tag << "\",\"ph\":\"" << typeTag << "\",\"ts\":" << msString << ",\"tid\":" << indexString << ",\"cat\":\"\",\"pid\":0,\"args\":{}}"; } // Write thread "names" if (!first) { for (auto& t : threadStack) { char indexString[64]; snprintf(indexString, sizeof(indexString), "%d", t.second.m_index); // Sort thread listing by the time that they appear in the profile (tool sorts by name) char indexSpaceString[64]; snprintf(indexSpaceString, sizeof(indexSpaceString), "%02d", t.second.m_index); // Ensure a clean json string std::stringstream ss; ss << t.first; std::string threadName = ss.str(); CleanJsonStr(threadName); o_outStream << ",\n{\"name\":\"thread_name\",\"ph\":\"M\",\"pid\":0,\"tid\":" << indexString << ",\"args\":{\"name\":\"Thread" << indexSpaceString << "_" << threadName << "\"}}"; } } o_outStream << "\n]\n}\n"; return true; } bool End(std::string& o_outString) { std::stringstream ss; bool retval = End(ss); o_outString = ss.str(); return retval; } bool EndFileJson(const char* i_fileName, bool i_appendDate) { std::ofstream file; if (i_appendDate) { // Create a filename with the current date in it std::time_t t = std::time(nullptr); tm timeBuf; localtime_s(&timeBuf, &t); char timeStr[100]; if (std::strftime(timeStr, sizeof(timeStr), "%Y%m%d-%H%M%S", &timeBuf) == 0) { return false; } // Append date and file extension char newFilename[1024]; snprintf(newFilename, sizeof(newFilename), "%s_%s.json", i_fileName, timeStr); file.open(newFilename); } else { file.open(i_fileName); } if (!file.is_open()) { return false; } return End(file); } }
23.091205
139
0.628297
dtrebilco
4df3f77aa553c0773f509532ad7fac8ccdf307d9
213
cpp
C++
src/solvers/Session.cpp
tomcreutz/planning-templ
55e35ede362444df9a7def6046f6df06851fe318
[ "BSD-3-Clause" ]
1
2022-03-31T12:15:15.000Z
2022-03-31T12:15:15.000Z
src/solvers/Session.cpp
tomcreutz/planning-templ
55e35ede362444df9a7def6046f6df06851fe318
[ "BSD-3-Clause" ]
null
null
null
src/solvers/Session.cpp
tomcreutz/planning-templ
55e35ede362444df9a7def6046f6df06851fe318
[ "BSD-3-Clause" ]
1
2021-12-29T10:38:07.000Z
2021-12-29T10:38:07.000Z
#include "Session.hpp" namespace templ { namespace solvers { Session::Session() {} Session::Session(const Mission::Ptr& mission) : mpMission(mission) {} } // end namespace solvers } // end namespace templ
14.2
45
0.699531
tomcreutz
4df6958aa4c08cf95fb7839eaf3984c835af62f0
52,190
cpp
C++
source/effect_symbol_table.cpp
JadeArkadian/reshade
9c0aaadacefab4fb4b176b24f4d4a60be26416e0
[ "BSD-3-Clause" ]
14
2018-04-09T15:48:01.000Z
2021-11-17T11:24:31.000Z
source/effect_symbol_table.cpp
JadeArkadian/GuildFX
9c0aaadacefab4fb4b176b24f4d4a60be26416e0
[ "BSD-3-Clause" ]
null
null
null
source/effect_symbol_table.cpp
JadeArkadian/GuildFX
9c0aaadacefab4fb4b176b24f4d4a60be26416e0
[ "BSD-3-Clause" ]
4
2018-04-10T10:30:28.000Z
2019-12-15T21:01:58.000Z
/** * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #include "effect_symbol_table.hpp" #include "effect_syntax_tree_nodes.hpp" #include <assert.h> #include <algorithm> #include <functional> namespace reshadefx { using namespace nodes; namespace { struct intrinsic { intrinsic(const std::string &name, enum intrinsic_expression_node::op op, type_node::datatype returntype, unsigned int returnrows, unsigned int returncols) : op(op) { function.name = name; function.return_type.basetype = returntype; function.return_type.rows = returnrows; function.return_type.cols = returncols; } intrinsic(const std::string &name, enum intrinsic_expression_node::op op, type_node::datatype returntype, unsigned int returnrows, unsigned int returncols, type_node::datatype arg0type, unsigned int arg0rows, unsigned int arg0cols) : op(op) { function.name = name; function.return_type.basetype = returntype; function.return_type.rows = returnrows; function.return_type.cols = returncols; arguments[0].type.basetype = arg0type; arguments[0].type.rows = arg0rows; arguments[0].type.cols = arg0cols; function.parameter_list.push_back(&arguments[0]); } intrinsic(const std::string &name, enum intrinsic_expression_node::op op, type_node::datatype returntype, unsigned int returnrows, unsigned int returncols, type_node::datatype arg0type, unsigned int arg0rows, unsigned int arg0cols, type_node::datatype arg1type, unsigned int arg1rows, unsigned int arg1cols) : op(op) { function.name = name; function.return_type.basetype = returntype; function.return_type.rows = returnrows; function.return_type.cols = returncols; arguments[0].type.basetype = arg0type; arguments[0].type.rows = arg0rows; arguments[0].type.cols = arg0cols; arguments[1].type.basetype = arg1type; arguments[1].type.rows = arg1rows; arguments[1].type.cols = arg1cols; function.parameter_list.push_back(&arguments[0]); function.parameter_list.push_back(&arguments[1]); } intrinsic(const std::string &name, enum intrinsic_expression_node::op op, type_node::datatype returntype, unsigned int returnrows, unsigned int returncols, type_node::datatype arg0type, unsigned int arg0rows, unsigned int arg0cols, type_node::datatype arg1type, unsigned int arg1rows, unsigned int arg1cols, type_node::datatype arg2type, unsigned int arg2rows, unsigned int arg2cols) : op(op) { function.name = name; function.return_type.basetype = returntype; function.return_type.rows = returnrows; function.return_type.cols = returncols; arguments[0].type.basetype = arg0type; arguments[0].type.rows = arg0rows; arguments[0].type.cols = arg0cols; arguments[1].type.basetype = arg1type; arguments[1].type.rows = arg1rows; arguments[1].type.cols = arg1cols; arguments[2].type.basetype = arg2type; arguments[2].type.rows = arg2rows; arguments[2].type.cols = arg2cols; function.parameter_list.push_back(&arguments[0]); function.parameter_list.push_back(&arguments[1]); function.parameter_list.push_back(&arguments[2]); } intrinsic(const std::string &name, enum intrinsic_expression_node::op op, type_node::datatype returntype, unsigned int returnrows, unsigned int returncols, type_node::datatype arg0type, unsigned int arg0rows, unsigned int arg0cols, type_node::datatype arg1type, unsigned int arg1rows, unsigned int arg1cols, type_node::datatype arg2type, unsigned int arg2rows, unsigned int arg2cols, type_node::datatype arg3type, unsigned int arg3rows, unsigned int arg3cols) : op(op) { function.name = name; function.return_type.basetype = returntype; function.return_type.rows = returnrows; function.return_type.cols = returncols; arguments[0].type.basetype = arg0type; arguments[0].type.rows = arg0rows; arguments[0].type.cols = arg0cols; arguments[1].type.basetype = arg1type; arguments[1].type.rows = arg1rows; arguments[1].type.cols = arg1cols; arguments[2].type.basetype = arg2type; arguments[2].type.rows = arg2rows; arguments[2].type.cols = arg2cols; arguments[3].type.basetype = arg3type; arguments[3].type.rows = arg3rows; arguments[3].type.cols = arg3cols; function.parameter_list.push_back(&arguments[0]); function.parameter_list.push_back(&arguments[1]); function.parameter_list.push_back(&arguments[2]); function.parameter_list.push_back(&arguments[3]); } enum intrinsic_expression_node::op op; function_declaration_node function; variable_declaration_node arguments[4]; }; const intrinsic s_intrinsics[] = { intrinsic("abs", intrinsic_expression_node::abs, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("abs", intrinsic_expression_node::abs, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("abs", intrinsic_expression_node::abs, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("abs", intrinsic_expression_node::abs, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("acos", intrinsic_expression_node::acos, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("acos", intrinsic_expression_node::acos, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("acos", intrinsic_expression_node::acos, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("acos", intrinsic_expression_node::acos, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("all", intrinsic_expression_node::all, type_node::datatype_bool, 1, 1, type_node::datatype_bool, 1, 1), intrinsic("all", intrinsic_expression_node::all, type_node::datatype_bool, 1, 1, type_node::datatype_bool, 2, 1), intrinsic("all", intrinsic_expression_node::all, type_node::datatype_bool, 1, 1, type_node::datatype_bool, 3, 1), intrinsic("all", intrinsic_expression_node::all, type_node::datatype_bool, 1, 1, type_node::datatype_bool, 4, 1), intrinsic("any", intrinsic_expression_node::any, type_node::datatype_bool, 1, 1, type_node::datatype_bool, 1, 1), intrinsic("any", intrinsic_expression_node::any, type_node::datatype_bool, 1, 1, type_node::datatype_bool, 2, 1), intrinsic("any", intrinsic_expression_node::any, type_node::datatype_bool, 1, 1, type_node::datatype_bool, 3, 1), intrinsic("any", intrinsic_expression_node::any, type_node::datatype_bool, 1, 1, type_node::datatype_bool, 4, 1), intrinsic("asfloat", intrinsic_expression_node::bitcast_int2float, type_node::datatype_float, 1, 1, type_node::datatype_int, 1, 1), intrinsic("asfloat", intrinsic_expression_node::bitcast_int2float, type_node::datatype_float, 2, 1, type_node::datatype_int, 2, 1), intrinsic("asfloat", intrinsic_expression_node::bitcast_int2float, type_node::datatype_float, 3, 1, type_node::datatype_int, 3, 1), intrinsic("asfloat", intrinsic_expression_node::bitcast_int2float, type_node::datatype_float, 4, 1, type_node::datatype_int, 4, 1), intrinsic("asfloat", intrinsic_expression_node::bitcast_uint2float, type_node::datatype_float, 1, 1, type_node::datatype_uint, 1, 1), intrinsic("asfloat", intrinsic_expression_node::bitcast_uint2float, type_node::datatype_float, 2, 1, type_node::datatype_uint, 2, 1), intrinsic("asfloat", intrinsic_expression_node::bitcast_uint2float, type_node::datatype_float, 3, 1, type_node::datatype_uint, 3, 1), intrinsic("asfloat", intrinsic_expression_node::bitcast_uint2float, type_node::datatype_float, 4, 1, type_node::datatype_uint, 4, 1), intrinsic("asin", intrinsic_expression_node::asin, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("asin", intrinsic_expression_node::asin, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("asin", intrinsic_expression_node::asin, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("asin", intrinsic_expression_node::asin, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("asint", intrinsic_expression_node::bitcast_float2int, type_node::datatype_int, 1, 1, type_node::datatype_float, 1, 1), intrinsic("asint", intrinsic_expression_node::bitcast_float2int, type_node::datatype_int, 2, 1, type_node::datatype_float, 2, 1), intrinsic("asint", intrinsic_expression_node::bitcast_float2int, type_node::datatype_int, 3, 1, type_node::datatype_float, 3, 1), intrinsic("asint", intrinsic_expression_node::bitcast_float2int, type_node::datatype_int, 4, 1, type_node::datatype_float, 4, 1), intrinsic("asuint", intrinsic_expression_node::bitcast_float2uint, type_node::datatype_uint, 1, 1, type_node::datatype_float, 1, 1), intrinsic("asuint", intrinsic_expression_node::bitcast_float2uint, type_node::datatype_uint, 2, 1, type_node::datatype_float, 2, 1), intrinsic("asuint", intrinsic_expression_node::bitcast_float2uint, type_node::datatype_uint, 3, 1, type_node::datatype_float, 3, 1), intrinsic("asuint", intrinsic_expression_node::bitcast_float2uint, type_node::datatype_uint, 4, 1, type_node::datatype_float, 4, 1), intrinsic("atan", intrinsic_expression_node::atan, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("atan", intrinsic_expression_node::atan, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("atan", intrinsic_expression_node::atan, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("atan", intrinsic_expression_node::atan, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("atan2", intrinsic_expression_node::atan2, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("atan2", intrinsic_expression_node::atan2, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("atan2", intrinsic_expression_node::atan2, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("atan2", intrinsic_expression_node::atan2, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("ceil", intrinsic_expression_node::ceil, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("ceil", intrinsic_expression_node::ceil, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("ceil", intrinsic_expression_node::ceil, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("ceil", intrinsic_expression_node::ceil, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("clamp", intrinsic_expression_node::clamp, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("clamp", intrinsic_expression_node::clamp, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("clamp", intrinsic_expression_node::clamp, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("clamp", intrinsic_expression_node::clamp, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("cos", intrinsic_expression_node::cos, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("cos", intrinsic_expression_node::cos, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("cos", intrinsic_expression_node::cos, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("cos", intrinsic_expression_node::cos, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("cosh", intrinsic_expression_node::cosh, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("cosh", intrinsic_expression_node::cosh, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("cosh", intrinsic_expression_node::cosh, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("cosh", intrinsic_expression_node::cosh, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("cross", intrinsic_expression_node::cross, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("ddx", intrinsic_expression_node::ddx, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("ddx", intrinsic_expression_node::ddx, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("ddx", intrinsic_expression_node::ddx, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("ddx", intrinsic_expression_node::ddx, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("ddy", intrinsic_expression_node::ddy, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("ddy", intrinsic_expression_node::ddy, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("ddy", intrinsic_expression_node::ddy, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("ddy", intrinsic_expression_node::ddy, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("degrees", intrinsic_expression_node::degrees, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("degrees", intrinsic_expression_node::degrees, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("degrees", intrinsic_expression_node::degrees, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("degrees", intrinsic_expression_node::degrees, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("determinant", intrinsic_expression_node::determinant, type_node::datatype_float, 1, 1, type_node::datatype_float, 2, 2), intrinsic("determinant", intrinsic_expression_node::determinant, type_node::datatype_float, 1, 1, type_node::datatype_float, 3, 3), intrinsic("determinant", intrinsic_expression_node::determinant, type_node::datatype_float, 1, 1, type_node::datatype_float, 4, 4), intrinsic("distance", intrinsic_expression_node::distance, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("distance", intrinsic_expression_node::distance, type_node::datatype_float, 1, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("distance", intrinsic_expression_node::distance, type_node::datatype_float, 1, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("distance", intrinsic_expression_node::distance, type_node::datatype_float, 1, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("dot", intrinsic_expression_node::dot, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("dot", intrinsic_expression_node::dot, type_node::datatype_float, 1, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("dot", intrinsic_expression_node::dot, type_node::datatype_float, 1, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("dot", intrinsic_expression_node::dot, type_node::datatype_float, 1, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("exp", intrinsic_expression_node::exp, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("exp", intrinsic_expression_node::exp, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("exp", intrinsic_expression_node::exp, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("exp", intrinsic_expression_node::exp, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("exp2", intrinsic_expression_node::exp2, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("exp2", intrinsic_expression_node::exp2, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("exp2", intrinsic_expression_node::exp2, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("exp2", intrinsic_expression_node::exp2, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("faceforward", intrinsic_expression_node::faceforward, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("faceforward", intrinsic_expression_node::faceforward, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("faceforward", intrinsic_expression_node::faceforward, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("faceforward", intrinsic_expression_node::faceforward, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("floor", intrinsic_expression_node::floor, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("floor", intrinsic_expression_node::floor, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("floor", intrinsic_expression_node::floor, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("floor", intrinsic_expression_node::floor, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("frac", intrinsic_expression_node::frac, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("frac", intrinsic_expression_node::frac, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("frac", intrinsic_expression_node::frac, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("frac", intrinsic_expression_node::frac, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("frexp", intrinsic_expression_node::frexp, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("frexp", intrinsic_expression_node::frexp, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("frexp", intrinsic_expression_node::frexp, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("frexp", intrinsic_expression_node::frexp, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("fwidth", intrinsic_expression_node::fwidth, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("fwidth", intrinsic_expression_node::fwidth, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("fwidth", intrinsic_expression_node::fwidth, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("fwidth", intrinsic_expression_node::fwidth, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("isinf", intrinsic_expression_node::isinf, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("isinf", intrinsic_expression_node::isinf, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("isinf", intrinsic_expression_node::isinf, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("isinf", intrinsic_expression_node::isinf, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("isnan", intrinsic_expression_node::isnan, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("isnan", intrinsic_expression_node::isnan, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("isnan", intrinsic_expression_node::isnan, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("isnan", intrinsic_expression_node::isnan, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("ldexp", intrinsic_expression_node::ldexp, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("ldexp", intrinsic_expression_node::ldexp, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("ldexp", intrinsic_expression_node::ldexp, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("ldexp", intrinsic_expression_node::ldexp, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("length", intrinsic_expression_node::length, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("length", intrinsic_expression_node::length, type_node::datatype_float, 1, 1, type_node::datatype_float, 2, 1), intrinsic("length", intrinsic_expression_node::length, type_node::datatype_float, 1, 1, type_node::datatype_float, 3, 1), intrinsic("length", intrinsic_expression_node::length, type_node::datatype_float, 1, 1, type_node::datatype_float, 4, 1), intrinsic("lerp", intrinsic_expression_node::lerp, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("lerp", intrinsic_expression_node::lerp, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("lerp", intrinsic_expression_node::lerp, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("lerp", intrinsic_expression_node::lerp, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("log", intrinsic_expression_node::log, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("log", intrinsic_expression_node::log, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("log", intrinsic_expression_node::log, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("log", intrinsic_expression_node::log, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("log10", intrinsic_expression_node::log10, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("log10", intrinsic_expression_node::log10, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("log10", intrinsic_expression_node::log10, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("log10", intrinsic_expression_node::log10, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("log2", intrinsic_expression_node::log2, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("log2", intrinsic_expression_node::log2, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("log2", intrinsic_expression_node::log2, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("log2", intrinsic_expression_node::log2, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("mad", intrinsic_expression_node::mad, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("mad", intrinsic_expression_node::mad, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("mad", intrinsic_expression_node::mad, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("mad", intrinsic_expression_node::mad, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("max", intrinsic_expression_node::max, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("max", intrinsic_expression_node::max, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("max", intrinsic_expression_node::max, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("max", intrinsic_expression_node::max, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("min", intrinsic_expression_node::min, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("min", intrinsic_expression_node::min, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("min", intrinsic_expression_node::min, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("min", intrinsic_expression_node::min, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("modf", intrinsic_expression_node::modf, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("modf", intrinsic_expression_node::modf, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("modf", intrinsic_expression_node::modf, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("modf", intrinsic_expression_node::modf, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 2, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 2, 1), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 3, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 3, 1), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 4, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 4, 1), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 1, 1), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 1, 1), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 1, 1), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 2, 2, type_node::datatype_float, 1, 1, type_node::datatype_float, 2, 2), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 3, 3, type_node::datatype_float, 1, 1, type_node::datatype_float, 3, 3), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 4, 4, type_node::datatype_float, 1, 1, type_node::datatype_float, 4, 4), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 2, 2, type_node::datatype_float, 2, 2, type_node::datatype_float, 1, 1), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 3, 3, type_node::datatype_float, 3, 3, type_node::datatype_float, 1, 1), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 4, 4, type_node::datatype_float, 4, 4, type_node::datatype_float, 1, 1), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 2), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 3), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 4), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 2, type_node::datatype_float, 2, 1), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 3, type_node::datatype_float, 3, 1), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 4, type_node::datatype_float, 4, 1), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 2, 2, type_node::datatype_float, 2, 2, type_node::datatype_float, 2, 2), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 3, 3, type_node::datatype_float, 3, 3, type_node::datatype_float, 3, 3), intrinsic("mul", intrinsic_expression_node::mul, type_node::datatype_float, 4, 4, type_node::datatype_float, 4, 4, type_node::datatype_float, 4, 4), intrinsic("normalize", intrinsic_expression_node::normalize, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("normalize", intrinsic_expression_node::normalize, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("normalize", intrinsic_expression_node::normalize, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("normalize", intrinsic_expression_node::normalize, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("pow", intrinsic_expression_node::pow, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("pow", intrinsic_expression_node::pow, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("pow", intrinsic_expression_node::pow, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("pow", intrinsic_expression_node::pow, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("radians", intrinsic_expression_node::radians, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("radians", intrinsic_expression_node::radians, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("radians", intrinsic_expression_node::radians, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("radians", intrinsic_expression_node::radians, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("rcp", intrinsic_expression_node::rcp, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("rcp", intrinsic_expression_node::rcp, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("rcp", intrinsic_expression_node::rcp, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("rcp", intrinsic_expression_node::rcp, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("reflect", intrinsic_expression_node::reflect, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("reflect", intrinsic_expression_node::reflect, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("reflect", intrinsic_expression_node::reflect, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("reflect", intrinsic_expression_node::reflect, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("refract", intrinsic_expression_node::refract, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("refract", intrinsic_expression_node::refract, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("refract", intrinsic_expression_node::refract, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("refract", intrinsic_expression_node::refract, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("round", intrinsic_expression_node::round, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("round", intrinsic_expression_node::round, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("round", intrinsic_expression_node::round, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("round", intrinsic_expression_node::round, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("rsqrt", intrinsic_expression_node::rsqrt, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("rsqrt", intrinsic_expression_node::rsqrt, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("rsqrt", intrinsic_expression_node::rsqrt, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("rsqrt", intrinsic_expression_node::rsqrt, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("saturate", intrinsic_expression_node::saturate, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("saturate", intrinsic_expression_node::saturate, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("saturate", intrinsic_expression_node::saturate, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("saturate", intrinsic_expression_node::saturate, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("sign", intrinsic_expression_node::sign, type_node::datatype_int, 1, 1, type_node::datatype_float, 1, 1), intrinsic("sign", intrinsic_expression_node::sign, type_node::datatype_int, 2, 1, type_node::datatype_float, 2, 1), intrinsic("sign", intrinsic_expression_node::sign, type_node::datatype_int, 3, 1, type_node::datatype_float, 3, 1), intrinsic("sign", intrinsic_expression_node::sign, type_node::datatype_int, 4, 1, type_node::datatype_float, 4, 1), intrinsic("sin", intrinsic_expression_node::sin, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("sin", intrinsic_expression_node::sin, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("sin", intrinsic_expression_node::sin, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("sin", intrinsic_expression_node::sin, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("sincos", intrinsic_expression_node::sincos, type_node::datatype_void, 0, 0, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("sincos", intrinsic_expression_node::sincos, type_node::datatype_void, 0, 0, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("sincos", intrinsic_expression_node::sincos, type_node::datatype_void, 0, 0, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("sincos", intrinsic_expression_node::sincos, type_node::datatype_void, 0, 0, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("sinh", intrinsic_expression_node::sinh, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("sinh", intrinsic_expression_node::sinh, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("sinh", intrinsic_expression_node::sinh, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("sinh", intrinsic_expression_node::sinh, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("smoothstep", intrinsic_expression_node::smoothstep, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("smoothstep", intrinsic_expression_node::smoothstep, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("smoothstep", intrinsic_expression_node::smoothstep, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("smoothstep", intrinsic_expression_node::smoothstep, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("sqrt", intrinsic_expression_node::sqrt, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("sqrt", intrinsic_expression_node::sqrt, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("sqrt", intrinsic_expression_node::sqrt, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("sqrt", intrinsic_expression_node::sqrt, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("step", intrinsic_expression_node::step, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("step", intrinsic_expression_node::step, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("step", intrinsic_expression_node::step, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("step", intrinsic_expression_node::step, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("tan", intrinsic_expression_node::tan, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("tan", intrinsic_expression_node::tan, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("tan", intrinsic_expression_node::tan, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("tan", intrinsic_expression_node::tan, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("tanh", intrinsic_expression_node::tanh, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("tanh", intrinsic_expression_node::tanh, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("tanh", intrinsic_expression_node::tanh, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("tanh", intrinsic_expression_node::tanh, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), intrinsic("tex2D", intrinsic_expression_node::texture, type_node::datatype_float, 4, 1, type_node::datatype_sampler, 0, 0, type_node::datatype_float, 2, 1), intrinsic("tex2Dfetch", intrinsic_expression_node::texture_fetch, type_node::datatype_float, 4, 1, type_node::datatype_sampler, 0, 0, type_node::datatype_int, 4, 1), intrinsic("tex2Dgather", intrinsic_expression_node::texture_gather, type_node::datatype_float, 4, 1, type_node::datatype_sampler, 0, 0, type_node::datatype_float, 2, 1, type_node::datatype_int, 1, 1), intrinsic("tex2Dgatheroffset", intrinsic_expression_node::texture_gather_offset, type_node::datatype_float, 4, 1, type_node::datatype_sampler, 0, 0, type_node::datatype_float, 2, 1, type_node::datatype_int, 2, 1, type_node::datatype_int, 1, 1), intrinsic("tex2Dgrad", intrinsic_expression_node::texture_gradient, type_node::datatype_float, 4, 1, type_node::datatype_sampler, 0, 0, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("tex2Dlod", intrinsic_expression_node::texture_level, type_node::datatype_float, 4, 1, type_node::datatype_sampler, 0, 0, type_node::datatype_float, 4, 1), intrinsic("tex2Dlodoffset", intrinsic_expression_node::texture_level_offset, type_node::datatype_float, 4, 1, type_node::datatype_sampler, 0, 0, type_node::datatype_float, 4, 1, type_node::datatype_int, 2, 1), intrinsic("tex2Doffset", intrinsic_expression_node::texture_offset, type_node::datatype_float, 4, 1, type_node::datatype_sampler, 0, 0, type_node::datatype_float, 2, 1, type_node::datatype_int, 2, 1), intrinsic("tex2Dproj", intrinsic_expression_node::texture_projection, type_node::datatype_float, 4, 1, type_node::datatype_sampler, 0, 0, type_node::datatype_float, 4, 1), intrinsic("tex2Dsize", intrinsic_expression_node::texture_size, type_node::datatype_int, 2, 1, type_node::datatype_sampler, 0, 0, type_node::datatype_int, 1, 1), intrinsic("transpose", intrinsic_expression_node::transpose, type_node::datatype_float, 2, 2, type_node::datatype_float, 2, 2), intrinsic("transpose", intrinsic_expression_node::transpose, type_node::datatype_float, 3, 3, type_node::datatype_float, 3, 3), intrinsic("transpose", intrinsic_expression_node::transpose, type_node::datatype_float, 4, 4, type_node::datatype_float, 4, 4), intrinsic("trunc", intrinsic_expression_node::trunc, type_node::datatype_float, 1, 1, type_node::datatype_float, 1, 1), intrinsic("trunc", intrinsic_expression_node::trunc, type_node::datatype_float, 2, 1, type_node::datatype_float, 2, 1), intrinsic("trunc", intrinsic_expression_node::trunc, type_node::datatype_float, 3, 1, type_node::datatype_float, 3, 1), intrinsic("trunc", intrinsic_expression_node::trunc, type_node::datatype_float, 4, 1, type_node::datatype_float, 4, 1), }; int compare_functions(const call_expression_node *call, const function_declaration_node *function1, const function_declaration_node *function2) { if (function2 == nullptr) { return -1; } const size_t count = call->arguments.size(); bool function1_viable = true; bool function2_viable = true; const auto function1_ranks = static_cast<unsigned int *>(alloca(count * sizeof(unsigned int))); const auto function2_ranks = static_cast<unsigned int *>(alloca(count * sizeof(unsigned int))); for (size_t i = 0; i < count; ++i) { function1_ranks[i] = type_node::rank(call->arguments[i]->type, function1->parameter_list[i]->type); if (function1_ranks[i] == 0) { function1_viable = false; break; } } for (size_t i = 0; i < count; ++i) { function2_ranks[i] = type_node::rank(call->arguments[i]->type, function2->parameter_list[i]->type); if (function2_ranks[i] == 0) { function2_viable = false; break; } } if (!(function1_viable && function2_viable)) { return function2_viable - function1_viable; } std::sort(function1_ranks, function1_ranks + count, std::greater<unsigned int>()); std::sort(function2_ranks, function2_ranks + count, std::greater<unsigned int>()); for (size_t i = 0; i < count; ++i) { if (function1_ranks[i] < function2_ranks[i]) { return -1; } else if (function2_ranks[i] < function1_ranks[i]) { return +1; } } return 0; } } unsigned int nodes::type_node::rank(const type_node &src, const type_node &dst) { if (src.is_array() != dst.is_array() || (src.array_length != dst.array_length && src.array_length > 0 && dst.array_length > 0)) { return 0; } if (src.is_struct() || dst.is_struct()) { return src.definition == dst.definition; } if (src.basetype == dst.basetype && src.rows == dst.rows && src.cols == dst.cols) { return 1; } if (!src.is_numeric() || !dst.is_numeric()) { return 0; } const int ranks[4][4] = { { 0, 5, 5, 5 }, { 4, 0, 3, 5 }, { 4, 2, 0, 5 }, { 4, 4, 4, 0 } }; assert(src.basetype <= 4 && dst.basetype <= 4); const int rank = ranks[static_cast<unsigned int>(src.basetype) - 1][static_cast<unsigned int>(dst.basetype) - 1] << 2; if (src.is_scalar() && dst.is_vector()) { return rank | 2; } if (src.is_vector() && dst.is_scalar() || (src.is_vector() == dst.is_vector() && src.rows > dst.rows && src.cols >= dst.cols)) { return rank | 32; } if (src.is_vector() != dst.is_vector() || src.is_matrix() != dst.is_matrix() || src.rows * src.cols != dst.rows * dst.cols) { return 0; } return rank; } symbol_table::symbol_table() { _current_scope.name = "::"; _current_scope.level = 0; _current_scope.namespace_level = 0; } void symbol_table::enter_scope(symbol parent) { if (parent != nullptr || _parent_stack.empty()) { _parent_stack.push(parent); } else { _parent_stack.push(_parent_stack.top()); } _current_scope.level++; } void symbol_table::enter_namespace(const std::string &name) { _current_scope.name += name + "::"; _current_scope.level++; _current_scope.namespace_level++; } void symbol_table::leave_scope() { assert(_current_scope.level > 0); for (auto &symbol : _symbol_stack) { auto &scope_list = symbol.second; for (auto scope_it = scope_list.begin(); scope_it != scope_list.end();) { if (scope_it->first.level > scope_it->first.namespace_level && scope_it->first.level >= _current_scope.level) { scope_it = scope_list.erase(scope_it); } else { ++scope_it; } } } _parent_stack.pop(); _current_scope.level--; } void symbol_table::leave_namespace() { assert(_current_scope.level > 0); assert(_current_scope.namespace_level > 0); _current_scope.name.erase(_current_scope.name.substr(0, _current_scope.name.size() - 2).rfind("::") + 2); _current_scope.level--; _current_scope.namespace_level--; } bool symbol_table::insert(symbol symbol, bool global) { // Make sure the symbol does not exist yet if (symbol->id != nodeid::function_declaration && find(symbol->name, _current_scope, true)) { return false; } // Insertion routine which keeps the symbol stack sorted by namespace level const auto insert_sorted = [](auto &vec, const auto &item) { return vec.insert( std::upper_bound(vec.begin(), vec.end(), item, [](auto lhs, auto rhs) { return lhs.first.namespace_level < rhs.first.namespace_level; }), item); }; // Global symbols are accessible from every scope if (global) { scope scope = { "", 0, 0 }; // Walk scope chain from global scope back to current one for (size_t pos = 0; pos != std::string::npos; pos = _current_scope.name.find("::", pos)) { // Extract scope name scope.name = _current_scope.name.substr(0, pos += 2); const auto previous_scope_name = _current_scope.name.substr(pos); // Insert symbol into this scope insert_sorted(_symbol_stack[previous_scope_name + symbol->name], std::make_pair(scope, symbol)); // Continue walking up the scope chain scope.level = ++scope.namespace_level; } } else { // This is a local symbol so it's sufficient to update the symbol stack with just the current scope insert_sorted(_symbol_stack[symbol->name], std::make_pair(_current_scope, symbol)); } return true; } symbol symbol_table::find(const std::string &name) const { // Default to start search with current scope and walk back the scope chain return find(name, _current_scope, false); } symbol symbol_table::find(const std::string &name, const scope &scope, bool exclusive) const { const auto it = _symbol_stack.find(name); // Check if symbol does exist if (it == _symbol_stack.end() || it->second.empty()) { return nullptr; } // Walk up the scope chain starting at the requested scope level and find a matching symbol symbol result = nullptr; const auto &scope_list = it->second; for (auto scope_it = scope_list.rbegin(), end = scope_list.rend(); scope_it != end; ++scope_it) { if (scope_it->first.level > scope.level || scope_it->first.namespace_level > scope.namespace_level || (scope_it->first.namespace_level == scope.namespace_level && scope_it->first.name != scope.name)) { continue; } if (exclusive && scope_it->first.level < scope.level) { continue; } if (scope_it->second->id == nodeid::variable_declaration || scope_it->second->id == nodeid::struct_declaration) { return scope_it->second; } if (result == nullptr) { result = scope_it->second; } } return result; } bool symbol_table::resolve_call(call_expression_node *call, const scope &scope, bool &is_intrinsic, bool &is_ambiguous) const { is_intrinsic = false; is_ambiguous = false; unsigned int overload_count = 0, overload_namespace = scope.namespace_level; const function_declaration_node *overload = nullptr; auto intrinsic_op = intrinsic_expression_node::none; const auto it = _symbol_stack.find(call->callee_name); if (it != _symbol_stack.end() && !it->second.empty()) { const auto &scope_list = it->second; for (auto scope_it = scope_list.rbegin(), end = scope_list.rend(); scope_it != end; ++scope_it) { if (scope_it->first.level > scope.level || scope_it->first.namespace_level > scope.namespace_level || scope_it->second->id != nodeid::function_declaration) { continue; } const auto function = static_cast<function_declaration_node *>(scope_it->second); if (function->parameter_list.empty()) { if (call->arguments.empty()) { overload = function; overload_count = 1; break; } else { continue; } } else if (call->arguments.size() != function->parameter_list.size()) { continue; } const int comparison = compare_functions(call, function, overload); if (comparison < 0) { overload = function; overload_count = 1; overload_namespace = scope_it->first.namespace_level; } else if (comparison == 0 && overload_namespace == scope_it->first.namespace_level) { ++overload_count; } } } if (overload_count == 0) { for (auto &intrinsic : s_intrinsics) { if (intrinsic.function.name != call->callee_name) { continue; } if (intrinsic.function.parameter_list.size() != call->arguments.size()) { is_intrinsic = overload_count == 0; break; } const int comparison = compare_functions(call, &intrinsic.function, overload); if (comparison < 0) { overload = &intrinsic.function; overload_count = 1; is_intrinsic = true; intrinsic_op = intrinsic.op; } else if (comparison == 0 && overload_namespace == 0) { ++overload_count; } } } if (overload_count == 1) { call->type = overload->return_type; call->callee = overload; if (is_intrinsic) { assert(intrinsic_op < 0xFF); call->callee_name = static_cast<char>(intrinsic_op); } else { call->callee_name = overload->name; } return true; } else { is_ambiguous = overload_count > 1; return false; } } }
69.401596
471
0.740717
JadeArkadian
4df712f1d8a9e7e31f5e5d4293dde9aa833cd15e
470
cpp
C++
BlueEngine/src/Blue/Log.cpp
YigitMemceroktay/BlueEngine
16a031b7ed31108743eb56613839bbfb7825128f
[ "MIT" ]
null
null
null
BlueEngine/src/Blue/Log.cpp
YigitMemceroktay/BlueEngine
16a031b7ed31108743eb56613839bbfb7825128f
[ "MIT" ]
null
null
null
BlueEngine/src/Blue/Log.cpp
YigitMemceroktay/BlueEngine
16a031b7ed31108743eb56613839bbfb7825128f
[ "MIT" ]
null
null
null
#include "bluecph.h" #include "Log.h" namespace Blue { std::shared_ptr<spdlog::logger> Log::s_ClientLogger; std::shared_ptr<spdlog::logger> Log::s_CoreLogger; void Log::Init() { s_CoreLogger = spdlog::stderr_color_mt("Blue"); s_CoreLogger->set_level(spdlog::level::trace); spdlog::set_pattern("%^[%T] %n: %v%$"); s_ClientLogger = spdlog::stderr_color_mt("App"); spdlog::set_level(spdlog::level::trace); spdlog::set_pattern("%^[%T] %n: %v%$"); } }
22.380952
53
0.670213
YigitMemceroktay
4df9d6ffed137911f4c4c2048561aa345a4bc8c4
3,676
cpp
C++
algorithms-and-data-structures/strings/g_multiple_search.cpp
nothingelsematters/university
5561969b1b11678228aaf7e6660e8b1a93d10294
[ "WTFPL" ]
1
2018-06-03T17:48:50.000Z
2018-06-03T17:48:50.000Z
algorithms-and-data-structures/strings/g_multiple_search.cpp
nothingelsematters/University
b1e188cb59e5a436731b92c914494626a99e1ae0
[ "WTFPL" ]
null
null
null
algorithms-and-data-structures/strings/g_multiple_search.cpp
nothingelsematters/University
b1e188cb59e5a436731b92c914494626a99e1ae0
[ "WTFPL" ]
14
2019-04-07T21:27:09.000Z
2021-12-05T13:37:25.000Z
#include <fstream> #include <iostream> #include <list> #include <vector> #include <map> struct Vertex { Vertex(size_t parent, char c) : parent(parent), parent_char(c) {} size_t operator[](char c) const { auto it = travel.find(c); if (it == travel.end()) { return -1; } return it->second; } size_t parent; char parent_char; size_t suf_link = -1; size_t com_link = -1; bool visited = false; std::map<char, int> travel; std::list<size_t> terminator; }; struct Forest { Forest() { vertex.push_back(Vertex(-1, '\0')); } void add(std::string const& str) { size_t current = 0; for (auto c: str) { size_t to = vertex[current][c]; if (to != -1) { current = to; continue; } vertex[current].travel[c] = vertex.size(); vertex.push_back(Vertex(current, c)); current = vertex.size() - 1; } vertex[current].terminator.push_back(string_quantity++); } bool* check(std::string const& text) { bool* result = new bool[string_quantity]; std::fill(result, result + string_quantity, false); size_t current = 0; vertex[current].visited = true; for (auto c: text) { current = get_link(current, c); for (size_t local = current; local != 0 && !vertex[local].visited; local = get_compressed(local)) { vertex[local].visited = true; for (auto j: vertex[local].terminator) { result[j] = true; } } vertex[current].visited = true; } return result; } private: size_t get_compressed(size_t index) { if (vertex[index].com_link != -1) { return vertex[index].com_link; } size_t suf = get_suf_link(index); if (get_suf_link(index) == 0) { vertex[index].com_link = 0; } else if (vertex[suf].terminator.size() > 0) { vertex[index].com_link = suf; } else { vertex[index].com_link = get_compressed(suf); } return vertex[index].com_link; } size_t get_suf_link(size_t index) { if (vertex[index].suf_link != -1) { return vertex[index].suf_link; } if (vertex[index].parent == -1 || vertex[index].parent == 0) { vertex[index].suf_link = 0; } else { vertex[index].suf_link = get_link(get_suf_link(vertex[index].parent), vertex[index].parent_char); } return vertex[index].suf_link; } size_t get_link(size_t index, char c) { size_t res = vertex[index][c]; if (res != -1) { return res; } size_t trans = vertex[index][c]; if (index == 0) { vertex[index].travel[c] = 0; } else { vertex[index].travel[c] = get_link(get_suf_link(index), c); } return vertex[index].travel[c]; } size_t string_quantity = 0; std::vector<Vertex> vertex; }; int main() { std::ifstream fin("search4.in"); Forest f; size_t quantity; fin >> quantity; for (size_t i = 0; i < quantity; ++i) { std::string str; fin >> str; f.add(str); } std::string text; fin >> text; fin.close(); bool* check = f.check(text); std::ofstream fout("search4.out"); for (size_t i = 0; i < quantity; ++i) { fout << (check[i] ? "YES" : "NO") << '\n'; } fout.close(); delete[] check; return 0; }
24.837838
111
0.51469
nothingelsematters
4dfe88bb4034d2693aa4cb511353bc4b26011e7d
5,145
cpp
C++
src/opt/call_inline.cpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
14
2020-04-14T17:00:56.000Z
2021-08-30T08:29:26.000Z
src/opt/call_inline.cpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
27
2020-12-27T16:00:44.000Z
2021-08-01T13:12:14.000Z
src/opt/call_inline.cpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
1
2020-05-29T18:33:37.000Z
2020-05-29T18:33:37.000Z
#include "internal/const_remapper.hpp" #include "internal/expr_matchers.hpp" #include "internal/prog_rewrite.hpp" #include "opt/opt.hpp" #include "prog/expr/nodes.hpp" #include "prog/expr/rewriter.hpp" #include "prog/sym/const_id_hasher.hpp" #include <cassert> #include <sstream> #include <unordered_set> namespace opt { // Calls to functions with more then 'g_maxInlineSrcFuncSize' expressions will not be inlined to // avoid bloating the executable. static unsigned int g_maxInlineSrcFuncSize = 50; class CallInlineRewriter final : public prog::expr::Rewriter { public: CallInlineRewriter( const prog::Program& prog, prog::sym::FuncId funcId, prog::sym::ConstDeclTable* consts) : m_prog{prog}, m_funcId{funcId}, m_consts{consts}, m_modified{false} { if (m_consts == nullptr) { throw std::invalid_argument{"Consts table cannot be null"}; } } [[nodiscard]] auto isInlinable(const prog::expr::CallExprNode* callExpr) -> bool; auto rewrite(const prog::expr::Node& expr) -> prog::expr::NodePtr override; [[nodiscard]] auto hasModified() -> bool override { return m_modified; } [[nodiscard]] auto inlineCall(const prog::expr::CallExprNode* callExpr) -> prog::expr::NodePtr; [[nodiscard]] auto registerTargetConsts(const prog::sym::ConstDeclTable& tgtConsts) -> internal::ConstRemapTable; private: const prog::Program& m_prog; prog::sym::FuncId m_funcId; prog::sym::ConstDeclTable* m_consts; bool m_modified; }; auto inlineCalls(const prog::Program& prog) -> prog::Program { auto modified = false; return inlineCalls(prog, modified); } auto inlineCalls(const prog::Program& prog, bool& modified) -> prog::Program { return internal::rewrite( prog, [](const prog::Program& prog, prog::sym::FuncId funcId, prog::sym::ConstDeclTable* consts) { return std::make_unique<CallInlineRewriter>(prog, funcId, consts); }, modified); } auto CallInlineRewriter::isInlinable(const prog::expr::CallExprNode* callExpr) -> bool { const auto funcId = callExpr->getFunc(); assert(callExpr->isComplete(m_prog)); // Call expression has to be complete (patched). // NOTE: Non-user function have no definition. const prog::sym::FuncDef* funcDef = m_prog.findFuncDef(funcId); // Non-normal (fork or lazy) calls or calls to non-user funcs are not inlinable. if (!funcDef || callExpr->getMode() != prog::expr::CallMode::Normal) { return false; } // Recursive calls cannot be inlined. if (funcId == m_funcId) { return false; } if (funcDef->hasFlags(prog::sym::FuncDef::Flags::NoInline)) { return false; } if (internal::exprSize(funcDef->getBody()) > g_maxInlineSrcFuncSize) { return false; } // Recursive functions are not inlined. if (internal::isRecursive(m_prog, *funcDef)) { return false; } // TODO(bastian): Consider adding size constraints to the functions we inline. return true; } auto CallInlineRewriter::rewrite(const prog::expr::Node& expr) -> prog::expr::NodePtr { if (expr.getKind() == prog::expr::NodeKind::Call) { auto* callExpr = expr.downcast<prog::expr::CallExprNode>(); if (isInlinable(callExpr)) { m_modified = true; return inlineCall(callExpr); } } return expr.clone(this); } auto CallInlineRewriter::inlineCall(const prog::expr::CallExprNode* callExpr) -> prog::expr::NodePtr { const auto& tgtFuncId = callExpr->getFunc(); const auto& tgtFuncDef = m_prog.getFuncDef(tgtFuncId); const auto& tgtConsts = tgtFuncDef.getConsts(); // Register all the consts of the target function into this function. auto constMapping = registerTargetConsts(tgtConsts); auto tgtInputs = tgtConsts.getInputs(); auto exprs = std::vector<prog::expr::NodePtr>{}; exprs.reserve(tgtInputs.size() + 1); // Create expressions to assign the constants that used to be inputs to the target function. for (auto i = 0U; i != tgtInputs.size(); ++i) { exprs.push_back(prog::expr::assignExprNode( *m_consts, constMapping.find(tgtInputs[i])->second, rewrite((*callExpr)[i]))); } // Remap the constants to point to the newly registered constants. auto remapper = internal::ConstRemapper{m_prog, *m_consts, constMapping}; auto remappedExpr = remapper.rewrite(tgtFuncDef.getBody()); // Run another 'rewrite' pass on the remapped expression so we can also inline calls inside the // inlined function body. exprs.push_back(rewrite(*remappedExpr)); return exprs.size() > 1 ? prog::expr::groupExprNode(std::move(exprs)) : std::move(exprs[0]); } auto CallInlineRewriter::registerTargetConsts(const prog::sym::ConstDeclTable& tgtConsts) -> internal::ConstRemapTable { auto table = internal::ConstRemapTable{}; for (const auto& tgtConstId : tgtConsts.getAll()) { const auto& tgtConstDecl = tgtConsts[tgtConstId]; std::ostringstream oss; oss << "__inlined_" << m_consts->getNextConstId().getNum() << '_' << tgtConstDecl.getName(); auto remappedConstId = m_consts->registerLocal(oss.str(), tgtConstDecl.getType()); table.insert({tgtConstId, remappedConstId}); } return table; } } // namespace opt
33.193548
98
0.704956
BastianBlokland
1502ec5ce1ad7ce13cd7fb396cbc67d8ead03f04
7,524
cpp
C++
src/subprocess/process.cpp
sithlord48/linuxdeploy
4c5b9c5dafd14412f80088a09437585aaf2edef4
[ "MIT" ]
298
2018-07-25T00:04:10.000Z
2022-03-31T15:26:28.000Z
src/subprocess/process.cpp
X0rg/linuxdeploy
58f8b6a6fd8eb9ecaec944f7dbd03cfe62f47e6e
[ "MIT" ]
183
2018-07-18T19:35:07.000Z
2022-03-31T13:38:50.000Z
src/subprocess/process.cpp
X0rg/linuxdeploy
58f8b6a6fd8eb9ecaec944f7dbd03cfe62f47e6e
[ "MIT" ]
45
2018-08-19T14:01:12.000Z
2022-03-17T06:35:20.000Z
// system headers #include <algorithm> #include <iostream> #include <memory> #include <sstream> #include <stdexcept> #include <utility> #include <unistd.h> #include <memory.h> #include <wait.h> // local headers #include "linuxdeploy/subprocess/process.h" #include "linuxdeploy/subprocess/subprocess.h" #include "linuxdeploy/util/assert.h" // shorter than using namespace ... using namespace linuxdeploy::subprocess; int process::pid() const { return child_pid_; } int process::stdout_fd() const { return stdout_fd_; } int process::stderr_fd() const { return stderr_fd_; } process::process(std::initializer_list<std::string> args, const subprocess_env_map_t& env) : process(std::vector<std::string>(args), env) {} process::process(const std::vector<std::string>& args, const subprocess_env_map_t& env) { // preconditions util::assert::assert_not_empty(args); // pipes for both stdout and stderr // the order is, as seen from the child: [read, write] int stdout_pipe_fds[2]; int stderr_pipe_fds[2]; // FIXME: for debugging of #150 auto create_pipe = [](int fds[]) { const auto rv = pipe(fds); if (rv != 0) { const auto error = errno; throw std::logic_error("failed to create pipe: " + std::string(strerror(error))); } }; // create actual pipes create_pipe(stdout_pipe_fds); create_pipe(stderr_pipe_fds); // create child process child_pid_ = fork(); if (child_pid_ < 0) { throw std::runtime_error{"fork() failed"}; } if (child_pid_ == 0) { // we're in the child process // first step: close the read end of both pipes close_pipe_fd_(stdout_pipe_fds[READ_END_]); close_pipe_fd_(stderr_pipe_fds[READ_END_]); auto connect_fd = [](int fd, int fileno) { for (;;) { if (dup2(fd, fileno) == -1) { const auto error = errno; if (error != EINTR) { throw std::logic_error{"failed to connect pipes: " + std::string(strerror(error))}; } continue; } break; } }; connect_fd(stdout_pipe_fds[WRITE_END_], STDOUT_FILENO); connect_fd(stderr_pipe_fds[WRITE_END_], STDERR_FILENO); // now, we also have to close the write end of both pipes close_pipe_fd_(stdout_pipe_fds[WRITE_END_]); close_pipe_fd_(stderr_pipe_fds[WRITE_END_]); // prepare arguments for exec* auto exec_args = make_args_vector_(args); auto exec_env = make_env_vector_(env); // call subprocess execvpe(args.front().c_str(), exec_args.data(), exec_env.data()); // only reached if exec* fails // clean up memory if exec should ever return // prevents memleaks if the exception below would be handled by a caller auto deleter = [](char* ptr) { free(ptr); ptr = nullptr; }; std::for_each(exec_args.begin(), exec_args.end(), deleter); std::for_each(exec_env.begin(), exec_env.end(), deleter); throw std::runtime_error{"exec() failed: " + std::string(strerror(errno))}; } // parent code // we do not intend to write to the processes close_pipe_fd_(stdout_pipe_fds[WRITE_END_]); close_pipe_fd_(stderr_pipe_fds[WRITE_END_]); // store file descriptors stdout_fd_ = stdout_pipe_fds[READ_END_]; stderr_fd_ = stderr_pipe_fds[READ_END_]; } int process::close() { if (!exited_) { close_pipe_fd_(stdout_fd_); stdout_fd_ = -1; close_pipe_fd_(stderr_fd_); stderr_fd_ = -1; { int status; if (waitpid(child_pid_, &status, 0) == -1) { throw std::logic_error{"waitpid() failed"}; } exited_ = true; exit_code_ = check_waitpid_status_(status); } } return exit_code_; } process::~process() { (void) close(); } std::vector<char*> process::make_args_vector_(const std::vector<std::string>& args) { std::vector<char*> rv{}; rv.reserve(args.size()); for (const auto& arg : args) { rv.emplace_back(strdup(arg.c_str())); } // execv* want a nullptr-terminated array rv.emplace_back(nullptr); return rv; } std::vector<char*> process::make_env_vector_(const subprocess_env_map_t& env) { std::vector<char*> rv; // first, copy existing environment // we cannot reserve space in the vector unfortunately, as we don't know the size of environ before the iteration if (environ != nullptr) { for (auto** current_env_var = environ; *current_env_var != nullptr; ++current_env_var) { rv.emplace_back(strdup(*current_env_var)); } } // add own environment variables, overwriting existing ones if necessary for (const auto& env_var : env) { const auto& key = env_var.first; const auto& value = env_var.second; auto predicate = [&key](char* existing_env_var) { char* equal_sign = strstr(existing_env_var, "="); if (equal_sign == nullptr) { throw std::runtime_error{"no equal sign in environment variable"}; } return strncmp(existing_env_var, key.c_str(), std::distance(equal_sign, existing_env_var)) == 0; }; // delete existing env var, if any rv.erase(std::remove_if(rv.begin(), rv.end(), predicate), rv.end()); // insert new value std::ostringstream oss; oss << key; oss << "="; oss << value; rv.emplace_back(strdup(oss.str().c_str())); } // exec*e want a nullptr-terminated array rv.emplace_back(nullptr); return rv; } void process::kill(int signal) const { if (::kill(child_pid_, signal) != 0) { throw std::logic_error{"failed to kill child process"}; } if (waitpid(child_pid_, nullptr, 0)) { throw std::logic_error{"failed to wait for killed child"}; } } bool process::is_running() { if (exited_) { return false; } int status; auto result = waitpid(child_pid_, &status, WNOHANG); if (result == 0) { return true; } if (result == child_pid_) { // TODO: extract the following lines from both this method and close() to eliminate duplicate code close_pipe_fd_(stdout_fd_); stdout_fd_ = -1; close_pipe_fd_(stderr_fd_); stderr_fd_ = -1; exited_ = true; exit_code_ = check_waitpid_status_(status); return false; } if (result < 0) { // TODO: check errno == ECHILD throw std::logic_error{"waitpid() failed: " + std::string(strerror(errno))}; } // can only happen if waitpid() returns an unknown process ID throw std::logic_error{"unknown error occured"}; } int process::check_waitpid_status_(int status) { if (WIFSIGNALED(status) != 0) { // TODO: consider treating child exit caused by signals separately return WTERMSIG(status); } else if (WIFEXITED(status) != 0) { return WEXITSTATUS(status); } throw std::logic_error{"unknown child process state"}; } void process::close_pipe_fd_(int fd) { const auto rv = ::close(fd); if (rv != 0) { const auto error = errno; throw std::logic_error("failed to close pipe fd: " + std::string(strerror(error))); } }
27.36
117
0.60513
sithlord48
150767b42ba3dac8100b63786ff64b5fda708ab7
1,418
hh
C++
tests/HelpTest.hh
azjezz/hh-clilib
ef39116c527ac2496c985657f93af0253c9d8227
[ "MIT" ]
null
null
null
tests/HelpTest.hh
azjezz/hh-clilib
ef39116c527ac2496c985657f93af0253c9d8227
[ "MIT" ]
null
null
null
tests/HelpTest.hh
azjezz/hh-clilib
ef39116c527ac2496c985657f93af0253c9d8227
[ "MIT" ]
null
null
null
<?hh // strict /* * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ namespace Facebook\CLILib; use namespace HH\Lib\Vec; use function Facebook\FBExpect\expect; final class HelpTest extends TestCase { public function testStandalone(): void { $stdin = new TestLib\StringInput(); $stdout = new TestLib\StringOutput(); $stderr = new TestLib\StringOutput(); $terminal = new Terminal($stdin, $stdout, $stderr); expect( () ==> new TestCLIWithoutArguments(vec[__FILE__, '--help'], $terminal) )->toThrow(ExitException::class); expect($stderr->getBuffer())->toBeSame(''); $buff = $stdout->getBuffer(); expect($buff)->toContain('--flag1'); expect($buff)->toContain('-1'); expect($buff)->toContain('Help text'); expect($buff)->toContain('--flag2'); } public function testAfterOptions(): void { $stdin = new TestLib\StringInput(); $stdout = new TestLib\StringOutput(); $stderr = new TestLib\StringOutput(); $terminal = new Terminal($stdin, $stdout, $stderr); expect( () ==> new TestCLIWithoutArguments( vec[__FILE__, '--flag1', '-h'], $terminal, ), )->toThrow(ExitException::class); expect($stdout->getBuffer())->toContain('--flag2'); } }
28.36
71
0.638223
azjezz
150f70b6048bb5be6185e5f3c2a0ece380654564
3,322
hh
C++
test/test_utils.hh
FirefoxMetzger/sdformat
b25ecbc75f6d54b0f35ceafb0222c8dd544fdbbc
[ "ECL-2.0", "Apache-2.0" ]
67
2020-04-11T22:27:46.000Z
2021-06-19T16:17:42.000Z
test/test_utils.hh
FirefoxMetzger/sdformat
b25ecbc75f6d54b0f35ceafb0222c8dd544fdbbc
[ "ECL-2.0", "Apache-2.0" ]
339
2020-04-13T23:15:09.000Z
2021-06-28T13:57:17.000Z
test/test_utils.hh
FirefoxMetzger/sdformat
b25ecbc75f6d54b0f35ceafb0222c8dd544fdbbc
[ "ECL-2.0", "Apache-2.0" ]
45
2020-04-14T21:27:44.000Z
2021-06-18T22:50:25.000Z
/* * Copyright 2021 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 SDF_TEST_UTILS_HH_ #define SDF_TEST_UTILS_HH_ #include <ostream> #include "sdf/Console.hh" namespace sdf { namespace testing { /// \brief Calls a function when going out of scope. /// Taken from: /// https://github.com/ros2/rclcpp/blob/master/rclcpp/include/rclcpp/scope_exit.hpp template <typename Callable> struct ScopeExit { /// \brief Constructor /// \param[in] _callable Any callable object that does not throw. explicit ScopeExit(Callable _callable) : callable(_callable) { } ~ScopeExit() { this->callable(); } private: Callable callable; }; /// \brief A class used for redirecting the output of sdferr, sdfwarn, etc to a /// more convenient stream object like a std::stringstream for testing purposes. /// The class reverts to the original stream object when it goes out of scope. /// /// Usage example: /// /// Redirect console output to a std::stringstream object: /// /// ``` /// std::stringstream buffer; /// sdf::testing::RedirectConsoleStream redir( /// sdf::Console::Instance()->GetMsgStream(), &buffer); /// /// sdfwarn << "Test message"; /// /// ``` /// `buffer` will now contain "Test message" with additional information, /// such as the file and line number where sdfwarn was called from. /// /// sdfdbg uses a log file as its output, so to redirect that, we can do /// /// ``` /// std::stringstream buffer; /// sdf::testing::RedirectConsoleStream redir( /// sdf::Console::Instance()->GetLogStream(), &buffer); /// /// sdfdbg << "Test message"; /// ``` class RedirectConsoleStream { /// \brief Constructor /// \param[in] _consoleStream Mutable reference to a console stream. /// \param[in] _newSink Pointer to any object derived from std::ostream public: RedirectConsoleStream(sdf::Console::ConsoleStream &_consoleStream, std::ostream *_newSink) : consoleStreamRef(_consoleStream) , oldStream(_consoleStream) { this->consoleStreamRef = sdf::Console::ConsoleStream(_newSink); } /// \brief Destructor. Restores the console to the original ConsoleStream /// object. public: ~RedirectConsoleStream() { this->consoleStreamRef = this->oldStream; } /// \brief Reference to the console stream object. This is usually obtained /// from the singleton sdf::Console object by calling either /// sdf::Console::GetMsgStream() or sdf::Console::GetLogStream() private: sdf::Console::ConsoleStream &consoleStreamRef; /// \brief Copy of the original console stream object. This will be used to /// restore the console stream when this object goes out of scope. private: sdf::Console::ConsoleStream oldStream; }; } // namespace testing } // namespace sdf #endif
29.660714
83
0.703191
FirefoxMetzger
151a8cfd397301375864395878766f7678013712
824
cpp
C++
projects/Phantom.JIT/phantom/jit/plugin.cpp
vlmillet/Phantom.JIT
c3a880ace39f41307325e93f05a55617cddd9b5d
[ "MIT" ]
11
2021-11-16T13:51:16.000Z
2022-03-15T08:11:33.000Z
projects/Phantom.JIT/phantom/jit/plugin.cpp
vlmillet/Phantom.JIT
c3a880ace39f41307325e93f05a55617cddd9b5d
[ "MIT" ]
null
null
null
projects/Phantom.JIT/phantom/jit/plugin.cpp
vlmillet/Phantom.JIT
c3a880ace39f41307325e93f05a55617cddd9b5d
[ "MIT" ]
2
2021-11-16T13:51:18.000Z
2021-11-17T02:33:16.000Z
// license [ // This file is part of the Phantom project. Copyright 2011-2020 Vivien Millet. // Distributed under the MIT license. Text available here at // https://github.com/vlmillet/phantom // ] #include "plugin.h" #include "Context.h" #include <llvm/Support/ManagedStatic.h> #include <llvm/Support/TargetSelect.h> #include <phantom/plugin> namespace phantom { namespace jit { void load() { llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); llvm::InitializeNativeTargetDisassembler(); Context::Main(); } void unload() { llvm::llvm_shutdown(); } PHANTOM_EXPORT_PHANTOM_JIT void autoload() {} } // namespace jit } // namespace phantom PHANTOM_PLUGIN("Phantom.JIT", PHANTOM_PLUGIN_REGISTER_CLASS_MEMBERS_ON_ACCESS, phantom::jit::load, phantom::jit::unload);
21.684211
98
0.726942
vlmillet
151d718537bc92078d8c4098657f08dbc1faa641
6,219
cpp
C++
demo/dsaboost.cpp
ipab-slmc/SDHLibrary-CPP
0217d4edf82f34292750240bd7a3d9c63feb7e33
[ "Apache-2.0" ]
2
2021-11-12T09:28:45.000Z
2021-12-22T09:09:31.000Z
demo/dsaboost.cpp
ipab-slmc/SDHLibrary-CPP
0217d4edf82f34292750240bd7a3d9c63feb7e33
[ "Apache-2.0" ]
null
null
null
demo/dsaboost.cpp
ipab-slmc/SDHLibrary-CPP
0217d4edf82f34292750240bd7a3d9c63feb7e33
[ "Apache-2.0" ]
2
2019-05-02T20:03:29.000Z
2019-06-24T14:50:42.000Z
//====================================================================== /*! \file \section sdhlibrary_cpp_sdh_dsaboost_cpp_general General file information \author Dirk Osswald \date 2009-08-02 \brief helper stuff for the "boosted" DSA stuff \section sdhlibrary_cpp_sdh_dsaboost_cpp_copyright Copyright Copyright (c) 2007 SCHUNK GmbH & Co. KG <HR> \internal \subsection sdhlibrary_cpp_sdh_dsaboost_cpp_details SVN related, detailed file specific information: $LastChangedBy: Osswald2 $ $LastChangedDate: 2009-11-02 09:20:24 +0100 (Mo, 02 Nov 2009) $ \par SVN file revision: $Id: dsaboost.cpp 4932 2009-11-02 08:20:24Z Osswald2 $ \subsection sdhlibrary_cpp_sdh_dsaboost_cpp_changelog Changelog of this file: \include dsaboost.cpp.log */ //====================================================================== #include <iostream> #include <fstream> #include <vector> // Include the cSDH interface #include "sdh/sdh.h" #include "sdh/util.h" #include "sdh/sdhlibrary_settings.h" #include "sdh/basisdef.h" #include "sdh/dsa.h" #include "dsaboost.h" #include <boost/bind.hpp> #include <boost/mem_fn.hpp> USING_NAMESPACE_SDH extern cDBG cdbg; //----------------------------------------------------------------- /*! run function of updater thread This function reads frames from the remote DSACON32m tactile sensor controllers continuously in an infinite loop. Uses global variable g_ts as the tactile sensor object which must point to a valid and connected cDSA object on call. */ void cDSAUpdater::Updater() { assert( ts != NULL ); int error_level = 0; cdbg << "cDSAUpdater::Updater(): thread started\n"; while( true ) { try { //cdbg << "_Updater: updating\n"; //semaphore.acquire() ts->UpdateFrame(); //semaphore.release() if ( error_level > 0 ) error_level--; // boost::this_thread::sleep(boost::posix_time::milliseconds(1000/40)); } catch (cDSAException* e) { error_level++; // ignore errors like checksum errors and retry next time cdbg << "cDSAUpdater::Updater(): ignoring " << e->what() << "\n"; delete e; } if ( error_level > error_threshold ) { std::cerr << "cDSAUpdater::Updater(): Too many errors from Tactile sensors of SDH. Reconnecting to DSACON32m!\n"; try { ts->Close(); boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); } catch (cDSAException* e) { // ignore errors while trying to reconnect cdbg << "cDSAUpdater::Updater(): ignoring " << e->what() << " while reconnecting step 1\n"; delete e; } try { ts->Open(); } catch (cDSAException* e) { // ignore errors while trying to reconnect cdbg << "cDSAUpdater::Updater(): ignoring " << e->what() << " while reconnecting step 2\n"; delete e; } try { ts->SetFramerate( 30, true ); error_level = 0; // reset error_level after successfull reconnection std::cerr << "cDSAUpdater::Updater() Succesfully reconnected to DSACON32m of SDH\n"; } catch (cDSAException* e) { // ignore errors while trying to reconnect cdbg << "cDSAUpdater::Updater(): ignoring " << e->what() << " while reconnecting step 3\n"; delete e; } } } } //----------------------------------------------------------------- cDSAUpdater::cDSAUpdater( cDSA* _ts, int _error_threshold ) : error_threshold(_error_threshold), ts(_ts) { assert( ts != NULL ); ts->SetFramerate( 30, true ); // start thread that reads the responses cdbg << "cDSAUpdater::cDSAUpdater(): Starting new updater thread..."; updater_thread = boost::thread( boost::bind(&cDSAUpdater::Updater, this ) ); cdbg << "OK\n"; } //----------------------------------------------------------------- double cIsGraspedByArea::FullArea( int m ) { return ts->GetMatrixInfo(m).cells_x * ts->GetMatrixInfo(m).texel_width * ts->GetMatrixInfo(m).cells_y * ts->GetMatrixInfo(m).texel_height; } void cIsGraspedByArea::SetCondition( double eaf0p, double eaf0d, double eaf1p, double eaf1d, double eaf2p, double eaf2d ) { expected_area[0] = eaf0p * FullArea( 0 ); expected_area[1] = eaf0d * FullArea( 1 ); expected_area[2] = eaf1p * FullArea( 2 ); expected_area[3] = eaf1d * FullArea( 3 ); expected_area[4] = eaf2p * FullArea( 4 ); expected_area[5] = eaf2d * FullArea( 5 ); } //! overloaded variant which uses an array of doubles instead of 6 single double parameters void cIsGraspedByArea::SetCondition( double* eafx ) { for ( int i=0; i<6; i++ ) expected_area[i] = eafx[i] * FullArea( i ); } //! default constructor which initializes the internal date cIsGraspedByArea::cIsGraspedByArea( cDSA* _ts ) // call base class constructors: : cIsGraspedBase( _ts ) { SetCondition( 0.5, 0.5, 0.5, 0.5, 0.5, 0.5 ); } /*! Implementation of is grasped condition. * * \return true if the object is grasped according to the actual tactile sensor * data in \a ts and the condition set with SetCondition() */ bool cIsGraspedByArea::IsGrasped(void) { cDSA::sContactInfo contact_info; bool is_grasped = true; for ( int i=0; i<6; i++ ) { contact_info = ts->GetContactInfo(i); if (contact_info.area < expected_area[ i ]) { is_grasped = false; break; } } return is_grasped; } //====================================================================== /* Here are some settings for the emacs/xemacs editor (and can be safely ignored) (e.g. to explicitely set C++ mode for *.h header files) Local Variables: mode:C++ mode:ELSE End: */ //======================================================================]
27.03913
125
0.559415
ipab-slmc
151e2b17d98636e4f0c80fb6227da16a507cb779
1,460
cpp
C++
BST_creation.cpp
priyanshu1044/cpp
fc7be7f38edfddfcb0477e1d732d84e448e7d009
[ "MIT" ]
null
null
null
BST_creation.cpp
priyanshu1044/cpp
fc7be7f38edfddfcb0477e1d732d84e448e7d009
[ "MIT" ]
null
null
null
BST_creation.cpp
priyanshu1044/cpp
fc7be7f38edfddfcb0477e1d732d84e448e7d009
[ "MIT" ]
5
2020-10-01T04:12:34.000Z
2021-10-22T04:49:45.000Z
#include<bits/stdc++.h> using namespace std; struct Node { struct Node *lchild; int data; struct Node *rchild; } *root = NULL; struct Node *RInsert(struct Node *p, int key) { struct Node *t = NULL; if (p == NULL) { t = (struct Node *)malloc(sizeof(struct Node)); t->data = key; t->lchild = t->rchild = NULL; return t; } if (key < p->data) p->lchild = RInsert(p->lchild, key); else if (key > p->data) p->rchild = RInsert(p->rchild, key); return p; } void Inorder(struct Node *p) { if (p) { Inorder(p->lchild); cout << p->data << " "; Inorder(p->rchild); } } void Preorder(struct Node *p) { if (p) { cout << p->data << " "; Preorder(p->lchild); Preorder(p->rchild); } } void Postorder(struct Node *p) { if (p) { Postorder(p->lchild); Postorder(p->rchild); cout << p->data << " "; } } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int T_node; cin >> T_node; int node, l_child, r_child; for (int i = 0; i < T_node; i++) { cin >> node >> l_child >> r_child; if (root == NULL) { root = RInsert(root, node); } RInsert(root, node); } Preorder(root); cout<<endl; Inorder(root); cout<<endl; Postorder(root); return 0; }
17.590361
77
0.49726
priyanshu1044
1522b458e7dbf25762d8757bc41c8a8339245998
2,692
cpp
C++
src/sdl_noOpenGL/MainMenu.cpp
callumpoole/2016-Pacman-Replica
17942799f0fffff614e78f59781e8b7041cbe263
[ "MIT" ]
null
null
null
src/sdl_noOpenGL/MainMenu.cpp
callumpoole/2016-Pacman-Replica
17942799f0fffff614e78f59781e8b7041cbe263
[ "MIT" ]
null
null
null
src/sdl_noOpenGL/MainMenu.cpp
callumpoole/2016-Pacman-Replica
17942799f0fffff614e78f59781e8b7041cbe263
[ "MIT" ]
null
null
null
#include "MainMenu.h" #include "MenuManager.h" #include "AudioGenerator.h" #include "SceneManager.h" #include "Button.h" #include "KeyBindingMenu.h" void SelectOnePlayer(int widgetIndex) { SceneManager::currentScene->SetAllEntitiesFrozenMovement(false); //Disable the second player SceneManager::currentScene->GetEntitiesOfType(Entity::EEntityType::player)[1]->SetAlive(false); MenuManager::curManager->menus[MenuManager::IND_MainMenu]->HideMenu(); } void SelectTwoPlayer(int widgetIndex) { SceneManager::currentScene->SetAllEntitiesFrozenMovement(false); MenuManager::curManager->menus[MenuManager::IND_MainMenu]->HideMenu(); } MainMenu::MainMenu() { menuRect = SDL_Rect{10,9,14,19 }; std::unique_ptr<Button> btn1(new Button("One Player", SDL_Rect{ 11,10,12,2 }, glm::vec3(0, 255, 0), glm::vec3(0, 0, 255), &SelectOnePlayer)); widgets.push_back(std::move(btn1)); std::unique_ptr<Button> btn2(new Button("Two Player", SDL_Rect{ 11,13,12,2 }, glm::vec3(0, 255, 0), glm::vec3(0, 0, 255) , &SelectTwoPlayer)); widgets.push_back(std::move(btn2)); std::unique_ptr<Button> btn3(new Button(" - ", SDL_Rect{ 11,16,2,2 }, glm::vec3(0, 255, 0), glm::vec3(0, 0, 255), [](int) {AudioGenerator::IncreasePsuedoVolumeBy(-1); })); //, &VolumeDown)); widgets.push_back(std::move(btn3)); std::unique_ptr<Button> btn4(new Button(" + ", SDL_Rect{ 21,16,2,2 }, glm::vec3(0, 255, 0), glm::vec3(0, 0, 255), [](int) {AudioGenerator::IncreasePsuedoVolumeBy(1); })); // , &VolumeUp)); widgets.push_back(std::move(btn4)); std::unique_ptr<Button> btn5(new Button("Volume: 10", SDL_Rect{ 14,16,6,2 }, glm::vec3(0, 0, 255), glm::vec3(0, 0, 255))); widgets.push_back(std::move(btn5)); std::unique_ptr<Button> btn6(new Button("Key Bindings", SDL_Rect{ 11,19,12,2 }, glm::vec3(0, 255, 0), glm::vec3(0, 0, 255), [](int) { MenuManager::curManager->menus[MenuManager::IND_MainMenu]->HideMenu(); MenuManager::curManager->menus[MenuManager::IND_KeyMenu]->ShowMenu(); dynamic_cast<KeyBindingMenu*>(MenuManager::curManager->menus[MenuManager::IND_KeyMenu].get())->previousMenuID = 0; })); widgets.push_back(std::move(btn6)); std::unique_ptr<Button> btn7(new Button("High Scores", SDL_Rect{ 11,22,12,2 }, glm::vec3(0, 255, 0), glm::vec3(0, 0, 255), [](int) { MenuManager::curManager->menus[MenuManager::IND_MainMenu]->HideMenu(); MenuManager::curManager->menus[MenuManager::IND_HighScoreMenu]->ShowMenu(); })); widgets.push_back(std::move(btn7)); std::unique_ptr<Button> btn8(new Button("Exit", SDL_Rect{ 11,25,12,2 }, glm::vec3(0, 255, 0), glm::vec3(0, 0, 255), [](int) {MenuManager::curManager->shouldCloseGame = true; })); //, &Exit)); widgets.push_back(std::move(btn8)); }
47.22807
195
0.69948
callumpoole
152400e14401c2d9a457506715e30007cf970d2e
37,326
cpp
C++
test/protocol_binary.cpp
arosh/yrmcds
350c8b9907e4760e47b75dc13d49c3639f38641c
[ "BSD-2-Clause" ]
75
2015-01-15T07:40:01.000Z
2021-09-21T15:39:35.000Z
test/protocol_binary.cpp
arosh/yrmcds
350c8b9907e4760e47b75dc13d49c3639f38641c
[ "BSD-2-Clause" ]
36
2015-01-21T00:40:51.000Z
2021-12-13T07:39:26.000Z
test/protocol_binary.cpp
arosh/yrmcds
350c8b9907e4760e47b75dc13d49c3639f38641c
[ "BSD-2-Clause" ]
16
2015-03-04T03:04:01.000Z
2022-02-08T23:52:49.000Z
#include "../src/memcache/memcache.hpp" #include <cybozu/dynbuf.hpp> #include <cybozu/tcp.hpp> #define TEST_DISABLE_AUTO_RUN #include <cybozu/test.hpp> #include <cybozu/util.hpp> #include <chrono> #include <cstdint> #include <cstring> #include <fcntl.h> #include <iostream> #include <string> #include <sys/socket.h> #include <sys/types.h> #include <thread> #include <unistd.h> #include <vector> using yrmcds::memcache::binary_command; using yrmcds::memcache::binary_status; using yrmcds::memcache::item; const char* g_server = nullptr; std::uint16_t g_port = 11211; typedef char opaque_t[4]; const std::size_t BINARY_HEADER_SIZE = 24; int connect_server() { int s = cybozu::tcp_connect(g_server, g_port); if( s == -1 ) return -1; ::fcntl(s, F_SETFL, ::fcntl(s, F_GETFL, 0) & ~O_NONBLOCK); struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 300000; ::setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); int ok = 1; ::setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &ok, sizeof(ok)); return s; } // compose binary request class request { public: request(binary_command cmd, std::uint16_t key_len, const char* key, char extras_len, const char* extras, std::uint32_t data_len, const char* data, opaque_t* opaque = nullptr, std::uint64_t cas = 0): m_data(BINARY_HEADER_SIZE + key_len + extras_len + data_len), m_p(&m_data[0]) { m_p[0] = '\x80'; m_p[1] = (char)cmd; cybozu::hton(key_len, m_p+2); m_p[4] = extras_len; m_p[5] = 0; m_p[6] = 0; m_p[7] = 0; std::uint32_t total_len = key_len + extras_len + data_len; cybozu::hton(total_len, m_p+8); if( opaque != nullptr ) std::memcpy(m_p+12, opaque, sizeof(opaque_t)); cybozu::hton(cas, m_p+16); char* p = m_p + BINARY_HEADER_SIZE; std::memcpy(p, extras, extras_len); p += extras_len; std::memcpy(p, key, key_len); p += key_len; std::memcpy(p, data, data_len); } const char* data() { return m_p; } std::size_t length() const noexcept { return m_data.size(); } private: std::vector<char> m_data; char* const m_p; }; // parse binary response class response { public: response() {} response(response&&) noexcept = default; // Return length of the response. // // Return length of the response. // If the response is incomplete, zero is returned. std::size_t length() const noexcept { return m_response_len; } // Response status, if determined by the request. binary_status status() const noexcept { return m_status; } // Return `true` if the response status was not OK. bool error() { return m_status != binary_status::OK; } // Return the command type. binary_command command() const noexcept { return m_command; } // Return `key`. item key() const noexcept { return m_key; } // Return `opaque` sent with the request. const char* opaque() const noexcept { return m_p + 12; } // Return `cas unique` sent with CAS command. std::uint64_t cas_unique() const noexcept { return m_cas_unique; } // Return `flags` sent with storage commands. std::uint32_t flags() const noexcept { return m_flags; } // Return data block sent with storage commands. item data() const noexcept { return m_data; } // Return an unsigned 64bit integer value for increment or decrement. std::uint64_t value() const noexcept { return m_value; } bool parse(const char* p, std::size_t len); private: const char* m_p = nullptr; std::size_t m_len = 0; std::size_t m_response_len = 0; binary_status m_status; binary_command m_command; item m_key; std::uint64_t m_cas_unique; std::uint32_t m_flags = 0; item m_data; std::uint64_t m_value = 0; }; bool response::parse(const char* p, std::size_t len) { m_p = p; m_len = len; if( m_len < BINARY_HEADER_SIZE ) return false; cybozu_assert( *m_p == '\x81' ); std::uint32_t total_len; cybozu::ntoh(m_p + 8, total_len); if( m_len < (BINARY_HEADER_SIZE + total_len) ) return false; m_response_len = BINARY_HEADER_SIZE + total_len; m_command = (binary_command)*(unsigned char*)(m_p + 1); std::uint16_t key_len; cybozu::ntoh(m_p + 2, key_len); std::uint8_t extras_len = *(unsigned char*)(m_p + 4); cybozu_assert( total_len >= (key_len + extras_len) ); if( key_len > 0 ) { m_key = item(m_p + (BINARY_HEADER_SIZE + extras_len), key_len); } else { m_key = item(nullptr, 0); } std::uint16_t i_status; cybozu::ntoh(m_p + 6, i_status); m_status = (binary_status)i_status; cybozu::ntoh(m_p + 16, m_cas_unique); std::size_t data_len = total_len - key_len - extras_len; if( data_len > 0 ) { m_data = item(m_p + (BINARY_HEADER_SIZE + extras_len + key_len), data_len); } else { m_data = item(nullptr, 0); } if( extras_len > 0 ) { cybozu_assert( extras_len == 4 ); cybozu::ntoh(m_p + BINARY_HEADER_SIZE, m_flags); } if( (m_command == binary_command::Increment || m_command == binary_command::Decrement) && m_status == binary_status::OK ) { cybozu_assert( data_len == 8 ); if( data_len == 8 ) { cybozu::ntoh(m_p + BINARY_HEADER_SIZE + key_len + extras_len, m_value); } } return true; } class client { public: client(): m_socket(connect_server()), m_buffer(1 << 20) { cybozu_assert( m_socket != -1 ); } ~client() { ::close(m_socket); } bool get_response(response& resp) { m_buffer.erase(m_last_response_size); m_last_response_size = 0; if( m_buffer.empty() ) { if( ! recv() ) { cybozu_assert( m_buffer.empty() ); return false; } } while( true ) { if( resp.parse(m_buffer.data(), m_buffer.size()) ) { m_last_response_size = resp.length(); return true; } cybozu_assert( recv() ); } } void noop(opaque_t* opaque) { request req(binary_command::Noop, 0, nullptr, 0, nullptr, 0, nullptr, opaque); send(req.data(), req.length()); } void get(const std::string& key, bool q) { request req(q ? binary_command::GetQ : binary_command::Get, (std::uint16_t)key.size(), key.data(), 0, nullptr, 0, nullptr); send(req.data(), req.length()); } void getk(const std::string& key, bool q) { request req(q ? binary_command::GetKQ : binary_command::GetK, (std::uint16_t)key.size(), key.data(), 0, nullptr, 0, nullptr); send(req.data(), req.length()); } void touch(const std::string& key, std::uint32_t expire) { char extra[4]; cybozu::hton(expire, extra); request req(binary_command::Touch, (std::uint16_t)key.size(), key.data(), sizeof(extra), extra, 0, nullptr); send(req.data(), req.length()); } void get_and_touch(const std::string& key, std::uint32_t expire, bool q) { char extra[4]; cybozu::hton(expire, extra); request req(q ? binary_command::GaTQ : binary_command::GaT, (std::uint16_t)key.size(), key.data(), sizeof(extra), extra, 0, nullptr); send(req.data(), req.length()); } void getk_and_touch(const std::string& key, std::uint32_t expire, bool q) { char extra[4]; cybozu::hton(expire, extra); request req(q ? binary_command::GaTKQ : binary_command::GaTK, (std::uint16_t)key.size(), key.data(), sizeof(extra), extra, 0, nullptr); send(req.data(), req.length()); } void lock_and_get(const std::string& key, bool q) { request req(q ? binary_command::LaGQ : binary_command::LaG, (std::uint16_t)key.size(), key.data(), 0, nullptr, 0, nullptr); send(req.data(), req.length()); } void lock_and_getk(const std::string& key, bool q) { request req(q ? binary_command::LaGKQ : binary_command::LaGK, (std::uint16_t)key.size(), key.data(), 0, nullptr, 0, nullptr); send(req.data(), req.length()); } void set(const std::string& key, const std::string& data, bool q, std::uint32_t flags, std::uint32_t expire, std::uint64_t cas = 0) { char extra[8]; cybozu::hton(flags, extra); cybozu::hton(expire, &extra[4]); request req(q ? binary_command::SetQ : binary_command::Set, (std::uint16_t)key.size(), key.data(), sizeof(extra), extra, (std::uint32_t)data.length(), data.data(), nullptr, cas); send(req.data(), req.length()); } void replace(const std::string& key, const std::string& data, bool q, std::uint32_t flags, std::uint32_t expire, std::uint64_t cas = 0) { char extra[8]; cybozu::hton(flags, extra); cybozu::hton(expire, &extra[4]); request req(q ? binary_command::ReplaceQ : binary_command::Replace, (std::uint16_t)key.size(), key.data(), sizeof(extra), extra, (std::uint32_t)data.length(), data.data(), nullptr, cas); send(req.data(), req.length()); } void add(const std::string& key, const std::string& data, bool q, std::uint32_t flags, std::uint32_t expire, std::uint64_t cas = 0) { char extra[8]; cybozu::hton(flags, extra); cybozu::hton(expire, &extra[4]); request req(q ? binary_command::AddQ : binary_command::Add, (std::uint16_t)key.size(), key.data(), sizeof(extra), extra, (std::uint32_t)data.length(), data.data(), nullptr, cas); send(req.data(), req.length()); } void replace_and_unlock(const std::string& key, const std::string& data, bool q, std::uint32_t flags, std::uint32_t expire, std::uint64_t cas = 0) { char extra[8]; cybozu::hton(flags, extra); cybozu::hton(expire, &extra[4]); request req(q ? binary_command::RaUQ : binary_command::RaU, (std::uint16_t)key.size(), key.data(), sizeof(extra), extra, (std::uint32_t)data.length(), data.data(), nullptr, cas); send(req.data(), req.length()); } void incr(const std::string& key, std::uint64_t value, bool q, std::uint32_t expire = ~(std::uint32_t)0, std::uint64_t initial = 0, std::uint64_t cas = 0) { char extra[20]; cybozu::hton(value, extra); cybozu::hton(initial, &extra[8]); cybozu::hton(expire, &extra[16]); request req(q ? binary_command::IncrementQ : binary_command::Increment, (std::uint16_t)key.size(), key.data(), sizeof(extra), extra, 0, nullptr, nullptr, cas); send(req.data(), req.length()); } void decr(const std::string& key, std::uint64_t value, bool q, std::uint32_t expire = ~(std::uint32_t)0, std::uint64_t initial = 0, std::uint64_t cas = 0) { char extra[20]; cybozu::hton(value, extra); cybozu::hton(initial, &extra[8]); cybozu::hton(expire, &extra[16]); request req(q ? binary_command::DecrementQ : binary_command::Decrement, (std::uint16_t)key.size(), key.data(), sizeof(extra), extra, 0, nullptr, nullptr, cas); send(req.data(), req.length()); } void append(const std::string& key, const std::string& value, bool q, std::uint64_t cas = 0) { request req(q ? binary_command::AppendQ : binary_command::Append, (std::uint16_t)key.size(), key.data(), 0, nullptr, (std::uint32_t)value.size(), value.data(), nullptr, cas); send(req.data(), req.length()); } void prepend(const std::string& key, const std::string& value, bool q, std::uint64_t cas = 0) { request req(q ? binary_command::PrependQ : binary_command::Prepend, (std::uint16_t)key.size(), key.data(), 0, nullptr, (std::uint32_t)value.size(), value.data(), nullptr, cas); send(req.data(), req.length()); } void remove(const std::string& key, bool q, std::uint64_t cas = 0) { request req(q ? binary_command::DeleteQ : binary_command::Delete, (std::uint16_t)key.size(), key.data(), 0, nullptr, 0, nullptr, nullptr, cas); send(req.data(), req.length()); } void lock(const std::string& key, bool q) { request req(q ? binary_command::LockQ : binary_command::Lock, (std::uint16_t)key.size(), key.data(), 0, nullptr, 0, nullptr); send(req.data(), req.length()); } void unlock(const std::string& key, bool q) { request req(q ? binary_command::UnlockQ : binary_command::Unlock, (std::uint16_t)key.size(), key.data(), 0, nullptr, 0, nullptr); send(req.data(), req.length()); } void unlock_all(bool q) { request req(q ? binary_command::UnlockAllQ : binary_command::UnlockAll, 0, nullptr, 0, nullptr, 0, nullptr); send(req.data(), req.length()); } void flush_all(bool q, std::uint32_t expire = 0) { if( expire == 0 ) { request req(q ? binary_command::FlushQ : binary_command::Flush, 0, nullptr, 0, nullptr, 0, nullptr); send(req.data(), req.length()); return; } char extra[4]; cybozu::hton(expire, extra); request req(q ? binary_command::FlushQ : binary_command::Flush, 0, nullptr, sizeof(extra), extra, 0, nullptr); send(req.data(), req.length()); } void version() { request req(binary_command::Version, 0, nullptr, 0, nullptr, 0, nullptr); send(req.data(), req.length()); } void stat() { request req(binary_command::Stat, 0, nullptr, 0, nullptr, 0, nullptr); send(req.data(), req.length()); } void stat(const std::string& key) { request req(binary_command::Stat, (std::uint16_t)key.size(), key.data(), 0, nullptr, 0, nullptr); send(req.data(), req.length()); } void keys(const std::string& key) { request req(binary_command::Keys, (std::uint16_t)key.size(), key.data(), 0, nullptr, 0, nullptr); send(req.data(), req.length()); } void quit(bool q) { request req(q ? binary_command::QuitQ : binary_command::Quit, 0, nullptr, 0, nullptr, 0, nullptr); send(req.data(), req.length()); } private: const int m_socket; cybozu::dynbuf m_buffer; std::size_t m_last_response_size = 0; void send(const char* p, std::size_t len) { while( len > 0 ) { ssize_t n = ::send(m_socket, p, len, 0); cybozu_assert( n != -1 ); p += n; len -= n; } } bool recv() { char* p = m_buffer.prepare(256 << 10); ssize_t n = ::recv(m_socket, p, 256<<10, 0); cybozu_assert( n != -1 ); if( n == -1 || n == 0 ) return false; m_buffer.consume(n); return true; } }; void print_item(const item& i) { std::cout << std::string(std::get<0>(i), std::get<1>(i)) << std::endl; } bool itemcmp(const item& i, const std::string& s) { if( s.size() != std::get<1>(i) ) return false; return std::memcmp(s.data(), std::get<0>(i), s.size()) == 0; } // tests #define ASSERT_COMMAND(r,cmd) cybozu_assert( r.command() == binary_command::cmd ) #define ASSERT_OK(r) cybozu_assert( r.status() == binary_status::OK ) AUTOTEST(opaque) { client c; response r; c.noop(nullptr); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Noop); ASSERT_OK(r); opaque_t zero = {'\0', '\0', '\0', '\0'}; cybozu_assert( std::memcmp(r.opaque(), &zero, sizeof(opaque_t)) == 0 ); opaque_t op1 = {'\x12', '\x23', '\x45', '\x67'}; c.noop(&op1); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Noop); ASSERT_OK(r); cybozu_assert( std::memcmp(r.opaque(), &op1, sizeof(opaque_t)) == 0 ); } AUTOTEST(quit) { client c; response r; c.quit(false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Quit); ASSERT_OK( r ); } AUTOTEST(quitq) { client c; response r; c.quit(true); cybozu_assert( ! c.get_response(r) ); } AUTOTEST(version) { client c; response r; c.version(); cybozu_assert( c.get_response(r) ); print_item( r.data() ); } AUTOTEST(set) { client c; response r; c.set("hello", "world", false, 123, 0); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Set); ASSERT_OK(r); c.set("hello", "world!", false, 111, 0, r.cas_unique()); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Set); ASSERT_OK(r); c.set("hello", "world!!", true, 111, 0, r.cas_unique() + 1); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, SetQ); cybozu_assert( r.status() == binary_status::Exists ); c.set("not exist", "hoge", true, 111, 0, 100); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, SetQ); cybozu_assert( r.status() == binary_status::NotFound ); c.set("abc", "def", true, 123, 0); c.noop(nullptr); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Noop); c.get("abc", false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Get); ASSERT_OK(r); cybozu_assert( itemcmp(r.data(), "def") ); cybozu_assert( r.flags() == 123 ); c.get("not exist", false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Get); cybozu_assert( r.status() == binary_status::NotFound ); c.get("not exist", true); c.noop(nullptr); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Noop); ASSERT_OK(r); } AUTOTEST(expire) { client c; response r; c.set("abc", "def1", true, 123, 1); c.get("abc", false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Get); ASSERT_OK(r); std::this_thread::sleep_for(std::chrono::seconds(3)); c.get("abc", false); cybozu_assert( c.get_response(r) ); cybozu_assert( r.status() == binary_status::NotFound ); } AUTOTEST(touch) { client c; response r; c.remove("abc", true); c.touch("abc", 0); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Touch); cybozu_assert( r.status() == binary_status::NotFound ); c.set("abc", "def", true, 10, 2); c.touch("abc", 0); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Touch); ASSERT_OK(r); std::uint64_t cas = r.cas_unique(); cybozu_assert( cas != 0 ); std::this_thread::sleep_for(std::chrono::seconds(4)); c.get("abc", false); cybozu_assert( c.get_response(r) ); ASSERT_OK(r); cybozu_assert( r.cas_unique() == cas ); c.touch("abc", 1); cybozu_assert( c.get_response(r) ); ASSERT_OK(r); cybozu_assert( r.cas_unique() == cas ); std::this_thread::sleep_for(std::chrono::seconds(3)); c.get("abc", false); cybozu_assert( c.get_response(r) ); cybozu_assert( r.status() == binary_status::NotFound ); } AUTOTEST(add) { client c; response r; c.set("abc", "def", true, 0, 0); c.add("abc", "123", true, 0, 0); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, AddQ); cybozu_assert( r.status() == binary_status::Exists ); c.remove("abc", true); c.add("abc", "123", false, 0, 0); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Add); ASSERT_OK(r); } AUTOTEST(replace) { client c; response r; c.replace("not exist", "hoge", true, 100, 0); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, ReplaceQ); cybozu_assert( r.status() == binary_status::NotFound ); c.set("abc", "def", true, 10, 0); c.replace("abc", "123", false, 100, 0); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Replace); ASSERT_OK(r); c.get("abc", false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Get); ASSERT_OK(r); cybozu_assert( itemcmp(r.data(), "123") ); cybozu_assert( r.flags() == 100 ); } AUTOTEST(get) { client c; response r; c.remove("unique key", true); c.add("unique key", "value", false, 10, 0); cybozu_assert( c.get_response(r) ); ASSERT_OK(r); c.replace("unique key", "value2", false, 11, 0); cybozu_assert( c.get_response(r) ); ASSERT_OK(r); std::uint64_t cas = r.cas_unique(); c.get("unique key", false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Get); ASSERT_OK(r); cybozu_assert( r.key() == item(nullptr, 0) ); cybozu_assert( itemcmp(r.data(), "value2") ); cybozu_assert( r.flags() == 11 ); cybozu_assert( r.cas_unique() == cas ); c.getk("unique key", false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, GetK); ASSERT_OK(r); cybozu_assert( itemcmp(r.key(), "unique key") ); cybozu_assert( itemcmp(r.data(), "value2") ); cybozu_assert( r.flags() == 11 ); cybozu_assert( r.cas_unique() == cas ); } AUTOTEST(get_and_touch) { client c; response r; c.set("abc", "def", true, 10, 2); c.get_and_touch("abc", 0, false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, GaT); ASSERT_OK(r); cybozu_assert( std::get<1>(r.key()) == 0 ); cybozu_assert( itemcmp(r.data(), "def") ); std::this_thread::sleep_for(std::chrono::seconds(4)); c.getk_and_touch("abc", 1, false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, GaTK); ASSERT_OK(r); cybozu_assert( itemcmp(r.key(), "abc") ); cybozu_assert( itemcmp(r.data(), "def") ); std::this_thread::sleep_for(std::chrono::seconds(3)); c.touch("abc", 0); cybozu_assert( c.get_response(r) ); cybozu_assert( r.status() == binary_status::NotFound ); } AUTOTEST(incr_decr) { client c; response r; c.set("abc", "def", true, 10, 0); c.incr("abc", 10, true); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, IncrementQ); cybozu_assert( r.status() == binary_status::NonNumeric ); c.remove("abc", true); c.incr("abc", 10, true); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, IncrementQ); cybozu_assert( r.status() == binary_status::NotFound ); c.incr("abc", 10, false, 0, 12); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Increment); ASSERT_OK(r); cybozu_assert( r.value() == 12 ); cybozu_assert( r.flags() == 0 ); std::uint64_t cas = r.cas_unique(); cybozu_assert( cas != 0 ); c.incr("abc", 10, false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Increment); ASSERT_OK(r); cybozu_assert( r.value() == 22 ); cybozu_assert( r.cas_unique() != 0 ); cybozu_assert( cas != r.cas_unique() ); cas = r.cas_unique(); c.decr("abc", 1, false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Decrement); ASSERT_OK(r); cybozu_assert( r.value() == 21 ); cybozu_assert( r.cas_unique() != 0 ); cybozu_assert( cas != r.cas_unique() ); c.decr("abc", 100, false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Decrement); ASSERT_OK(r); cybozu_assert( r.value() == 0 ); c.remove("abc", true); c.decr("abc", 1, true); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, DecrementQ); cybozu_assert( r.status() == binary_status::NotFound ); c.set("abc", "def", true, 10, 0); c.decr("abc", 1, true); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, DecrementQ); cybozu_assert( r.status() == binary_status::NonNumeric ); c.remove("abc", true); c.decr("abc", 10, false, 0, 22); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Decrement); ASSERT_OK(r); cybozu_assert( r.value() == 22 ); } AUTOTEST(append_prepend) { client c; response r; c.remove("ttt", true); c.append("ttt", "111", true); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, AppendQ); cybozu_assert( r.status() == binary_status::NotFound ); c.set("ttt", "aaa", true, 0, 0); c.append("ttt", "111", false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Append); ASSERT_OK(r); std::uint64_t cas = r.cas_unique(); cybozu_assert( cas != 0 ); c.get("ttt", false); cybozu_assert( c.get_response(r) ); ASSERT_OK(r); cybozu_assert( itemcmp(r.data(), "aaa111") ); c.prepend("ttt", "222", false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Prepend); ASSERT_OK(r); cybozu_assert( r.cas_unique() != 0 ); cybozu_assert( cas != r.cas_unique() ); c.get("ttt", false); cybozu_assert( c.get_response(r) ); ASSERT_OK(r); cybozu_assert( itemcmp(r.data(), "222aaa111") ); c.remove("ttt", true); c.prepend("ttt", "111", true); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, PrependQ); cybozu_assert( r.status() == binary_status::NotFound ); } AUTOTEST(delete) { client c; response r; c.set("abc", "def", true, 10, 0); c.remove("abc", false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Delete); ASSERT_OK(r); c.set("abc", "def", false, 10, 0); cybozu_assert( c.get_response(r) ); ASSERT_OK(r); std::uint64_t cas = r.cas_unique(); c.remove("abc", true, cas + 1); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, DeleteQ); cybozu_assert( r.status() == binary_status::Exists ); c.remove("abc", false, cas); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Delete); ASSERT_OK(r); c.remove("abc", false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Delete); cybozu_assert( r.status() == binary_status::NotFound ); c.remove("abc", true); c.noop(nullptr); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Noop); } AUTOTEST(lock) { client c; response r; c.set("abc", "10", false, 0, 0); cybozu_assert( c.get_response(r) ); { client c2; c2.lock("abc", false); cybozu_assert( c2.get_response(r) ); ASSERT_COMMAND(r, Lock); ASSERT_OK(r); c.lock("abc", true); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, LockQ); cybozu_assert( r.status() == binary_status::Locked ); c2.quit(false); cybozu_assert( c2.get_response(r) ); } c.lock("abc", false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Lock); ASSERT_OK(r); c.quit(false); c.get_response(r); } AUTOTEST(unlock) { client c; response r; c.remove("abc", false); cybozu_assert( c.get_response(r) ); ASSERT_OK(r); c.lock("abc", true); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, LockQ); cybozu_assert( r.status() == binary_status::NotFound ); c.unlock("abc", true); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, UnlockQ); cybozu_assert( r.status() == binary_status::NotFound ); c.set("abc", "def", true, 10, 0); c.unlock("abc", true); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, UnlockQ); cybozu_assert( r.status() == binary_status::NotLocked ); c.lock("abc", false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Lock); ASSERT_OK(r); client c2; c2.unlock("abc", true); cybozu_assert( c2.get_response(r) ); ASSERT_COMMAND(r, UnlockQ); cybozu_assert( r.status() == binary_status::NotLocked ); c.unlock("abc", false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Unlock); ASSERT_OK(r); c2.lock("abc", false); cybozu_assert( c2.get_response(r) ); ASSERT_COMMAND(r, Lock); ASSERT_OK(r); c2.quit(false); c2.get_response(r); } AUTOTEST(unlock_all) { client c; response r; c.set("abc", "1", true, 10, 0); c.set("def", "2", true, 10, 0); c.lock("abc", false); cybozu_assert( c.get_response(r) ); ASSERT_OK(r); c.lock("def", false); cybozu_assert( c.get_response(r) ); ASSERT_OK(r); client c2; c2.lock("abc", true); cybozu_assert( c2.get_response(r) ); cybozu_assert( r.status() == binary_status::Locked ); c2.lock("def", true); cybozu_assert( c2.get_response(r) ); cybozu_assert( r.status() == binary_status::Locked ); c.unlock_all(false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, UnlockAll); ASSERT_OK(r); c2.lock("abc", false); cybozu_assert( c2.get_response(r) ); ASSERT_OK(r); c2.lock("def", false); cybozu_assert( c2.get_response(r) ); ASSERT_OK(r); c2.quit(false); c2.get_response(r); } AUTOTEST(lock_and_get) { client c; response r; c.remove("abc", true); c.lock_and_get("abc", true); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, LaGQ); cybozu_assert( r.status() == binary_status::NotFound ); c.set("abc", "def", true, 10, 0); c.lock_and_get("abc", false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, LaG); ASSERT_OK(r); cybozu_assert( std::get<1>(r.key()) == 0 ); cybozu_assert( itemcmp(r.data(), "def") ); std::uint64_t cas = r.cas_unique(); c.lock_and_get("abc", true); cybozu_assert( c.get_response(r) ); cybozu_assert( r.status() == binary_status::Locked ); client c2; c2.lock_and_get("abc", true); cybozu_assert( c2.get_response(r) ); cybozu_assert( r.status() == binary_status::Locked ); c2.replace_and_unlock("abc", "ghi", true, 20, 0); cybozu_assert( c2.get_response(r) ); ASSERT_COMMAND(r, RaUQ); cybozu_assert( r.status() == binary_status::NotLocked ); c.replace_and_unlock("abc", "ghi", false, 20, 0); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, RaU); ASSERT_OK(r); cybozu_assert( r.cas_unique() != cas ); cybozu_assert( r.cas_unique() != 0 ); c2.lock_and_getk("abc", false); cybozu_assert( c2.get_response(r) ); ASSERT_OK(r); cybozu_assert( itemcmp(r.key(), "abc") ); cybozu_assert( itemcmp(r.data(), "ghi") ); c2.quit(false); c2.get_response(r); } AUTOTEST(flush) { client c; response r; c.set("abc", "def", true, 10, 0); c.flush_all(true, 2); c.get("abc", false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Get); ASSERT_OK(r); std::this_thread::sleep_for(std::chrono::seconds(4)); c.get("abc", false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Get); cybozu_assert( r.status() == binary_status::NotFound ); c.set("abc", "234", true, 10, 0); c.flush_all(false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Flush); ASSERT_OK(r); c.get("abc", false); cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Get); cybozu_assert( r.status() == binary_status::NotFound ); } AUTOTEST(stat_general) { client c; response r; c.stat(); while( true ) { cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Stat); ASSERT_OK(r); if( std::get<1>(r.key()) == 0 ) break; continue; std::cout << std::string(std::get<0>(r.key()), std::get<1>(r.key())) << ": " << std::string(std::get<0>(r.data()), std::get<1>(r.data())) << std::endl; } } AUTOTEST(stat_settings) { client c; response r; c.stat("settings"); while( true ) { cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Stat); ASSERT_OK(r); if( std::get<1>(r.key()) == 0 ) break; continue; std::cout << std::string(std::get<0>(r.key()), std::get<1>(r.key())) << ": " << std::string(std::get<0>(r.data()), std::get<1>(r.data())) << std::endl; } } AUTOTEST(stat_sizes) { client c; response r; c.stat("sizes"); while( true ) { cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Stat); ASSERT_OK(r); if( std::get<1>(r.key()) == 0 ) break; continue; std::cout << std::string(std::get<0>(r.key()), std::get<1>(r.key())) << ": " << std::string(std::get<0>(r.data()), std::get<1>(r.data())) << std::endl; } } AUTOTEST(stat_items) { client c; response r; c.stat("items"); while( true ) { cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Stat); ASSERT_OK(r); if( std::get<1>(r.key()) == 0 ) break; continue; std::cout << std::string(std::get<0>(r.key()), std::get<1>(r.key())) << ": " << std::string(std::get<0>(r.data()), std::get<1>(r.data())) << std::endl; } } AUTOTEST(stat_ops) { client c; response r; c.stat("ops"); while( true ) { cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Stat); ASSERT_OK(r); if( std::get<1>(r.key()) == 0 ) break; continue; std::cout << std::string(std::get<0>(r.key()), std::get<1>(r.key())) << ": " << std::string(std::get<0>(r.data()), std::get<1>(r.data())) << std::endl; } } AUTOTEST(keys) { client c; response r; c.flush_all(true, 0); std::this_thread::sleep_for(std::chrono::seconds(2)); c.set("foo", "bar", true, 10, 0); c.set("fo1", "bar", true, 10, 0); c.set("zzzzzzzzz", "bar", true, 10, 0); c.keys(""); int n = 0; while( true ) { cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Keys); ASSERT_OK(r); if( std::get<1>(r.key()) == 0 ) break; ++n; } cybozu_assert( n == 3 ); n = 0; c.keys("f"); while( true ) { cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Keys); ASSERT_OK(r); if( std::get<1>(r.key()) == 0 ) break; ++n; } cybozu_assert( n == 2 ); n = 0; c.keys("foo"); while( true ) { cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Keys); ASSERT_OK(r); if( std::get<1>(r.key()) == 0 ) break; ++n; } cybozu_assert( n == 1 ); n = 0; c.keys("zzzz"); while( true ) { cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Keys); ASSERT_OK(r); if( std::get<1>(r.key()) == 0 ) break; ++n; } cybozu_assert( n == 1 ); n = 0; c.keys("b"); while( true ) { cybozu_assert( c.get_response(r) ); ASSERT_COMMAND(r, Keys); ASSERT_OK(r); if( std::get<1>(r.key()) == 0 ) break; ++n; } cybozu_assert( n == 0 ); } void print_usage() { std::cout << "Usage: protocol_binary.exe [SERVER [PORT]]\n" "Environment options:\n" " YRMCDS_SERVER : the name of a yrmcds server.\n" " used only when `SERVER` is unspecified.\n" " YRMCDS_PORT : the port number of a yrmcds server.\n" " used only when `PORT` is unspecified.\n" << std::flush; } // main bool optparse(int argc, char** argv) { if( argc > 3 ) { print_usage(); return false; } g_server = getenv("YRMCDS_SERVER"); const char* env_port = getenv("YRMCDS_PORT"); if( env_port != nullptr ) g_port = std::stoi(env_port); if( argc >= 2 ) g_server = argv[1]; if( argc >= 3 ) g_port = std::stoi(argv[2]); if( g_server == nullptr ) { std::cout << "No server specified." << std::endl; print_usage(); return false; } if( g_port <= 0 || g_port > 65535 ) { std::cout << "Invalid port number: " << g_port << std::endl; return false; } int s = connect_server(); if( s == -1 ) { std::cout << "Failed to connect to " << g_server << std::endl; return false; } ::close(s); return true; } TEST_MAIN(optparse);
28.912471
81
0.561271
arosh
15273e260231d1dafab1344261f2c551974f7576
81
cpp
C++
src/components/output/outputcomp.cpp
rthrh/imageflow
e4be67f0b19c67fcc597d19fb54ae076453b3202
[ "Unlicense" ]
3
2019-09-11T16:48:48.000Z
2022-03-14T05:47:35.000Z
src/components/output/outputcomp.cpp
rthrh/imageflow
e4be67f0b19c67fcc597d19fb54ae076453b3202
[ "Unlicense" ]
5
2018-02-17T17:58:30.000Z
2018-03-06T10:07:06.000Z
src/components/output/outputcomp.cpp
rthrh/imageflow
e4be67f0b19c67fcc597d19fb54ae076453b3202
[ "Unlicense" ]
1
2018-02-15T19:29:25.000Z
2018-02-15T19:29:25.000Z
#include "outputcomp.h" template <class... T> OutputComp<T...>::OutputComp() {}
16.2
33
0.654321
rthrh
15281d5758ca44b9322fa7612a3bdbbdc406deb2
29,014
cc
C++
src/enc/lossless/backward_references_cost_enc.cc
RReverser/libwebp2
c90b5b476004c9a98731ae1c175cebab5de50fbf
[ "Apache-2.0" ]
4
2020-11-10T17:46:57.000Z
2022-03-22T06:24:17.000Z
src/enc/lossless/backward_references_cost_enc.cc
RReverser/libwebp2
c90b5b476004c9a98731ae1c175cebab5de50fbf
[ "Apache-2.0" ]
null
null
null
src/enc/lossless/backward_references_cost_enc.cc
RReverser/libwebp2
c90b5b476004c9a98731ae1c175cebab5de50fbf
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. // ----------------------------------------------------------------------------- // // Improves a given set of backward references by analyzing its bit cost. // The algorithm is similar to the Zopfli compression algorithm but tailored to // images. // // Author: Vincent Rabaud (vrabaud@google.com) // #include <cassert> #include "src/common/lossless/color_cache.h" #include "src/dsp/lossless/lossless_common.h" #include "src/enc/lossless/backward_references_enc.h" #include "src/enc/lossless/histogram_enc.h" #include "src/enc/lossless/losslessi_enc.h" #include "src/enc/symbols_enc.h" namespace WP2L { static void ConvertPopulationCountTableToBitEstimates( int num_symbols, const uint32_t population_counts[], double output[]) { uint32_t sum = 0; int nonzeros = 0; int i; for (i = 0; i < num_symbols; ++i) { sum += population_counts[i]; if (population_counts[i] > 0) { ++nonzeros; } } if (nonzeros <= 1) { memset(output, 0, num_symbols * sizeof(*output)); } else { const double logsum = WP2Log2(sum); for (i = 0; i < num_symbols; ++i) { output[i] = logsum - WP2Log2(population_counts[i]); } } } // Class storing the cost of each symbol in bits ,based on its count. class CostModel : public CountsBuffer<double> { public: // 'refs' must not have its distance modified by DistanceToPlaneCode. WP2Status Build(uint32_t width, const LosslessSymbolsInfo& info, const BackwardRefs& refs) { width_ = width; HistogramSet histo; WP2_CHECK_ALLOC_OK(histo.Allocate(/*size=*/1, info)); WP2_CHECK_STATUS(BuildHistograms(width, /*height=*/0, /*histo_bits=*/0, info, refs, &histo)); has_alpha_ = LosslessSymbolsInfo::HasAlpha(info); is_label_image_ = LosslessSymbolsInfo::IsLabelImage(info); for (size_t i = 0; i < kSymbolNum; ++i) { ConvertPopulationCountTableToBitEstimates( histo.symbols_info_->GetMaxRange(i), histo.histograms_[0]->counts_[i], counts_[i]); } return WP2_STATUS_OK; } inline double GetLiteralCost(const int16_t* const v) const { return counts_[kSymbolType][kSymbolTypeLiteral] + (has_alpha_ ? counts_[kSymbolA][MakeIndex(v[0])] : 0.) + (is_label_image_ ? 0. : counts_[kSymbolR][MakeIndex(v[1])] + counts_[kSymbolB][MakeIndex(v[3])]) + counts_[kSymbolG][MakeIndex(v[2])]; } inline double GetCacheCost(uint32_t idx) const { return counts_[kSymbolType][kSymbolTypeCacheIdx] + counts_[kSymbolCache][idx]; } inline double GetLengthCost(uint32_t length) const { int code, extra_bits; WP2LPrefixEncodeBits(length, &code, &extra_bits); return counts_[kSymbolType][kSymbolTypeCopy] + counts_[kSymbolLen][code] + extra_bits; } inline double GetDistanceCost(uint32_t distance) const { distance = DistanceToPlaneCode(width_, distance); int code, extra_bits; WP2LPrefixEncodeBits(distance, &code, &extra_bits); return counts_[kSymbolDist][code] + extra_bits; } private: uint32_t width_; bool has_alpha_; bool is_label_image_; }; // Describes how a segment of pixels of length 'len' is represented (copy ...) struct Segment { uint16_t len; SymbolType mode; }; static inline void AddSingleLiteralWithCostModel( const int16_t* const argb, ColorCache* const color_cache, const CostModel& cost_model, int idx, int use_color_cache, float prev_cost, float* const cost, Segment* const segments) { double cost_val = prev_cost; const int16_t* const color = &argb[4 * idx]; uint32_t tag; if (use_color_cache && color_cache->Contains(color, &tag)) { // use_color_cache is true and color_cache contains color const double mul0 = 0.68; cost_val += cost_model.GetCacheCost(tag) * mul0; if (cost[idx] > cost_val) { cost[idx] = (float)cost_val; // Only one is inserted. segments[idx].len = 1; segments[idx].mode = kSymbolTypeCacheIdx; } } else { const double mul1 = 0.82; if (use_color_cache) color_cache->Insert(color, /*index_ptr=*/nullptr); cost_val += cost_model.GetLiteralCost(color) * mul1; if (cost[idx] > cost_val) { cost[idx] = (float)cost_val; // Only one is inserted. segments[idx].len = 1; segments[idx].mode = kSymbolTypeLiteral; } } } // ----------------------------------------------------------------------------- // CostManager and interval handling // Empirical value to avoid high memory consumption but good for performance. #define COST_CACHE_INTERVAL_SIZE_MAX 500 // To perform backward reference every pixel at 'index' is considered and // the cost for the kMaxLZ77Length following pixels computed. Those following // pixels at index 'index' + k (k from 0 to kMaxLZ77Length) have a cost of: // cost_ = distance cost at index + GetLengthCost(cost_model, k) // and the minimum value is kept. GetLengthCost(cost_model, k) is cached in an // array of size kMaxLZ77Length. // Instead of performing kMaxLZ77Length comparisons per pixel, we keep track of // the minimal values using intervals of constant cost. // An interval is defined by the 'index' of the pixel that generated it and is // only useful in a range of indices from 'start' to 'end' (exclusive), i.e. it // contains the minimum value for pixels between 'start' and 'end'. Intervals // are stored in a linked list and ordered by 'start'. When a new interval has a // better value, old intervals are split or removed. There are therefore no // overlapping intervals. struct CostInterval : WP2Allocable { float cost; int start; int end; int index; CostInterval* previous; CostInterval* next; }; // The GetLengthCost(cost_model, k) are cached in a CostCacheInterval. typedef struct { double cost; int start; int end; // Exclusive. } CostCacheInterval; // This structure is in charge of managing intervals and costs. // It caches the different CostCacheInterval, caches the different // GetLengthCost(cost_model, k) in cost_cache_ and the CostInterval's (whose // count_ is limited by COST_CACHE_INTERVAL_SIZE_MAX). #define COST_MANAGER_MAX_FREE_LIST 10 class CostManager { public: CostManager() = default; ~CostManager() { Reset(); } bool Init(Segment* const segments, uint32_t num_pixels, const CostModel& cost_model); void Reset(); CostInterval* head_ = nullptr; int count_ = 0; // The number of stored intervals. WP2::VectorNoCtor<CostCacheInterval> cache_intervals_; size_t cache_intervals_size_ = 0; // Contains the GetLengthCost(cost_model, k). Size max: kMaxLZ77Length. WP2::VectorNoCtor<double> cost_cache_; WP2::Vector_f costs_; Segment* segments_ = nullptr; // Most of the time, we only need few intervals -> use a free-list, to avoid // fragmentation with small allocs in most common cases. CostInterval intervals_[COST_MANAGER_MAX_FREE_LIST]; CostInterval* free_intervals_ = nullptr; // These are regularly malloc'd remains. This list can't grow larger than than // size COST_CACHE_INTERVAL_SIZE_MAX - COST_MANAGER_MAX_FREE_LIST, note. CostInterval* recycled_intervals_ = nullptr; }; static void CostIntervalAddToFreeList(CostManager* const manager, CostInterval* const interval) { interval->next = manager->free_intervals_; manager->free_intervals_ = interval; } static int CostIntervalIsInFreeList(const CostManager* const manager, const CostInterval* const interval) { return (interval >= &manager->intervals_[0] && interval <= &manager->intervals_[COST_MANAGER_MAX_FREE_LIST - 1]); } static void CostManagerInitFreeList(CostManager* const manager) { int i; manager->free_intervals_ = NULL; for (i = 0; i < COST_MANAGER_MAX_FREE_LIST; ++i) { CostIntervalAddToFreeList(manager, &manager->intervals_[i]); } } static void DeleteIntervalList(CostManager* const manager, const CostInterval* interval) { while (interval != NULL) { const CostInterval* const next = interval->next; if (!CostIntervalIsInFreeList(manager, interval)) { WP2Free((void*)interval); } // else: do nothing interval = next; } } void CostManager::Reset() { costs_.reset(); cache_intervals_.reset(); // Clear the interval lists. DeleteIntervalList(this, head_); head_ = nullptr; DeleteIntervalList(this, recycled_intervals_); recycled_intervals_ = nullptr; // Reset pointers, count_ and cache_intervals_size_. count_ = 0; cache_intervals_size_ = 0; cost_cache_.reset(); segments_ = nullptr; memset(intervals_, 0, sizeof(intervals_)); free_intervals_ = nullptr; CostManagerInitFreeList(this); } bool CostManager::Init(Segment* const segments, uint32_t num_pixels, const CostModel& cost_model) { Reset(); segments_ = segments; const uint32_t cost_cache_size = std::min(kMaxLZ77Length, num_pixels); if (!cost_cache_.resize(cost_cache_size)) return false; // Fill in the cost_cache_. cache_intervals_size_ = 1; cost_cache_[0] = cost_model.GetLengthCost(0); for (uint32_t i = 1; i < cost_cache_size; ++i) { cost_cache_[i] = cost_model.GetLengthCost(i); // Get the number of bound intervals. if (cost_cache_[i] != cost_cache_[i - 1]) { ++cache_intervals_size_; } } // With the current cost model, we usually have below 20 intervals. // The worst case scenario with a cost model would be if every length has a // different cost, hence kMaxLZ77Length but that is impossible with the // current implementation that spirals around a pixel. assert(cache_intervals_size_ <= kMaxLZ77Length); if (!cache_intervals_.resize(cache_intervals_size_)) { Reset(); return false; } // Fill in the cache_intervals_. { CostCacheInterval* cur = cache_intervals_.data(); // Consecutive values in cost_cache_ are compared and if a big enough // difference is found, a new interval is created and bounded. cur->start = 0; cur->end = 1; cur->cost = cost_cache_[0]; for (uint32_t i = 1; i < cost_cache_size; ++i) { const double cost_val = cost_cache_[i]; if (cost_val != cur->cost) { ++cur; // Initialize an interval. cur->start = i; cur->cost = cost_val; } cur->end = i + 1; } } if (!costs_.resize(num_pixels)) { Reset(); return false; } // Set the initial costs_ high for every pixel as we will keep the minimum. std::fill(costs_.begin(), costs_.end(), 1e38f); return true; } // Given the cost and the position that define an interval, update the cost at // pixel 'i' if it is smaller than the previously computed value. static inline void UpdateCost(CostManager* const manager, int i, int position, float cost) { const uint32_t k = i - position; assert(i >= position && k < kMaxLZ77Length); if (manager->costs_[i] > cost) { manager->costs_[i] = cost; // Force the mode to be a copy. manager->segments_[i].len = (uint16_t)(k + 1); manager->segments_[i].mode = kSymbolTypeCopy; } } // Given the cost and the position that define an interval, update the cost for // all the pixels between 'start' and 'end' excluded. static inline void UpdateCostPerInterval(CostManager* const manager, int start, int end, int position, float cost) { int i; for (i = start; i < end; ++i) UpdateCost(manager, i, position, cost); } // Given two intervals, make 'prev' be the previous one of 'next' in 'manager'. static inline void ConnectIntervals(CostManager* const manager, CostInterval* const prev, CostInterval* const next) { if (prev != NULL) { prev->next = next; } else { manager->head_ = next; } if (next != NULL) next->previous = prev; } // Pop an interval in the manager. static inline void PopInterval(CostManager* const manager, CostInterval* const interval) { if (interval == NULL) return; ConnectIntervals(manager, interval->previous, interval->next); if (CostIntervalIsInFreeList(manager, interval)) { CostIntervalAddToFreeList(manager, interval); } else { // recycle regularly malloc'd intervals too interval->next = manager->recycled_intervals_; manager->recycled_intervals_ = interval; } --manager->count_; assert(manager->count_ >= 0); } // Update the cost at index i by going over all the stored intervals that // overlap with i. // If 'do_clean_intervals' is set to something different than 0, intervals that // end before 'i' will be popped. static inline void UpdateCostAtIndex(CostManager* const manager, int i, int do_clean_intervals) { CostInterval* current = manager->head_; while (current != NULL && current->start <= i) { CostInterval* const next = current->next; if (current->end <= i) { if (do_clean_intervals) { // We have an outdated interval, remove it. PopInterval(manager, current); } } else { UpdateCost(manager, i, current->index, current->cost); } current = next; } } // Given a current orphan interval and its previous interval, before // it was orphaned (which can be NULL), set it at the right place in the list // of intervals using the start_ ordering and the previous interval as a hint. static inline void PositionOrphanInterval(CostManager* const manager, CostInterval* const current, CostInterval* previous) { assert(current != NULL); if (previous == NULL) previous = manager->head_; while (previous != NULL && current->start < previous->start) { previous = previous->previous; } while (previous != NULL && previous->next != NULL && previous->next->start < current->start) { previous = previous->next; } if (previous != NULL) { ConnectIntervals(manager, current, previous->next); } else { ConnectIntervals(manager, current, manager->head_); } ConnectIntervals(manager, previous, current); } // Insert an interval in the list contained in the manager by starting at // interval_in as a hint. The intervals are sorted by start_ value. static inline WP2Status InsertInterval(CostManager* const manager, CostInterval* const interval_in, float cost, int position, int start, int end) { CostInterval* interval_new; if (start >= end) return WP2_STATUS_OK; if (manager->count_ >= COST_CACHE_INTERVAL_SIZE_MAX) { // Serialize the interval if we cannot store it. UpdateCostPerInterval(manager, start, end, position, cost); return WP2_STATUS_OK; } if (manager->free_intervals_ != NULL) { interval_new = manager->free_intervals_; manager->free_intervals_ = interval_new->next; } else if (manager->recycled_intervals_ != NULL) { interval_new = manager->recycled_intervals_; manager->recycled_intervals_ = interval_new->next; } else { // malloc for good interval_new = new (WP2Allocable::nothrow) CostInterval(); WP2_CHECK_ALLOC_OK(interval_new != nullptr); } interval_new->cost = cost; interval_new->index = position; interval_new->start = start; interval_new->end = end; PositionOrphanInterval(manager, interval_new, interval_in); ++manager->count_; return WP2_STATUS_OK; } // Given a new cost interval defined by its start at position, its length value // and distance_cost, add its contributions to the previous intervals and costs. // If handling the interval or one of its subintervals becomes to heavy, its // contribution is added to the costs right away. static inline WP2Status PushInterval(CostManager* const manager, double distance_cost, int position, int len) { size_t i; CostInterval* interval = manager->head_; CostInterval* interval_next; const CostCacheInterval* const cost_cache_intervals = manager->cache_intervals_.data(); // If the interval is small enough, no need to deal with the heavy // interval logic, just serialize it right away. This constant is empirical. const int kSkipDistance = 10; if (len < kSkipDistance) { int j; for (j = position; j < position + len; ++j) { const uint32_t k = j - position; float cost_tmp; assert(j >= position && k < kMaxLZ77Length); cost_tmp = (float)(distance_cost + manager->cost_cache_[k]); if (manager->costs_[j] > cost_tmp) { manager->costs_[j] = cost_tmp; // Force the mode to be a copy. manager->segments_[j].len = (uint16_t)(k + 1); manager->segments_[j].mode = kSymbolTypeCopy; } } return WP2_STATUS_OK; } for (i = 0; i < manager->cache_intervals_size_ && cost_cache_intervals[i].start < len; ++i) { // Define the intersection of the ith interval with the new one. int start = position + cost_cache_intervals[i].start; const int end = position + (cost_cache_intervals[i].end > len ? len : cost_cache_intervals[i].end); const float cost = (float)(distance_cost + cost_cache_intervals[i].cost); for (; interval != NULL && interval->start < end; interval = interval_next) { interval_next = interval->next; // Make sure we have some overlap if (start >= interval->end) continue; if (cost >= interval->cost) { // When intervals are represented, the lower, the better. // [**********************************************************[ // start end // [----------------------------------[ // interval->start_ interval->end_ // If we are worse than what we already have, add whatever we have so // far up to interval. const int start_new = interval->end; WP2_CHECK_STATUS(InsertInterval(manager, interval, cost, position, start, interval->start)); start = start_new; if (start >= end) break; continue; } if (start <= interval->start) { if (interval->end <= end) { // [----------------------------------[ // interval->start_ interval->end_ // [**************************************************************[ // start end // We can safely remove the old interval as it is fully included. PopInterval(manager, interval); } else { // [------------------------------------[ // interval->start_ interval->end_ // [*****************************[ // start end interval->start = end; break; } } else { if (end < interval->end) { // [--------------------------------------------------------------[ // interval->start_ interval->end_ // [*****************************[ // start end // We have to split the old interval as it fully contains the new one. const int end_original = interval->end; interval->end = start; WP2_CHECK_STATUS(InsertInterval(manager, interval, interval->cost, interval->index, end, end_original)); interval = interval->next; break; } else { // [------------------------------------[ // interval->start_ interval->end_ // [*****************************[ // start end interval->end = start; } } } // Insert the remaining interval from start to end. WP2_CHECK_STATUS( InsertInterval(manager, interval, cost, position, start, end)); } return WP2_STATUS_OK; } // Optimizes the BackwardReferences based on the distance code. static WP2Status BackwardReferencesHashChainDistanceOnly( uint32_t width, uint32_t height, const int16_t* const argb, const LosslessSymbolsInfo& symbols_info, const HashChain& hash_chain, const CacheConfig& cache_config, const BackwardRefs& refs, Segment* const segments) { const uint32_t num_pixels = width * height; CostModel cost_model; uint32_t offset_prev = -1, len_prev = -1; double offset_cost = -1; int first_offset_is_constant = -1; // initialized with 'impossible' value uint32_t reach = 0; WP2_CHECK_ALLOC_OK(cost_model.Allocate(&symbols_info)); const bool use_color_cache = (cache_config.type != CacheType::kNone); ColorCachePtr color_cache; WP2_CHECK_STATUS(color_cache.Init(cache_config)); WP2_CHECK_STATUS(cost_model.Build(width, symbols_info, refs)); CostManager cost_manager; WP2_CHECK_ALLOC_OK(cost_manager.Init(segments, num_pixels, cost_model)); // We loop one pixel at a time, but store all currently best points to // non-processed locations from this point. segments[0].len = 1; segments[0].mode = kSymbolTypeLiteral; // Add first pixel as literal. AddSingleLiteralWithCostModel(argb, color_cache.get(), cost_model, 0, use_color_cache, 0.f, cost_manager.costs_.data(), segments); for (size_t i = 1; i < num_pixels; ++i) { const float prev_cost = cost_manager.costs_[i - 1]; uint32_t offset, len; hash_chain.FindCopy(i, &offset, &len); // Try adding the pixel as a literal. AddSingleLiteralWithCostModel(argb, color_cache.get(), cost_model, i, use_color_cache, prev_cost, cost_manager.costs_.data(), segments); // If we are dealing with a non-literal. if (len >= 2) { if (offset != offset_prev) { offset_cost = cost_model.GetDistanceCost(offset); first_offset_is_constant = 1; WP2_CHECK_STATUS( PushInterval(&cost_manager, prev_cost + offset_cost, i, len)); } else { assert(offset_cost >= 0); assert(len_prev >= 0); assert(first_offset_is_constant == 0 || first_offset_is_constant == 1); // Instead of considering all contributions from a pixel i by calling: // PushInterval(cost_manager, prev_cost + offset_cost, i, len); // we optimize these contributions in case offset_cost stays the same // for consecutive pixels. This describes a set of pixels similar to a // previous set (e.g. constant color regions). if (first_offset_is_constant) { reach = i - 1 + len_prev - 1; first_offset_is_constant = 0; } if (i + len - 1 > reach) { // We can only be go further with the same offset if the previous // length was maxed, hence len_prev == len == kMaxLZ77Length. // TODO(vrabaud): bump i to the end right away (insert cache and // update cost). // TODO(vrabaud): check if one of the points in between does not have // a lower cost. // Already consider the pixel at "reach" to add intervals that are // better than whatever we add. uint32_t offset_j, len_j = 0; uint32_t j; assert(len == kMaxLZ77Length || len == num_pixels - i); // Figure out the last consecutive pixel within [i, reach + 1] with // the same offset. for (j = i; j <= reach; ++j) { hash_chain.FindCopy(j + 1, &offset_j, &len_j); if (offset_j != offset) { hash_chain.FindCopy(j, &offset_j, &len_j); break; } } // Update the cost at j - 1 and j. UpdateCostAtIndex(&cost_manager, j - 1, 0); UpdateCostAtIndex(&cost_manager, j, 0); WP2_CHECK_STATUS( PushInterval(&cost_manager, cost_manager.costs_[j - 1] + offset_cost, j, len_j)); reach = j + len_j - 1; } } } UpdateCostAtIndex(&cost_manager, i, 1); offset_prev = offset; len_prev = len; } return WP2_STATUS_OK; } // We pack the path at the end of *segments and return // a pointer to this part of the array. Example: // segments = [1x2xx3x2] => packed [1x2x1232], chosen_path = [1232] static void TraceBackwards(Segment* const segments, size_t segments_size, Segment** const chosen_path, size_t* const chosen_path_size) { Segment* path = segments + segments_size; Segment* cur = segments + segments_size - 1; while (cur >= segments) { --path; *path = *cur; cur -= cur->len; } *chosen_path = path; *chosen_path_size = (size_t)(segments + segments_size - path); } static WP2Status BackwardReferencesHashChainFollowChosenPath( const int16_t* const argb, const CacheConfig& cache_config, const Segment* const chosen_path, uint32_t chosen_path_size, const HashChain& hash_chain, BackwardRefs* const refs, bool* const check_histogram) { const bool use_color_cache = (cache_config.type != CacheType::kNone); ColorCachePtr color_cache; WP2_CHECK_STATUS(color_cache.Init(cache_config)); refs->Clear(); for (uint32_t ix = 0, i = 0; ix < chosen_path_size; ++ix) { const Segment& seg = chosen_path[ix]; if (seg.mode == kSymbolTypeCopy) { // TODO(vrabaud) do not go through here when seg.len_ == 1 const uint32_t len = seg.len; const uint32_t offset = hash_chain.FindOffset(i); WP2_CHECK_STATUS(refs->CursorAdd(PixelMode::CreateCopy(offset, len))); if (use_color_cache) { for (uint32_t k = 0; k < len; ++k) { color_cache->Insert(&argb[4 * (i + k)], /*index_ptr=*/nullptr); } } i += len; } else if (seg.mode == kSymbolTypeCacheIdx) { uint32_t tag; if (!color_cache->Contains(&argb[4 * i], &tag)) { *check_histogram = false; break; } WP2_CHECK_STATUS(refs->CursorAdd( PixelMode::CreateCacheIdx(tag, color_cache->IndexRange()))); color_cache->Insert(&argb[4 * i], /*index_ptr=*/nullptr); ++i; } else { assert(seg.mode == kSymbolTypeLiteral); if (use_color_cache) { color_cache->Insert(&argb[4 * i], /*index_ptr=*/nullptr); } WP2_CHECK_STATUS(refs->CursorAdd(PixelMode::CreateLiteral(&argb[4 * i]))); ++i; } } return WP2_STATUS_OK; } // Returns 1 on success. extern WP2Status BackwardReferencesTraceBackwards( uint32_t width, uint32_t height, const int16_t* const argb, const LosslessSymbolsInfo& symbols_info, const HashChain& hash_chain, const CacheConfig& cache_config, const BackwardRefs& refs_src, BackwardRefs* const refs_dst, bool* const check_histogram); WP2Status BackwardReferencesTraceBackwards( uint32_t width, uint32_t height, const int16_t* const argb, const LosslessSymbolsInfo& symbols_info, const HashChain& hash_chain, const CacheConfig& cache_config, const BackwardRefs& refs_src, BackwardRefs* const refs_dst, bool* const check_histogram) { const uint32_t num_pixels = width * height; WP2::VectorNoCtor<Segment> segments; *check_histogram = true; WP2_CHECK_ALLOC_OK(segments.resize(num_pixels)); WP2_CHECK_STATUS(BackwardReferencesHashChainDistanceOnly( width, height, argb, symbols_info, hash_chain, cache_config, refs_src, segments.data())); Segment* chosen_path = nullptr; size_t chosen_path_size = 0; TraceBackwards(segments.data(), num_pixels, &chosen_path, &chosen_path_size); WP2_CHECK_STATUS(BackwardReferencesHashChainFollowChosenPath( argb, cache_config, chosen_path, chosen_path_size, hash_chain, refs_dst, check_histogram)); return WP2_STATUS_OK; } } // namespace WP2L
37.729519
80
0.63135
RReverser
15286358e4095be124b0b5c2636f233eaa165e47
1,627
cpp
C++
Source/Engine/src/stdlib/system/sldebug.cpp
DatZach/Swift
b0c6f9c87e8c8dfe8a19dedc4dd57081fa5cdef7
[ "MIT" ]
null
null
null
Source/Engine/src/stdlib/system/sldebug.cpp
DatZach/Swift
b0c6f9c87e8c8dfe8a19dedc4dd57081fa5cdef7
[ "MIT" ]
null
null
null
Source/Engine/src/stdlib/system/sldebug.cpp
DatZach/Swift
b0c6f9c87e8c8dfe8a19dedc4dd57081fa5cdef7
[ "MIT" ]
1
2021-10-30T20:43:01.000Z
2021-10-30T20:43:01.000Z
/* * console.cpp * Swift Standard Library * Console */ #include <iostream> #include <StdLib/SlApi.hpp> namespace StdLib { namespace Debug { void WriteLine(Util::Stack<Vm::Variant*>& stack, Vm::Class* parent) { std::cout << stack.Pop()->Cast(Vm::Variant::Type::String).String() << std::endl; } void Write(Util::Stack<Vm::Variant*>& stack, Vm::Class* parent) { std::cout << stack.Pop()->Cast(Vm::Variant::Type::String).String(); } void Log(Util::Stack<Vm::Variant*>& stack, Vm::Class* parent) { ::Log << stack.Pop()->Cast(Vm::Variant::Type::String).String() << lendl; } void Trace(Util::Stack<Vm::Variant*>& stack, Vm::Class* parent) { ::Trace << stack.Pop()->Cast(Vm::Variant::Type::String).String() << lendl; } void Warn(Util::Stack<Vm::Variant*>& stack, Vm::Class* parent) { ::Warn << stack.Pop()->Cast(Vm::Variant::Type::String).String() << lendl; } void Error(Util::Stack<Vm::Variant*>& stack, Vm::Class* parent) { ::Error << stack.Pop()->Cast(Vm::Variant::Type::String).String() << lendl; } /*! class Debug methods WriteLine 1 static Write 1 static Log 1 static Trace 1 static Warn 1 static Error 1 static */ void Install() { // Debug class Vm::Class debugClass; // Methods debugClass.AddMethod("WriteLine", WriteLine, 1); debugClass.AddMethod("Write", Write, 1); debugClass.AddMethod("Log", Log, 1); debugClass.AddMethod("Trace", Trace, 1); debugClass.AddMethod("Warn", Warn, 1); debugClass.AddMethod("Error", Error, 1); VirtualMachine.AddClass("Debug", debugClass); } } }
22.597222
83
0.618931
DatZach